我如何通过一个自定义类型的对象从一个活动到另一个使用类意图的putExtra()方法?


当前回答

谢谢你的帮助,但我发现了一个可选的解决方案

 public class getsetclass implements Serializable {
        private int dt = 10;
    //pass any object, drwabale 
        public int getDt() {
            return dt;
        }

        public void setDt(int dt) {
            this.dt = dt;
        }
    }

活动一

getsetclass d = new getsetclass ();
                d.setDt(50);
                LinkedHashMap<String, Object> obj = new LinkedHashMap<String, Object>();
                obj.put("hashmapkey", d);
            Intent inew = new Intent(SgParceLableSampelActivity.this,
                    ActivityNext.class);
            Bundle b = new Bundle();
            b.putSerializable("bundleobj", obj);
            inew.putExtras(b);
            startActivity(inew);

在活动2中获取数据

 try {  setContentView(R.layout.main);
            Bundle bn = new Bundle();
            bn = getIntent().getExtras();
            HashMap<String, Object> getobj = new HashMap<String, Object>();
            getobj = (HashMap<String, Object>) bn.getSerializable("bundleobj");
            getsetclass  d = (getsetclass) getobj.get("hashmapkey");
        } catch (Exception e) {
            Log.e("Err", e.getMessage());
        }

其他回答

您需要将对象序列化为某种字符串表示形式。一种可能的字符串表示是JSON,如果你问我,在android中序列化JSON最简单的方法之一是通过谷歌GSON。

在这种情况下,你只需要输入字符串返回值from (new Gson()).toJson(myObject);并检索字符串值并使用fromJson将其转换回您的对象。

但是,如果您的对象不是非常复杂,那么可能不值得这样做,您可以考虑传递对象的单独值。

Start another activity from this activity pass parameters via Bundle Object

Intent intent = new Intent(this, YourActivity.class);
Intent.putExtra(AppConstants.EXTRAS.MODEL, cModel);
startActivity(intent);
Retrieve on another activity (YourActivity)

ContentResultData cModel = getIntent().getParcelableExtra(AppConstants.EXTRAS.MODEL);

最简单的java方法是:在你的pojo/model类中实现serializable

推荐用于Android的性能视图:使模型可封装

在臂膀上

在build.gradle中添加kotlin扩展。

apply plugin: 'kotlin-android-extensions'

android {
    androidExtensions {
        experimental = true
   }
}

然后像这样创建数据类。

@Parcelize
data class Sample(val id: Int, val name: String) : Parcelable

传递带有意图的对象

val sample = Sample(1,"naveen")

val intent = Intent(context, YourActivity::class.java)
    intent.putExtra("id", sample)
    startActivity(intent)

获取带有意图的对象

val sample = intent.getParcelableExtra("id")

对于你知道要在应用程序中传递数据的情况,使用“全局变量”(比如静态类)

以下是Dianne Hackborn (hackbod -谷歌安卓软件工程师)对此事的看法:

For situations where you know the activities are running in the same process, you can just share data through globals. For example, you could have a global HashMap<String, WeakReference<MyInterpreterState>> and when you make a new MyInterpreterState come up with a unique name for it and put it in the hash map; to send that state to another activity, simply put the unique name into the hash map and when the second activity is started it can retrieve the MyInterpreterState from the hash map with the name it receives.