Passing Of Value From One Activity To Another In Android
Solution 1:
Mistakes you made:
1) Why are you trying to start activity twice?
startActivity(myIntent); // this is OK
HomeActivity.this.startActivity(myIntent);
2) To pass entered text from one activity to another, you can use putExtra()
method of Intent, for example:
myIntent.putExtra("SearchText", outlet_no);
So your complete code would be:
Intent myIntent = new Intent(HomeActivity.this, StoreActivity.class);
myIntent.putExtra("SearchText", outlet_no);
startActivity(myIntent);
3) To receive value which you have passed from first activity:
Intent intent = getIntent();
Bundle bundle = intent.getExtras();
String outlet_no= bundle.getString("SearchText");
4) SharedPreferences:
FYI, SharedPreference
is used to save small amount of data which can be reference and used later across application.
You should refer below links:
Solution 2:
Intent myIntent = new Intent(HomeActivity.this, StoreActivity.class);
myIntent.putExtra("searchString", outlet_no);
startActivity(myIntent);
This will send the searchString
to the StoreActivity
and in StoreActivity
you can retrieve the value using:
String s = getIntent.getStringExtra("searchString");
Solution 3:
In your onClick method, have the following code:
String outlet_no = outlet_id.getText().toString();
if(!outlet_no.isEmpty()){
Intent myIntent = new Intent(HomeActivity.this, StoreActivity.class);
myIntent.putExtra("outlet_id",outlet_no);
startActivity(myIntent);
}
else{
Toast.makeText(getApplicationContext(), "Please enter an outlet id", Toast.LENGTH_SHORT);
}
Now in the StoreActivity, in the onCreate() method have something like this:
String outlet_no = getIntent().getStringExtra("outlet_id");
if (outlet_no != null) //Just a defensive check
//Start your processing
Solution 4:
You can also do this with Intents.
Say, we have 2 activities: SourceActivity & DestinationActivity and we want to pass a value of SourceActivity to DestinationActivity
in your Button OnClickListener:
String str_outlet_no = outlet_no.getText().toString();
Intent intent = new Intent(SourceActivity.this, DestinationActivity.class);
intent.putExtra("outlet_no_key", outlet_no);
startActivity(intent);
and on the other side in DestinationActivity:
Intent intent = getIntent();
String desi = intent.getStringExtra("outlet_no");
and search desi from database
Solution 5:
You can try something like this:-
Activity A
myIntent.putExtra(var, value); // Putting the value
startActivity(myIntent);
Activity B
String value = getIntent().getStringExtra(var); // Getting the value
Post a Comment for "Passing Of Value From One Activity To Another In Android"