0

I`m trying to parse an object from my my main activity to a new activity that starts when the user clicks a button. I've seached the internet and found how to parse primative types and custom made classes that implements parceble or serilizable, but can't find any information on how to transfeer a raw object.

I'll write psuedo-code of what I`m trying to achive below:

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    loadConnectInfo();
    View connectButton = findViewById(R.id.connectButton);
    connectButton.setOnClickListener(this);
}

public void onClick(View v) {
    switch (v.getId()) {
        case R.id.connectButton:
            Intent i = new Intent(this, NewClass.class);
            Socket s = connect();  // this is the object I want to parse to to "NewClass"
            startActivity( i);
            break;
    }
Anne
  • 26,765
  • 9
  • 65
  • 71
John Snow
  • 5,214
  • 4
  • 37
  • 44

3 Answers3

1

You can't pass an object that is neither serializable nor parcelable between activities this way. What you probably want to do in this case is make your code that manages and interacts with the socket into a service and bind to that service in all the activities that need to use it.

Chris
  • 22,923
  • 4
  • 56
  • 50
1

Sometimes when I had to pass variable from one class to another I've used static variables in class which I deliver some objects. This will work but it is not recommended way to pass object in Android and you don't have guaranty that will work always.. Here you should check if your delivered object is not null of course.

public void onClick(View v) {
    switch (v.getId()) {
        case R.id.connectButton:
            Intent i = new Intent(this, NewClass.class);
            Socket s = connect();  // this is the object I want to parse to to "NewClass"
            //Here using static field of class you pass variable to NewClass
            //You can access this value in NewClass like that: NewClass.StaticSocket
            //Warning: This is not a standar android scheme but I tested and it works
            //with Date object
            NewClass.StaticSocket = s;
            startActivity( i);
            break;
    }

On second activity:

public void onCreate(Bundle savedInstanceState) {
        Log.i("StaticVar","NewClass.StaticSocket: "+ NewClass.StaticSocket.toString());
r.piesnikowski
  • 2,911
  • 1
  • 26
  • 32
0

There are already other posts about this:

What's the best way to share data between activities?

BTW, be careful: objects like sockets are not meant to be shared by bundles through the intent because they shouldn't be serialized. Maybe using a global state, like a singleton does it for you.

Community
  • 1
  • 1
Guille Polito
  • 882
  • 7
  • 3