Hi i have developed an app which has a text box and a search button when i enter a number in the text box and click on the search button it needs to pass the value entered to the next activity where it uses that value to get the value from a database.
I am using the following code to pass the value.
search_button.setClickable(true);
search_button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
String outlet_no = outlet_id.getText().toString();
System.out.println(outlet_no);
if(!outlet_no.isEmpty()){
@SuppressWarnings("deprecation")
SharedPreferences myPrefs = getApplicationContext().getSharedPreferences("myPrefs", MODE_WORLD_READABLE);
SharedPreferences.Editor prefsEditor = myPrefs.edit();
prefsEditor.putString("outlet_id", outlet_no);
prefsEditor.commit();
Intent myIntent = new Intent(HomeActivity.this, StoreActivity.class);
startActivity(myIntent);
HomeActivity.this.startActivity(myIntent);
}
else{
Toast.makeText(getApplicationContext(), "Please enter an outlet id", Toast.LENGTH_SHORT);
}
}
});
My problem is that it doesnot pass the value. Can any one help me with this and also can any1 explain me the above code as i didnot write it and i am finding it difficult to understand it.
StoreActivity side
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.store);
myPrefs = this.getSharedPreferences("myPrefs", MODE_WORLD_READABLE);
mOutletID = myPrefs.getString("outlet_id", "0");
mOutletDetails = myPrefs.getString("outlet_details","{}");
Log.v("outlet_details",myPrefs.getString("outlet_details","{}"));
if(mOutletDetails != "{}"){
setOutletData(mOutletDetails);
}
else{
executeAjaxRequest();
}
}
Mistakes you made:
1) Why are you trying to start activity twice?
2) To pass entered text from one activity to another, you can use
putExtra()method of Intent, for example:So your complete code would be:
3) To receive value which you have passed from first activity:
4) SharedPreferences:
FYI,
SharedPreferenceis used to save small amount of data which can be reference and used later across application.You should refer below links: