Send not serializable data to new Activity

孤者浪人 提交于 2020-01-06 18:43:52

问题


I have not serializable data which I must sent to other Activity. I try to use Intent, but it's impossible.

Intent intent = new Intent(v.getContext(), UserDetailActivity.class);
intent.putExtra("class", user);
v.getContext().startActivity(intent);

How can I send the data from previous Activity to new Activity?


回答1:


I don't think you can do this bacause the ParseUser needs to implement either Parcelable or Serializable. You probably can't modify the class so this is what you can do:

  1. Create a wrapper class and reconstruct the ParseUser object. This wrapper needs to implement either Parcelable or Serializable. This might not always work.

  2. Extend the Application class here you create make a instance of the ParseUser object.

  3. Use a singleton.

1 can be tricky, 2 and 3 are easier.




回答2:


You can do this in two ways

1.the way you are doing it pass data via intent

To use the data send via this method use getIntent() method inside your second activity to which you want to pass the data this gives you the intent object and from thatvyou can reteive the data passing your key




回答3:


You can use Google Gson lib to convert and parse your objects as JSON formatted Strings, and pass them as normal Java Strings.

To convert an object to a JSON String:

ParseUser user=new ParseUser();
Gson gson = new Gson();
String json = gson.toJson(user); 

To parse it from JSON String back to object:

ParseUser user = gson.fromJson(json, ParseUser.class); 

An unrelated consideration, however, is whether passing ParseUser to another Activity is a good idea. It's possible that ParseUser cannot be serialized because of bad library design, OR because it's not supposed to be used this way. Since I don't use this particular library I cannot answer this question for you.




回答4:


If you can't Serialize or make the object Parcelable, routing it via the Application object or a static variable seems like the options.

You can also check out this library(https://github.com/noxiouswinter/gnlib_android/wiki/gnlauncher) I wrote to make this process of sending data to other Activities easier. It does not required the object to be serialized or implement Parcelable.



来源:https://stackoverflow.com/questions/16238049/send-not-serializable-data-to-new-activity

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!