Reputation: 324
I want to pass an object to a new activity from MainActivity
NetworkHandler nH=new NetworkHandler();
nH
is my own created class i want to send this object to a new activity
Upvotes: 0
Views: 744
Reputation: 1708
if NetworkHandler is Serializable you can serialize object and pass it to another Activity
class NetworkHandler implements Serializable{
....
}
and pass it to another activity in this way
Bundle bundleObject = new Bundle();
Intent i = new Intent(this,SecondActivity.class);
bundleObject.putSerializable(KEY, (Serializable) new NetworkHandler ());
i.putExtras(bundleObject);
startActivity(i);
in second activity onCreate get objet
Bundle bundleObject = getIntent().getExtras();
NetworkHandler nh = (NetworkHandler)
bundleObject.getSerializable
(KEY);
You can also Implement Parcelable interface to NetworkHandler.
Upvotes: 0
Reputation: 15336
Two possible answers
You Can't: Because you can't pass objects from one activity to another (until and unless it is Parcelable) in android
You Can: You can use shared preferences
to pass primitive data from one activity to another OR you can use single instance (singleton) class to set/get objects
from one place to another.
Upvotes: 1
Reputation: 390
You can create a class that extends Application class and create a singleton of that object inside it. This way you can access this object in all of your activity.
public class GlobalClass extends Application {
NetworkHandler nH = null;
public NetworkHandler getNetworkHandler() {
if (nH == null) {
nH = new NetworkHandler();
}
return nH;
}
}
in your AndroidManifest.xml mention the name your class
<application
android:name=".GlobalClass " >
You can access this object in any class using following code.
GlobalClass gObj = (GlobalClass) this.getApplication();
NetworkHandler nH = gObj.getNetworkHandler()
Upvotes: 0
Reputation: 366
If it is to do with network it should really be on its own thread.
However I would probably keep a handle to it in the application
of my app, that way it can be used on all activities.
Upvotes: 0
Reputation: 1916
When starting new activity, your intent can carry data:
public void sendMessage(View view) {
Intent intent = new Intent(this, DisplayMessageActivity.class);
EditText editText = (EditText) findViewById(R.id.edit_message);
String message = editText.getText().toString();
intent.putExtra(EXTRA_MESSAGE, message);
}
The problem is, that intent can carry only primitive, Serializable
or Parcelable
data types. If you have non-serializable objects, like network sockets, you can't send them via Intent
extras. In such case you may want to start a Service
holding your complex data (sockets, resource handlers, etc) and bind to that service in new activity.
Check out those resources:
Upvotes: 0