问题
I am porting a program to Android. I have all my business logic on POJOs, so I need to use Activities as a mere front-end.
The problem is that I don't know how to share POJO between Activities; I've tried with this, but it doesn't work:
class Activity1 extends Activity{
Logic logic=new Logic();
public Logic getLogic(){
return logic
}
}
class Activity2 extends Activity{
Logic logic;
public void onCreate(Bundle savedInstanceState) {
main = (Activity1) findViewById((R.id.Activity1);
logic= main.getLogic();
}
}
Please note that POJO is not for sharing data, it actually contains business logic.
回答1:
main = (Activity1) findViewById((R.id.Activity1);
findViewById
works only for views! Its not meant to be used for activities as an activity is more like a "screen" and not a view itself.
If it is possible for your business logic to be a singleton, than I would recommend to make it so. It should be the easiest way.
回答2:
Your POJOs need to implement the Parcelable interface. Then you can put them inside Intents using putExtra and retrieve them in the next activity using getParcelableExtra. http://developer.android.com/reference/android/os/Parcelable.html
回答3:
If you start another activity from one activity by issuing an Intent you can pass POJOs by using the method putExtra()
. In the new activity where you receive the Intent you can then get the POJO back by using getXXXExtra()
where XXX ist the POJOs Type.
You should also have a look at http://developer.android.com/guide/topics/intents/intents-filters.html for a better understanding what Intents are and how they work together with Activities.
edit: as stated in the other answers here you'll have to implement either Parceable or Serializable Interface.
回答4:
I see that you are mixing two different things: findViewById
will get you a View
, not an Activity
like what you tried to do.
If your logic doesn't have to keep the state between activities, you can simply create a new object in both activities
Logic logic=new Logic();
If you want to keep the state, assuming it's a POJO, you can send the data via the intent when you are "calling" the second activity
intent.putExtra("MyInt", 123);
intent.putExtra("MyString", "hello!");
//...
and then in the second activity
intent.getIntExtra("MyInt"); // 123
intent.getStringExtra("MyString"); //"hello!"
Another option is to implemente parcelable . You have a sample in that link.
来源:https://stackoverflow.com/questions/5272276/android-how-to-share-a-pojo-between-activities