I'm a newbie creating a unit converter. I have two classes, I have this method in the first class:
public String cardName;
public String StartConversion(View view){
Intent intent = new Intent(this, ConversionActivity.class);
startActivity(intent);
return cardName = view.getResources().getResourceEntryName(view.getId());
}
I would like to get and use the cardName's value in my second class, so:
MainActivity myObj = new MainActivity();
Toast.makeText(getApplicationContext(), "cardName: " + myObj.cardName, Toast.LENGTH_LONG).show();
But this doesn't work. I know local variables are only accessible inside their scope so I did this instead. They say you can only access it if you make it a class member, that does work but then it has a NULL value.
Typically, you'd a) create some class, b) make class members "private", then c) expose those members with getter and setter methods .
EXAMPLE:
public class MyClass {
private String cardName;
public void StartConversion(View view){
Intent intent = new Intent(this, ConversionActivity.class);
startActivity(intent);
cardName = view.getResources().getResourceEntryName(view.getId());
}
public getCardName() { return cardName; }
}
Then whatever class wanted to access "cardName" would call:
String cardName = myObject.getCardName();
Look here for more details: Java Getter and Setter Tutorial, Nam Ha Minh
There exists a train of way to resolve your problem. For instance,
First- the method of StartConversion works to set the card name and then provide a method of getter to access.
Second- Only use the method of StartConversion to return that you want. But you ought to change the code to return view.getResources().getResourceEntryName(view.getId());
, to remove the cardName =
. The outer class should be called the method to access that you want.
In a word, either call the method to access directly or giving a setter then using the getter to access.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.