I'm new in android and I have a question.
I want to have just one instance of a class in my whole android program so that it's attributes won't change during the program, but I also want to call it's methods in all my activities.
With some search I realized that I can pass my object via implementing class as Serializable or Parcelable. I did this but I got following error:
java.lang.RuntimeException: Parcelable encountered IOException writing serializable object
java.io.NotSerializableException: microsoft.aspnet.signalr.client.hubs.HubConnection
as you see one of my class attributes is HubConnection
which is in microsoft package and i can't make it Serializable.
What can I do to pass the object of SignalR class to another activities? And what are my options?
public class SignalR implements Serializable {
private HubConnection connection;
private HubProxy proxy;
//some methods
}
If you want a single instance of YourCustomClass throughout the application, you can do by keeping a reference of your custom class object in YourApplication class.
Create a class and extends it to Application class. Create setter and getter method in your application class to access the your custom class instance. Now you can access the your custom class instance from any where within your app and you don't have to pass the instance between activities.
public class YourApplicationClass extends Application{
private YourCustomClass yourCustomClass;
public YourCustomClass getYourCustomClass() {
if (yourCustomClass == null) {
yourCustomClass = new YourCustomClass();
}
return yourCustomClass;
}
public void setYourCustomClass(YourCustomClass yourCustomClass) {
this.yourCustomClass = yourCustomClass;
}
}
Don't forget to put android:name="YourApplicationClass" in your manifest file.
<application
......
android:name=".YourApplicationClass"
....... >
Now to access the object from your activity, say MainActivity you would write something like -
@override
protected void onCreate(Bundle savedInstanceState) {
YourApplicationClass app = (YourApplicationClass) getApplication();
YourCustomClass yourCustomInstance = app.getYourCustomClass();
}