I am trying to send the value stored in a variable my_var
from one activity to the other in Android. There are probably already many similar questions here at SOV, but I have been trying things by my own, and so far, no success. I shall highly appreciate little help or hints on what I am doing wrong?
My (pseudo/example) code is like this:
public class MyActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {
public String my_var;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.my_layout);
My_method();
}
public void my_method() {
// This is a method that makes HTTP GET request and parse response to my_var
my_var = responseObject1.getX() + " " + responseObject1.getY()
}
// Then, at the bottom of MyActivity, I am creating an Intent to pass my_var to another activity to show it in TextView.
// I took this method from here[.][1]
public void rsa_key(String s){
Intent intent = new Intent(getBaseContext(), AnotherClass.class);
intent.putExtra("my_var", my_var);
startActivity(intent);
}
}
Then, in the other activity (in OnCreate)
, I am trying to get my_var
like this:
// public String my_var in initialization
Intent intent = getIntent();
my_var = intent.getStringExtra("my_var");
The app compiles, and I get no errors, but I can't see my_var
value (XML layout) when put it in TextView.setText(my_var);
in the other activity. There were no useful hints in the log as well. Can somebody help me to understand what am I doing wrong? or missing something.
I also tried SharedPreferences
like this but no luck!
In first acitvity:
SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString("varKey", my_var);
editor.commit();
Second actvity:
SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(this);
my_var = sharedPref.getString("varKey", my_var);
I shall highly appreciate help/suggestions to fix this. Many thanks!