0

I created a class Telnet and I inicialize it on the Mainactivity. Now I want to access the telnet I inicialized in the MainActivity in all other activities of the project. What I am doing is creating a get function:

public Telnet getMyTelnet() {
    return telnet;
}

And then just call it wherever I want. When I call it in fragments I do it like this:

MainActivity activity = (MainActivity) getActivity();
            telnet = activity.getMyTelnet();

The problem is when I need it in another activity. How can I do it? I tried this but no luck.

MainActivity a = new MainActivity ();
            telnet = a.getTelnet();
scottbear
  • 155
  • 1
  • 2
  • 10

2 Answers2

1

In android there are two ways to achieve send and receive objects bebtween Activities: they must:

  • Serializable (Implment object as Serializable)
    or
  • Parcelable (Implement object as Parcelable)

you will need to implement Parcelabel and add the following methods to the class

a constructor with a parcel as parameter

public Telnet(Parcel in) {
    readFromParcel(in);
}

override the writeToParcel method

 @Override
    public void writeToParcel(Parcel dest, int flags) {

        // write each field into the parcel. When we read from parcel, they
        // will come back in the same order
        dest.writeString(strVar); // to write your string variables
        dest.writeInt(intVar); // to write your int variables
    }

a method for read from Parcel

private void readFromParcel(Parcel in) {

    strVar= in.readString();
    intVar= in.readInt();
}

a parcel creator

public static final Parcelable.Creator CREATOR =
    new Parcelable.Creator() {
        public Telnet createFromParcel(Parcel in) {
            return new Telnet(in);
        }

        public Telnet[] newArray(int size) {
            return new Telnet[size];
        }
    };

@Override
    public int describeContents() {
        return 0;
    }

then your Telnet class is ready to be transfer to another activities.

Now use it: in the main act do:

Telnet obj = new Telnet();

// Set values etc.

Intent i = new Intent(this, MyActivity.class);
i.putExtra("your.package.Telnet", obj);

startActivity(i);

and in the second activity do:

@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        Bundle b = getIntent().getExtras();
        Telnet obj =
            b.getParcelable("your.package.Telnet");
    }
ΦXocę 웃 Пepeúpa ツ
  • 47,427
  • 17
  • 69
  • 97
  • How can I implement any of them? – scottbear Feb 07 '16 at 10:56
  • Your telnet class can implement any of them. But I am not sure if this is gonna solve your problem. – Sanjeet A Feb 07 '16 at 11:00
  • What you suggest? @SanjeetAjnabee – scottbear Feb 07 '16 at 11:02
  • As much as I can guess you are doing some connection/server related stuffs and this should be done on a service ( if my guess is right). And your activity can either bind to that service to get the telnet instance directly or broadcaat and intent may be option to perform tasks and get notified if service has done that. – Sanjeet A Feb 07 '16 at 11:08
  • You are right. This is a client server connection. On my Main Activity I create a telnet variable and then telnet = new Telnet(getApplicationContext()); telnet.connect_info(ip, port_int); telnet.execute() I define the IP and the port and then I just create the connection socket. Now to send for instance a message to the network I just telnet.send("some info"); . As long as I have the variable from MainActivity I am able to to use the telnet features. @SanjeetAjnabee – scottbear Feb 07 '16 at 11:13
  • please check the update, give a try and let me know – ΦXocę 웃 Пepeúpa ツ Feb 07 '16 at 11:21
  • I tried your solution but i get: java.lang.RuntimeException: Parcelable encountered IOException writing serializable object (name = com.rs.approbot.Telnet) @Xoce – scottbear Feb 07 '16 at 11:32
  • It will strongly suggest you to use the service approach. None of these are gonna solve your issue. You need a persistent connection to the server and from the activity you need the same connection to perform the tasks. You should use a service and perform the connection on the service then bind your activity which needs the telnet/connection instance and get that instance from the binder. – Sanjeet A Feb 07 '16 at 11:36
  • Can you explain how can I do that? @SanjeetAjnabee – scottbear Feb 07 '16 at 11:38
  • what is the error... can you post the trace- exception? – ΦXocę 웃 Пepeúpa ツ Feb 07 '16 at 11:38
  • I will. Another thing Wht is strVar and intVar and what are they for? – scottbear Feb 07 '16 at 11:40
  • strVar and intVar are the variables you have to define the Telnet Object... they are just an example for you, replace it with the fileds in your class.. – ΦXocę 웃 Пepeúpa ツ Feb 07 '16 at 11:41
  • ok, I add this method aswell **@Override public int describeContents() { return 0; }** – ΦXocę 웃 Пepeúpa ツ Feb 07 '16 at 11:49
  • Have a look on http://developer.android.com/guide/components/bound-services.html#Creating – Sanjeet A Feb 07 '16 at 11:50
  • Now it works but the telnet variable comes out null. Could I send you my class and you implement it please? – scottbear Feb 07 '16 at 11:52
  • jap, create a repo and share me the link – ΦXocę 웃 Пepeúpa ツ Feb 07 '16 at 11:56
  • https://github.com/Renato-Silva/AppRobot/blob/master/Telnet.java here you go – scottbear Feb 07 '16 at 11:59
1

create Telnet instance in MyActivity class as static. and right this method

punlic static Telnet telnet;

onCreate() {
 //initialise telnet
}

onResume() {
//initialise telnet if null;
}

onStop() {
//make telnet null
}
public static Telnet getTelnet() {
return telnet;

Let me know if it works or not

GvSharma
  • 2,632
  • 1
  • 24
  • 30
  • 1
    That's definitely not the recommended way for passing something between activities. Using a static in this case is just an ugly workaround. – reVerse Feb 07 '16 at 11:20
  • then you have to parcel the telnet instance and pass form one activity to another activity.. This can be done using Parcelable interface provided by Android – GvSharma Feb 07 '16 at 11:23
  • Exactly - and that's what you really should be doing. Not that hard to implement given the fact of so many [plugins](https://github.com/mcharmas/android-parcelable-intellij-plugin) or [libraries](https://github.com/johncarl81/parceler). – reVerse Feb 07 '16 at 11:27