Steve Steve - 17 days ago 5
Android Question

Get string from one class to another class in Android?

I need to get the string variable from one class of my project to another class,

in First class, I made a string type variable and that is Global, like this:
the name of class is firstclass

public String firstClassVar;


and I am assigning the value to it in this method

public String requestForServerData(String strURL) throws IOException, UnknownHostException, IllegalArgumentException, Exception {
//additional code
firstClassVar = myObject.getString("values");
//additional code
}


Now in second class, I am doing something like this:

public firstclass getVar;

public void method{
String secondClassVar;
secondClassVar=getVar.firstClassVar;
}


By doing this it crashes. I have done another thing in firstclass that is

public String getStringPublically() {
return firstClassVar;
}


and for accessing it another class I am doing like this

secondClassVar =getVar.getStringPublically();


and by doing this it also crashes the app.

Now I am bit new to Android, and don't know the basic way to access the string from another class.

Answer

You can use SharedPreferences to set/get values in any class you want. Here is a good topic about it

Comments