How to add/pass multiple values to Intent object? - java

i have two EditText objects in my first activity. i want both their values when i go to the next activity.
Lets assume the EditText objects are inp1, inp2 and they can only accept numbers.
please mention how i can add their values to int Intent object and how i will extract their values in my next activity's .java file.

Here we go, your code will look like,
Sender Side:
Intent myIntent = new Intent(A.this, B.class);
myIntent.putExtra("intVariableName1", intValue1);
myIntent.putExtra("intVariableName2", intValue2);
startActivity(myIntent);
Receiver Side:
Intent mIntent = getIntent();
int intValue1 = mIntent.getIntExtra("intVariableName1", 0);
int intValue2 = mIntent.getIntExtra("intVariableName2", 0);
Hope it helps.

Use this code
Intent intent = new Intent(first.this, Second.class);
Bundle extras = new Bundle();
extras.putString("value1",String.valueof(inp1.getText().toString()));
extras.putString("value2",String.valueof(inp2.getText().toString()));
intent.putExtras(extras);
startActivity(intent);
Then in your second Activity onCreate()
Intent intent = getIntent();
Bundle extras = intent.getExtras();
String value1 = extras.getString("value1");
String value2 = extras.getString("value2");

To make thing easier and reusable you can make your own intent like this
public class MyIntent extent Intent{
private static final String FIRST_VALUE;
private static final String SECOND_VALUE;
public MyIntent(Context context, String firstValue, String secondValue){
super(context,MySecondActivity.class);
putExtra(FIRST_VALUE, firstValue);
putExtra(SECOND_VALUE, secondValue);
}
public String getFirstValue(){
getStringExtra(FIRST_VALUE);
}
public String getSecondValue(){
getStringExtra(SECOND_VALUE);
}
}
Sender:
startActivity(new MyIntent(this,"FirstString", "SecondString"));
Receiver Side:
MyIntent myIntent = (MyIntent)getIntent();
String firstValue = myIntent.getFirstValue();
String secondValue = myIntent.getSecondValue();

Related

Android Studio: How to send, and recieve a Class in diferent Activities

Im making a quiz game with questions on diferent topics
For Example i have activities for these topics: Flags, Capitals, Population, Economy, Continent, etc.
And i have one single ResultActivity to obtain the Score of the quiz.
The ResultActivity has a PLAY AGAIN button.
On the FlagsActivity i have this code:
Intent intent = new Intent(getApplicationContext(),ResultActivity.class);
intent.putExtra("RIGHT_ANSWER_COUNT", score);
intent.putExtra("NAME_ACTIVITY", "FlagsActivity");
startActivity(intent);
On the CapitalActivity i have this code:
Intent intent = new Intent(getApplicationContext(),ResultActivity.class);
intent.putExtra("RIGHT_ANSWER_COUNT", score);
intent.putExtra("NAME_ACTIVITY", "CapitalActivity");
startActivity(intent);
etc.....
On the ResultActivity i have this code:
activity = getIntent().getStringExtra("NAME_ACTIVITY");
public void playAgain(View view){
if(activity.equals("FlagsActivity")){
Intent intent = new Intent(getApplicationContext(), FlagsActivity.class);
startActivity(intent);
}
if(activity.equals("CapitalActivity")){
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
startActivity(intent);
}
if(activity.equals("PopulationActivity")){
Intent intent = new Intent(getApplicationContext(), PopulationActivity.class);
startActivity(intent);
}
if(activity.equals("EconomyActivity")){
Intent intent = new Intent(getApplicationContext(), EconomyActivity.class);
startActivity(intent);
}
if(activity.equals("ContinentActivity")){
Intent intent = new Intent(getApplicationContext(), ContinentActivity.class);
startActivity(intent);
}
}
Basically im sending an Intent with a String containing the name of the activity, then on the Result Activity evaluating with "if" the String = That activity name, start the activity.
What i want to do is someting like this:
On the Flags Activity:
Intent(getApplicationContext(),ResultActivity.class);
intent.putExtra(FlagsActivity.class);
startActivity(intent);
On the CapitalActivity:
Intent(getApplicationContext(),ResultActivity.class);
intent.putExtra(CapitalActivity.class);
startActivity(intent);
On the Result Activity:
activity = getIntent();
public void playAgain(View view){
Intent intent = new Intent(getApplicationContext(), activity);
startActivity(intent);
}
So that i can create as many quiz activities without having to create an "if" statement on the ResultActivity for it to work.
You can pass the class name as a string and use reflection to look up a class object for that type. Something like this:
Class classToLoad = Class.forName(getIntent().getStringExtra("NAME_ACTIVITY"));
Intent intent = new Intent(getApplicationContext(), classToLoad);
startActivity(intent);
I would pass the fully qualified class name to avoid errors.
You could pass the String of activity name to the Result activity, and get its corresponding class name using reflection:
String strActivity = "com.package.FlagsActivity";
Intent intent = new Intent(getApplicationContext(),ResultActivity.class);
intent.putExtra("activity_name", strActivity );
startActivity(intent);
String activityName = getIntent().getStringExtra("activity_name");
Class<?> myClass = Class.forName(activityName );
Intent myIntent = new Intent(getApplicationContext(), myClass);
Something like this.
In the Results Activity
public static void toActivity(Context context, final Class ActivityToOpen){
//whatever awesome code you would like to perform
Intent intent = new Intent(context, ActivityToOpen);
startActivity(intent);
}
In the originating Activity (Flags Activity for example)
ResultsActivity.toActivity(FlagsActivity.this, FlagActivity.class);
Check for typos... I kinda winged this :)
You should be able to call from any originating Activity without if statement.
When you receive the data
String activity;
Bundle bundle = getIntent().getExtras();
if (bundle != null){
activity = bundle.getString("NAME_ACTIVITY");
}

How to pass Latitude and Longitude to Google Maps API on button click? [duplicate]

I have a scenario where, after logging in through a login page, there will be a sign-out button on each activity.
On clicking sign-out, I will be passing the session id of the signed in user to sign-out. Can anyone guide me on how to keep session id available to all activities?
Any alternative to this case
In your current Activity, create a new Intent:
String value="Hello world";
Intent i = new Intent(CurrentActivity.this, NewActivity.class);
i.putExtra("key",value);
startActivity(i);
Then in the new Activity, retrieve those values:
Bundle extras = getIntent().getExtras();
if (extras != null) {
String value = extras.getString("key");
//The key argument here must match that used in the other activity
}
Use this technique to pass variables from one Activity to the other.
The easiest way to do this would be to pass the session id to the signout activity in the Intent you're using to start the activity:
Intent intent = new Intent(getBaseContext(), SignoutActivity.class);
intent.putExtra("EXTRA_SESSION_ID", sessionId);
startActivity(intent);
Access that intent on the next activity:
String sessionId = getIntent().getStringExtra("EXTRA_SESSION_ID");
The docs for Intents has more information (look at the section titled "Extras").
Passing Intent extras is a good approach as Erich noted.
The Application object is another way though, and it is sometimes easier when dealing with the same state across multiple activities (as opposed to having to get/put it everywhere), or objects more complex than primitives and Strings.
You can extend Application, and then set/get whatever you want there and access it from any Activity (in the same application) with getApplication().
Also keep in mind that other approaches you might see, like statics, can be problematic because they can lead to memory leaks. Application helps solve this too.
Source class:
Intent myIntent = new Intent(this, NewActivity.class);
myIntent.putExtra("firstName", "Your First Name Here");
myIntent.putExtra("lastName", "Your Last Name Here");
startActivity(myIntent)
Destination Class (NewActivity class):
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.view);
Intent intent = getIntent();
String fName = intent.getStringExtra("firstName");
String lName = intent.getStringExtra("lastName");
}
You just have to send extras while calling your intent.
Like this:
Intent intent = new Intent(getApplicationContext(), SecondActivity.class);
intent.putExtra("Variable name", "Value you want to pass");
startActivity(intent);
Now on the OnCreate method of your SecondActivity you can fetch the extras like this.
If the value you sent was in long:
long value = getIntent().getLongExtra("Variable name which you sent as an extra", defaultValue(you can give it anything));
If the value you sent was a String:
String value = getIntent().getStringExtra("Variable name which you sent as an extra");
If the value you sent was a Boolean:
Boolean value = getIntent().getBooleanExtra("Variable name which you sent as an extra", defaultValue);
It helps me to see things in context. Here are two examples.
Passing Data Forward
Main Activity
Put the data you want to send in an Intent with a key-value pair. See this answer for naming conventions for the key.
Start the Second Activity with startActivity.
MainActivity.java
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
// "Go to Second Activity" button click
public void onButtonClick(View view) {
// get the text to pass
EditText editText = (EditText) findViewById(R.id.editText);
String textToPass = editText.getText().toString();
// start the SecondActivity
Intent intent = new Intent(this, SecondActivity.class);
intent.putExtra(Intent.EXTRA_TEXT, textToPass);
startActivity(intent);
}
}
Second Activity
You use getIntent() to get the Intent that started the second activity. Then you can extract the data with getExtras() and the key you defined in the first activity. Since our data is a String we will just use getStringExtra here.
SecondActivity.java
public class SecondActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
// get the text from MainActivity
Intent intent = getIntent();
String text = intent.getStringExtra(Intent.EXTRA_TEXT);
// use the text in a TextView
TextView textView = (TextView) findViewById(R.id.textView);
textView.setText(text);
}
}
Passing Data Back
Main Activity
Start the Second Activity with startActivityForResult, providing it an arbitrary result code.
Override onActivityResult. This is called when the Second Activity finishes. You can make sure that it is actually the Second Activity by checking the result code. (This is useful when you are starting multiple different activities from the same main activity.)
Extract the data you got from the return Intent. The data is extracted using a key-value pair. I could use any string for the key but I'll use the predefined Intent.EXTRA_TEXT since I'm sending text.
MainActivity.java
public class MainActivity extends AppCompatActivity {
private static final int SECOND_ACTIVITY_REQUEST_CODE = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
// "Go to Second Activity" button click
public void onButtonClick(View view) {
// Start the SecondActivity
Intent intent = new Intent(this, SecondActivity.class);
startActivityForResult(intent, SECOND_ACTIVITY_REQUEST_CODE);
}
// This method is called when the second activity finishes
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// check that it is the SecondActivity with an OK result
if (requestCode == SECOND_ACTIVITY_REQUEST_CODE) {
if (resultCode == RESULT_OK) {
// get String data from Intent
String returnString = data.getStringExtra(Intent.EXTRA_TEXT);
// set text view with string
TextView textView = (TextView) findViewById(R.id.textView);
textView.setText(returnString);
}
}
}
}
Second Activity
Put the data that you want to send back to the previous activity into an Intent. The data is stored in the Intent using a key-value pair. I chose to use Intent.EXTRA_TEXT for my key.
Set the result to RESULT_OK and add the intent holding your data.
Call finish() to close the Second Activity.
SecondActivity.java
public class SecondActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
}
// "Send text back" button click
public void onButtonClick(View view) {
// get the text from the EditText
EditText editText = (EditText) findViewById(R.id.editText);
String stringToPassBack = editText.getText().toString();
// put the String to pass back into an Intent and close this activity
Intent intent = new Intent();
intent.putExtra(Intent.EXTRA_TEXT, stringToPassBack);
setResult(RESULT_OK, intent);
finish();
}
}
Updated Note that I had mentioned the use of SharedPreference. It has a simple API and is accessible across an application's activities. But this is a clumsy solution, and is a security risk if you pass around sensitive data. It's best to use intents. It has an extensive list of overloaded methods that can be used to better transfer many different data types between activities. Have a look at intent.putExtra. This link presents the use of putExtra quite well.
In passing data between activities, my preferred approach is to create a static method for the relevant activity that includes the required parameters launch the intent. Which then provides easily setup and retrieve parameters. So it can look like this
public class MyActivity extends Activity {
public static final String ARG_PARAM1 = "arg_param1";
...
public static getIntent(Activity from, String param1, Long param2...) {
Intent intent = new Intent(from, MyActivity.class);
intent.putExtra(ARG_PARAM1, param1);
intent.putExtra(ARG_PARAM2, param2);
return intent;
}
....
// Use it like this.
startActivity(MyActvitiy.getIntent(FromActivity.this, varA, varB, ...));
...
Then you can create an intent for the intended activity and ensure you have all the parameters. You can adapt for fragments to. A simple example above, but you get the idea.
Try to do the following:
Create a simple "helper" class (factory for your Intents), like this:
import android.content.Intent;
public class IntentHelper {
public static final Intent createYourSpecialIntent(Intent src) {
return new Intent("YourSpecialIntent").addCategory("YourSpecialCategory").putExtras(src);
}
}
This will be the factory for all your Intents. Everytime you need a new Intent, create a static factory method in IntentHelper. To create a new Intent you should just say it like this:
IntentHelper.createYourSpecialIntent(getIntent());
In your activity. When you want to "save" some data in a "session" just use the following:
IntentHelper.createYourSpecialIntent(getIntent()).putExtra("YOUR_FIELD_NAME", fieldValueToSave);
And send this Intent. In the target Activity your field will be available as:
getIntent().getStringExtra("YOUR_FIELD_NAME");
So now we can use Intent like same old session (like in servlets or JSP).
You can also pass custom class objects by making a parcelable class. Best way to make it parcelable is to write your class and then simply paste it to a site like http://www.parcelabler.com/. Click on build and you will get new code. Copy all of this and replace the original class contents.
Then-
Intent intent = new Intent(getBaseContext(), NextActivity.class);
Foo foo = new Foo();
intent.putExtra("foo", foo);
startActivity(intent);
and get the result in NextActivity like-
Foo foo = getIntent().getExtras().getParcelable("foo");
Now you can simply use the foo object like you would have used.
Another way is to use a public static field in which you store data, i.e.:
public class MyActivity extends Activity {
public static String SharedString;
public static SomeObject SharedObject;
//...
The most convenient way to pass data between activities is by passing intents. In the first activity from where you want to send data, you should add code,
String str = "My Data"; //Data you want to send
Intent intent = new Intent(FirstActivity.this, SecondActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.putExtra("name",str); //Here you will add the data into intent to pass bw activites
v.getContext().startActivity(intent);
You should also import
import android.content.Intent;
Then in the next Acitvity(SecondActivity), you should retrieve the data from the intent using the following code.
String name = this.getIntent().getStringExtra("name");
You can use SharedPreferences...
Logging. Time store session id in SharedPreferences
SharedPreferences preferences = getSharedPreferences("session",getApplicationContext().MODE_PRIVATE);
Editor editor = preferences.edit();
editor.putString("sessionId", sessionId);
editor.commit();
Signout. Time fetch session id in sharedpreferences
SharedPreferences preferences = getSharedPreferences("session", getApplicationContext().MODE_PRIVATE);
String sessionId = preferences.getString("sessionId", null);
If you don't have the required session id, then remove sharedpreferences:
SharedPreferences settings = context.getSharedPreferences("session", Context.MODE_PRIVATE);
settings.edit().clear().commit();
That is very useful, because one time you save the value and then retrieve anywhere of activity.
From Activity
int n= 10;
Intent in = new Intent(From_Activity.this,To_Activity.class);
Bundle b1 = new Bundle();
b1.putInt("integerNumber",n);
in.putExtras(b1);
startActivity(in);
To Activity
Bundle b2 = getIntent().getExtras();
int m = 0;
if(b2 != null){
m = b2.getInt("integerNumber");
}
The standard approach.
Intent i = new Intent(this, ActivityTwo.class);
AutoCompleteTextView textView = (AutoCompleteTextView) findViewById(R.id.autocomplete);
String getrec=textView.getText().toString();
Bundle bundle = new Bundle();
bundle.putString(“stuff”, getrec);
i.putExtras(bundle);
startActivity(i);
Now in your second activity retrieve your data from the bundle:
Get the bundle
Bundle bundle = getIntent().getExtras();
Extract the data…
String stuff = bundle.getString(“stuff”);
Kotlin
Pass from First Activity
val intent = Intent(this, SecondActivity::class.java)
intent.putExtra("key", "value")
startActivity(intent)
Get in Second Activity
val value = intent.getStringExtra("key")
Suggestion
Always put keys in constant file for more managed way.
companion object {
val KEY = "key"
}
You can send data between activities using intent object.
Consider you have two activities namely FirstActivity and SecondActivity.
Inside FirstActivity:
Using Intent:
i = new Intent(FirstActivity.this,SecondActivity.class);
i.putExtra("key", value);
startActivity(i)
Inside SecondActivity
Bundle bundle= getIntent().getExtras();
Now you can use different bundle class methods to get values passed from FirstActivity by Key.
E.g.
bundle.getString("key"),bundle.getDouble("key") ,bundle.getInt("key") etc.
If you want to tranfer bitmap between Activites/Fragments
Activity
To pass a bitmap between Activites
Intent intent = new Intent(this, Activity.class);
intent.putExtra("bitmap", bitmap);
And in the Activity class
Bitmap bitmap = getIntent().getParcelableExtra("bitmap");
Fragment
To pass a bitmap between Fragments
SecondFragment fragment = new SecondFragment();
Bundle bundle = new Bundle();
bundle.putParcelable("bitmap", bitmap);
fragment.setArguments(bundle);
To receive inside the SecondFragment
Bitmap bitmap = getArguments().getParcelable("bitmap");
Transfering Large Bitmaps
If you are getting failed binder transaction, this means you are exceeding the binder transaction buffer by transferring large element from one activity to another activity.
So in that case you have to compress the bitmap as an byte's array and then uncompress it in another activity, like this
In the FirstActivity
Intent intent = new Intent(this, SecondActivity.class);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPG, 100, stream);
byte[] bytes = stream.toByteArray();
intent.putExtra("bitmapbytes",bytes);
And in the SecondActivity
byte[] bytes = getIntent().getByteArrayExtra("bitmapbytes");
Bitmap bmp = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
Intent intent = new Intent(YourCurrentActivity.this, YourActivityName.class);
intent.putExtra("NAme","John");
intent.putExtra("Id",1);
startActivity(intent);
You can retrieve it in another activity. Two ways:
int id = getIntent.getIntExtra("id", /* defaltvalue */ 2);
The second way is:
Intent i = getIntent();
String name = i.getStringExtra("name");
Supplemental Answer: Naming Conventions for the Key String
The actual process of passing data has already been answered, however most of the answers use hard coded strings for the key name in the Intent. This is usually fine when used only within your app. However, the documentation recommends using the EXTRA_* constants for standardized data types.
Example 1: Using Intent.EXTRA_* keys
First activity
Intent intent = new Intent(getActivity(), SecondActivity.class);
intent.putExtra(Intent.EXTRA_TEXT, "my text");
startActivity(intent);
Second activity:
Intent intent = getIntent();
String myText = intent.getExtras().getString(Intent.EXTRA_TEXT);
Example 2: Defining your own static final key
If one of the Intent.EXTRA_* Strings does not suit your needs, you can define your own at the beginning of the first activity.
static final String EXTRA_STUFF = "com.myPackageName.EXTRA_STUFF";
Including the package name is just a convention if you are only using the key in your own app. But it is a necessity to avoid naming conflicts if you are creating some sort of service that other apps can call with an Intent.
First activity:
Intent intent = new Intent(getActivity(), SecondActivity.class);
intent.putExtra(EXTRA_STUFF, "my text");
startActivity(intent);
Second activity:
Intent intent = getIntent();
String myText = intent.getExtras().getString(FirstActivity.EXTRA_STUFF);
Example 3: Using a String resource key
Although not mentioned in the documentation, this answer recommends using a String resource to avoid dependencies between activities.
strings.xml
<string name="EXTRA_STUFF">com.myPackageName.MY_NAME</string>
First activity
Intent intent = new Intent(getActivity(), SecondActivity.class);
intent.putExtra(getString(R.string.EXTRA_STUFF), "my text");
startActivity(intent);
Second activity
Intent intent = getIntent();
String myText = intent.getExtras().getString(getString(R.string.EXTRA_STUFF));
Here is my best practice and it helps a lot when the project is huge and complex.
Suppose that I have 2 activities, LoginActivity and HomeActivity.
I want to pass 2 parameters (username & password) from LoginActivity to HomeActivity.
First, I create my HomeIntent
public class HomeIntent extends Intent {
private static final String ACTION_LOGIN = "action_login";
private static final String ACTION_LOGOUT = "action_logout";
private static final String ARG_USERNAME = "arg_username";
private static final String ARG_PASSWORD = "arg_password";
public HomeIntent(Context ctx, boolean isLogIn) {
this(ctx);
//set action type
setAction(isLogIn ? ACTION_LOGIN : ACTION_LOGOUT);
}
public HomeIntent(Context ctx) {
super(ctx, HomeActivity.class);
}
//This will be needed for receiving data
public HomeIntent(Intent intent) {
super(intent);
}
public void setData(String userName, String password) {
putExtra(ARG_USERNAME, userName);
putExtra(ARG_PASSWORD, password);
}
public String getUsername() {
return getStringExtra(ARG_USERNAME);
}
public String getPassword() {
return getStringExtra(ARG_PASSWORD);
}
//To separate the params is for which action, we should create action
public boolean isActionLogIn() {
return getAction().equals(ACTION_LOGIN);
}
public boolean isActionLogOut() {
return getAction().equals(ACTION_LOGOUT);
}
}
Here is how I pass the data in my LoginActivity
public class LoginActivity extends AppCompatActivity {
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
String username = "phearum";
String password = "pwd1133";
final boolean isActionLogin = true;
//Passing data to HomeActivity
final HomeIntent homeIntent = new HomeIntent(this, isActionLogin);
homeIntent.setData(username, password);
startActivity(homeIntent);
}
}
Final step, here is how I receive the data in HomeActivity
public class HomeActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
//This is how we receive the data from LoginActivity
//Make sure you pass getIntent() to the HomeIntent constructor
final HomeIntent homeIntent = new HomeIntent(getIntent());
Log.d("HomeActivity", "Is action login? " + homeIntent.isActionLogIn());
Log.d("HomeActivity", "username: " + homeIntent.getUsername());
Log.d("HomeActivity", "password: " + homeIntent.getPassword());
}
}
Done! Cool :) I just want to share my experience. If you working on small project this shouldn't be the big problem. But when your working on big project, it really pain when you want to do refactoring or fixing bugs.
The passing of data between activities is mainly by means of an intent object.
First you have to attach the data to the intent object with the use of the Bundle class. Then call the activity using either startActivity() or startActivityForResult() methods.
You can find more information about it, with an example from the blog post Passing data to an Activity.
You can try Shared Preference, it may be a good alternative for sharing data between the activities
To save session id -
SharedPreferences pref = myContexy.getSharedPreferences("Session
Data",MODE_PRIVATE);
SharedPreferences.Editor edit = pref.edit();
edit.putInt("Session ID", session_id);
edit.commit();
To get them -
SharedPreferences pref = myContexy.getSharedPreferences("Session Data", MODE_PRIVATE);
session_id = pref.getInt("Session ID", 0);
You can use Intent
Intent mIntent = new Intent(FirstActivity.this, SecondActivity.class);
mIntent.putExtra("data", data);
startActivity(mIntent);
Another way could be using singleton pattern also:
public class DataHolder {
private static DataHolder dataHolder;
private List<Model> dataList;
public void setDataList(List<Model>dataList) {
this.dataList = dataList;
}
public List<Model> getDataList() {
return dataList;
}
public synchronized static DataHolder getInstance() {
if (dataHolder == null) {
dataHolder = new DataHolder();
}
return dataHolder;
}
}
From your FirstActivity
private List<Model> dataList = new ArrayList<>();
DataHolder.getInstance().setDataList(dataList);
On SecondActivity
private List<Model> dataList = DataHolder.getInstance().getDataList();
Write following code in CurrentActivity.java
Intent i = new Intent(CurrentActivity.this, SignOutActivity.class);
i.putExtra("SESSION_ID",sessionId);
startActivity(i);
Access SessionId in SignOutActivity.java is following way
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sign_out);
Intent intent = getIntent();
// check intent is null or not
if(intent != null){
String sessionId = intent.getStringExtra("SESSION_ID");
Log.d("Session_id : " + sessionId);
}
else{
Toast.makeText(SignOutActivity.this, "Intent is null", Toast.LENGTH_SHORT).show();
}
}
Start another activity from this activity pass parameters via Bundle Object
Intent intent = new Intent(getBaseContext(), YourActivity.class);
intent.putExtra("USER_NAME", "xyz#gmail.com");
startActivity(intent);
Retrieve on another activity (YourActivity)
String s = getIntent().getStringExtra("USER_NAME");
This is ok for simple kind data type.
But if u want to pass complex data in between activity u need to serialize it first.
Here we have Employee Model
class Employee{
private String empId;
private int age;
print Double salary;
getters...
setters...
}
You can use Gson lib provided by google to serialize the complex data
like this
String strEmp = new Gson().toJson(emp);
Intent intent = new Intent(getBaseContext(), YourActivity.class);
intent.putExtra("EMP", strEmp);
startActivity(intent);
Bundle bundle = getIntent().getExtras();
String empStr = bundle.getString("EMP");
Gson gson = new Gson();
Type type = new TypeToken<Employee>() {
}.getType();
Employee selectedEmp = gson.fromJson(empStr, type);
1st way: In your current Activity, when you create an object of intent to open a new screen:
String value="xyz";
Intent intent = new Intent(CurrentActivity.this, NextActivity.class);
intent.putExtra("key", value);
startActivity(intent);
Then in the nextActivity in the onCreate method, retrieve those values which you pass from the previous activity:
if (getIntent().getExtras() != null) {
String value = getIntent().getStringExtra("key");
//The key argument must always match that used send and retrieve value from one activity to another.
}
2nd way: You can create a bundle object and put values in a bundle and then put the bundle object in intent from your current activity -
String value="xyz";
Intent intent = new Intent(CurrentActivity.this, NextActivity.class);
Bundle bundle = new Bundle();
bundle.putInt("key", value);
intent.putExtra("bundle_key", bundle);
startActivity(intent);
Then in the nextActivity in the onCreate method, retrieve those values which you pass from the previous activity:
if (getIntent().getExtras() != null) {
Bundle bundle = getIntent().getStringExtra("bundle_key");
String value = bundle.getString("key");
//The key argument must always match that used send and retrieve value from one activity to another.
}
You can also use the bean class to pass data between classes using serialization.
/*
* If you are from transferring data from one class that doesn't
* extend Activity, then you need to do something like this.
*/
public class abc {
Context context;
public abc(Context context) {
this.context = context;
}
public void something() {
context.startactivity(new Intent(context, anyone.class).putextra("key", value));
}
}
I recently released Vapor API, a jQuery flavored Android framework that makes all sorts of tasks like this simpler. As mentioned, SharedPreferences is one way you could do this.
VaporSharedPreferences is implemented as Singleton so that is one option, and in Vapor API it has a heavily overloaded .put(...) method so you don't have to explicitly worry about the datatype you are committing - providing it is supported. It is also fluent, so you can chain calls:
$.prefs(...).put("val1", 123).put("val2", "Hello World!").put("something", 3.34);
It also optionally autosaves changes, and unifies the reading and writing process under-the-hood so you don't need to explicitly retrieve an Editor like you do in standard Android.
Alternatively you could use an Intent. In Vapor API you can also use the chainable overloaded .put(...) method on a VaporIntent:
$.Intent().put("data", "myData").put("more", 568)...
And pass it as an extra, as mentioned in the other answers. You can retrieve extras from your Activity, and furthermore if you are using VaporActivity this is done for you automatically so you can use:
this.extras()
To retrieve them at the other end in the Activity you switch to.
Hope that is of interest to some :)
First Activity:
Intent intent = new Intent(getApplicationContext(), ClassName.class);
intent.putExtra("Variable name", "Value you want to pass");
startActivity(intent);
Second Activity:
String str= getIntent().getStringExtra("Variable name which you sent as an extra");
Use a global class:
public class GlobalClass extends Application
{
private float vitamin_a;
public float getVitaminA() {
return vitamin_a;
}
public void setVitaminA(float vitamin_a) {
this.vitamin_a = vitamin_a;
}
}
You can call the setters and the getters of this class from all other classes.
Do do that, you need to make a GlobalClass-Object in every Actitity:
GlobalClass gc = (GlobalClass) getApplication();
Then you can call for example:
gc.getVitaminA()

I can't change background color another activity [duplicate]

I have a scenario where, after logging in through a login page, there will be a sign-out button on each activity.
On clicking sign-out, I will be passing the session id of the signed in user to sign-out. Can anyone guide me on how to keep session id available to all activities?
Any alternative to this case
In your current Activity, create a new Intent:
String value="Hello world";
Intent i = new Intent(CurrentActivity.this, NewActivity.class);
i.putExtra("key",value);
startActivity(i);
Then in the new Activity, retrieve those values:
Bundle extras = getIntent().getExtras();
if (extras != null) {
String value = extras.getString("key");
//The key argument here must match that used in the other activity
}
Use this technique to pass variables from one Activity to the other.
The easiest way to do this would be to pass the session id to the signout activity in the Intent you're using to start the activity:
Intent intent = new Intent(getBaseContext(), SignoutActivity.class);
intent.putExtra("EXTRA_SESSION_ID", sessionId);
startActivity(intent);
Access that intent on the next activity:
String sessionId = getIntent().getStringExtra("EXTRA_SESSION_ID");
The docs for Intents has more information (look at the section titled "Extras").
Passing Intent extras is a good approach as Erich noted.
The Application object is another way though, and it is sometimes easier when dealing with the same state across multiple activities (as opposed to having to get/put it everywhere), or objects more complex than primitives and Strings.
You can extend Application, and then set/get whatever you want there and access it from any Activity (in the same application) with getApplication().
Also keep in mind that other approaches you might see, like statics, can be problematic because they can lead to memory leaks. Application helps solve this too.
Source class:
Intent myIntent = new Intent(this, NewActivity.class);
myIntent.putExtra("firstName", "Your First Name Here");
myIntent.putExtra("lastName", "Your Last Name Here");
startActivity(myIntent)
Destination Class (NewActivity class):
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.view);
Intent intent = getIntent();
String fName = intent.getStringExtra("firstName");
String lName = intent.getStringExtra("lastName");
}
You just have to send extras while calling your intent.
Like this:
Intent intent = new Intent(getApplicationContext(), SecondActivity.class);
intent.putExtra("Variable name", "Value you want to pass");
startActivity(intent);
Now on the OnCreate method of your SecondActivity you can fetch the extras like this.
If the value you sent was in long:
long value = getIntent().getLongExtra("Variable name which you sent as an extra", defaultValue(you can give it anything));
If the value you sent was a String:
String value = getIntent().getStringExtra("Variable name which you sent as an extra");
If the value you sent was a Boolean:
Boolean value = getIntent().getBooleanExtra("Variable name which you sent as an extra", defaultValue);
It helps me to see things in context. Here are two examples.
Passing Data Forward
Main Activity
Put the data you want to send in an Intent with a key-value pair. See this answer for naming conventions for the key.
Start the Second Activity with startActivity.
MainActivity.java
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
// "Go to Second Activity" button click
public void onButtonClick(View view) {
// get the text to pass
EditText editText = (EditText) findViewById(R.id.editText);
String textToPass = editText.getText().toString();
// start the SecondActivity
Intent intent = new Intent(this, SecondActivity.class);
intent.putExtra(Intent.EXTRA_TEXT, textToPass);
startActivity(intent);
}
}
Second Activity
You use getIntent() to get the Intent that started the second activity. Then you can extract the data with getExtras() and the key you defined in the first activity. Since our data is a String we will just use getStringExtra here.
SecondActivity.java
public class SecondActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
// get the text from MainActivity
Intent intent = getIntent();
String text = intent.getStringExtra(Intent.EXTRA_TEXT);
// use the text in a TextView
TextView textView = (TextView) findViewById(R.id.textView);
textView.setText(text);
}
}
Passing Data Back
Main Activity
Start the Second Activity with startActivityForResult, providing it an arbitrary result code.
Override onActivityResult. This is called when the Second Activity finishes. You can make sure that it is actually the Second Activity by checking the result code. (This is useful when you are starting multiple different activities from the same main activity.)
Extract the data you got from the return Intent. The data is extracted using a key-value pair. I could use any string for the key but I'll use the predefined Intent.EXTRA_TEXT since I'm sending text.
MainActivity.java
public class MainActivity extends AppCompatActivity {
private static final int SECOND_ACTIVITY_REQUEST_CODE = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
// "Go to Second Activity" button click
public void onButtonClick(View view) {
// Start the SecondActivity
Intent intent = new Intent(this, SecondActivity.class);
startActivityForResult(intent, SECOND_ACTIVITY_REQUEST_CODE);
}
// This method is called when the second activity finishes
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// check that it is the SecondActivity with an OK result
if (requestCode == SECOND_ACTIVITY_REQUEST_CODE) {
if (resultCode == RESULT_OK) {
// get String data from Intent
String returnString = data.getStringExtra(Intent.EXTRA_TEXT);
// set text view with string
TextView textView = (TextView) findViewById(R.id.textView);
textView.setText(returnString);
}
}
}
}
Second Activity
Put the data that you want to send back to the previous activity into an Intent. The data is stored in the Intent using a key-value pair. I chose to use Intent.EXTRA_TEXT for my key.
Set the result to RESULT_OK and add the intent holding your data.
Call finish() to close the Second Activity.
SecondActivity.java
public class SecondActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
}
// "Send text back" button click
public void onButtonClick(View view) {
// get the text from the EditText
EditText editText = (EditText) findViewById(R.id.editText);
String stringToPassBack = editText.getText().toString();
// put the String to pass back into an Intent and close this activity
Intent intent = new Intent();
intent.putExtra(Intent.EXTRA_TEXT, stringToPassBack);
setResult(RESULT_OK, intent);
finish();
}
}
Updated Note that I had mentioned the use of SharedPreference. It has a simple API and is accessible across an application's activities. But this is a clumsy solution, and is a security risk if you pass around sensitive data. It's best to use intents. It has an extensive list of overloaded methods that can be used to better transfer many different data types between activities. Have a look at intent.putExtra. This link presents the use of putExtra quite well.
In passing data between activities, my preferred approach is to create a static method for the relevant activity that includes the required parameters launch the intent. Which then provides easily setup and retrieve parameters. So it can look like this
public class MyActivity extends Activity {
public static final String ARG_PARAM1 = "arg_param1";
...
public static getIntent(Activity from, String param1, Long param2...) {
Intent intent = new Intent(from, MyActivity.class);
intent.putExtra(ARG_PARAM1, param1);
intent.putExtra(ARG_PARAM2, param2);
return intent;
}
....
// Use it like this.
startActivity(MyActvitiy.getIntent(FromActivity.this, varA, varB, ...));
...
Then you can create an intent for the intended activity and ensure you have all the parameters. You can adapt for fragments to. A simple example above, but you get the idea.
Try to do the following:
Create a simple "helper" class (factory for your Intents), like this:
import android.content.Intent;
public class IntentHelper {
public static final Intent createYourSpecialIntent(Intent src) {
return new Intent("YourSpecialIntent").addCategory("YourSpecialCategory").putExtras(src);
}
}
This will be the factory for all your Intents. Everytime you need a new Intent, create a static factory method in IntentHelper. To create a new Intent you should just say it like this:
IntentHelper.createYourSpecialIntent(getIntent());
In your activity. When you want to "save" some data in a "session" just use the following:
IntentHelper.createYourSpecialIntent(getIntent()).putExtra("YOUR_FIELD_NAME", fieldValueToSave);
And send this Intent. In the target Activity your field will be available as:
getIntent().getStringExtra("YOUR_FIELD_NAME");
So now we can use Intent like same old session (like in servlets or JSP).
You can also pass custom class objects by making a parcelable class. Best way to make it parcelable is to write your class and then simply paste it to a site like http://www.parcelabler.com/. Click on build and you will get new code. Copy all of this and replace the original class contents.
Then-
Intent intent = new Intent(getBaseContext(), NextActivity.class);
Foo foo = new Foo();
intent.putExtra("foo", foo);
startActivity(intent);
and get the result in NextActivity like-
Foo foo = getIntent().getExtras().getParcelable("foo");
Now you can simply use the foo object like you would have used.
Another way is to use a public static field in which you store data, i.e.:
public class MyActivity extends Activity {
public static String SharedString;
public static SomeObject SharedObject;
//...
The most convenient way to pass data between activities is by passing intents. In the first activity from where you want to send data, you should add code,
String str = "My Data"; //Data you want to send
Intent intent = new Intent(FirstActivity.this, SecondActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.putExtra("name",str); //Here you will add the data into intent to pass bw activites
v.getContext().startActivity(intent);
You should also import
import android.content.Intent;
Then in the next Acitvity(SecondActivity), you should retrieve the data from the intent using the following code.
String name = this.getIntent().getStringExtra("name");
You can use SharedPreferences...
Logging. Time store session id in SharedPreferences
SharedPreferences preferences = getSharedPreferences("session",getApplicationContext().MODE_PRIVATE);
Editor editor = preferences.edit();
editor.putString("sessionId", sessionId);
editor.commit();
Signout. Time fetch session id in sharedpreferences
SharedPreferences preferences = getSharedPreferences("session", getApplicationContext().MODE_PRIVATE);
String sessionId = preferences.getString("sessionId", null);
If you don't have the required session id, then remove sharedpreferences:
SharedPreferences settings = context.getSharedPreferences("session", Context.MODE_PRIVATE);
settings.edit().clear().commit();
That is very useful, because one time you save the value and then retrieve anywhere of activity.
From Activity
int n= 10;
Intent in = new Intent(From_Activity.this,To_Activity.class);
Bundle b1 = new Bundle();
b1.putInt("integerNumber",n);
in.putExtras(b1);
startActivity(in);
To Activity
Bundle b2 = getIntent().getExtras();
int m = 0;
if(b2 != null){
m = b2.getInt("integerNumber");
}
The standard approach.
Intent i = new Intent(this, ActivityTwo.class);
AutoCompleteTextView textView = (AutoCompleteTextView) findViewById(R.id.autocomplete);
String getrec=textView.getText().toString();
Bundle bundle = new Bundle();
bundle.putString(“stuff”, getrec);
i.putExtras(bundle);
startActivity(i);
Now in your second activity retrieve your data from the bundle:
Get the bundle
Bundle bundle = getIntent().getExtras();
Extract the data…
String stuff = bundle.getString(“stuff”);
Kotlin
Pass from First Activity
val intent = Intent(this, SecondActivity::class.java)
intent.putExtra("key", "value")
startActivity(intent)
Get in Second Activity
val value = intent.getStringExtra("key")
Suggestion
Always put keys in constant file for more managed way.
companion object {
val KEY = "key"
}
You can send data between activities using intent object.
Consider you have two activities namely FirstActivity and SecondActivity.
Inside FirstActivity:
Using Intent:
i = new Intent(FirstActivity.this,SecondActivity.class);
i.putExtra("key", value);
startActivity(i)
Inside SecondActivity
Bundle bundle= getIntent().getExtras();
Now you can use different bundle class methods to get values passed from FirstActivity by Key.
E.g.
bundle.getString("key"),bundle.getDouble("key") ,bundle.getInt("key") etc.
If you want to tranfer bitmap between Activites/Fragments
Activity
To pass a bitmap between Activites
Intent intent = new Intent(this, Activity.class);
intent.putExtra("bitmap", bitmap);
And in the Activity class
Bitmap bitmap = getIntent().getParcelableExtra("bitmap");
Fragment
To pass a bitmap between Fragments
SecondFragment fragment = new SecondFragment();
Bundle bundle = new Bundle();
bundle.putParcelable("bitmap", bitmap);
fragment.setArguments(bundle);
To receive inside the SecondFragment
Bitmap bitmap = getArguments().getParcelable("bitmap");
Transfering Large Bitmaps
If you are getting failed binder transaction, this means you are exceeding the binder transaction buffer by transferring large element from one activity to another activity.
So in that case you have to compress the bitmap as an byte's array and then uncompress it in another activity, like this
In the FirstActivity
Intent intent = new Intent(this, SecondActivity.class);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPG, 100, stream);
byte[] bytes = stream.toByteArray();
intent.putExtra("bitmapbytes",bytes);
And in the SecondActivity
byte[] bytes = getIntent().getByteArrayExtra("bitmapbytes");
Bitmap bmp = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
Intent intent = new Intent(YourCurrentActivity.this, YourActivityName.class);
intent.putExtra("NAme","John");
intent.putExtra("Id",1);
startActivity(intent);
You can retrieve it in another activity. Two ways:
int id = getIntent.getIntExtra("id", /* defaltvalue */ 2);
The second way is:
Intent i = getIntent();
String name = i.getStringExtra("name");
Supplemental Answer: Naming Conventions for the Key String
The actual process of passing data has already been answered, however most of the answers use hard coded strings for the key name in the Intent. This is usually fine when used only within your app. However, the documentation recommends using the EXTRA_* constants for standardized data types.
Example 1: Using Intent.EXTRA_* keys
First activity
Intent intent = new Intent(getActivity(), SecondActivity.class);
intent.putExtra(Intent.EXTRA_TEXT, "my text");
startActivity(intent);
Second activity:
Intent intent = getIntent();
String myText = intent.getExtras().getString(Intent.EXTRA_TEXT);
Example 2: Defining your own static final key
If one of the Intent.EXTRA_* Strings does not suit your needs, you can define your own at the beginning of the first activity.
static final String EXTRA_STUFF = "com.myPackageName.EXTRA_STUFF";
Including the package name is just a convention if you are only using the key in your own app. But it is a necessity to avoid naming conflicts if you are creating some sort of service that other apps can call with an Intent.
First activity:
Intent intent = new Intent(getActivity(), SecondActivity.class);
intent.putExtra(EXTRA_STUFF, "my text");
startActivity(intent);
Second activity:
Intent intent = getIntent();
String myText = intent.getExtras().getString(FirstActivity.EXTRA_STUFF);
Example 3: Using a String resource key
Although not mentioned in the documentation, this answer recommends using a String resource to avoid dependencies between activities.
strings.xml
<string name="EXTRA_STUFF">com.myPackageName.MY_NAME</string>
First activity
Intent intent = new Intent(getActivity(), SecondActivity.class);
intent.putExtra(getString(R.string.EXTRA_STUFF), "my text");
startActivity(intent);
Second activity
Intent intent = getIntent();
String myText = intent.getExtras().getString(getString(R.string.EXTRA_STUFF));
Here is my best practice and it helps a lot when the project is huge and complex.
Suppose that I have 2 activities, LoginActivity and HomeActivity.
I want to pass 2 parameters (username & password) from LoginActivity to HomeActivity.
First, I create my HomeIntent
public class HomeIntent extends Intent {
private static final String ACTION_LOGIN = "action_login";
private static final String ACTION_LOGOUT = "action_logout";
private static final String ARG_USERNAME = "arg_username";
private static final String ARG_PASSWORD = "arg_password";
public HomeIntent(Context ctx, boolean isLogIn) {
this(ctx);
//set action type
setAction(isLogIn ? ACTION_LOGIN : ACTION_LOGOUT);
}
public HomeIntent(Context ctx) {
super(ctx, HomeActivity.class);
}
//This will be needed for receiving data
public HomeIntent(Intent intent) {
super(intent);
}
public void setData(String userName, String password) {
putExtra(ARG_USERNAME, userName);
putExtra(ARG_PASSWORD, password);
}
public String getUsername() {
return getStringExtra(ARG_USERNAME);
}
public String getPassword() {
return getStringExtra(ARG_PASSWORD);
}
//To separate the params is for which action, we should create action
public boolean isActionLogIn() {
return getAction().equals(ACTION_LOGIN);
}
public boolean isActionLogOut() {
return getAction().equals(ACTION_LOGOUT);
}
}
Here is how I pass the data in my LoginActivity
public class LoginActivity extends AppCompatActivity {
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
String username = "phearum";
String password = "pwd1133";
final boolean isActionLogin = true;
//Passing data to HomeActivity
final HomeIntent homeIntent = new HomeIntent(this, isActionLogin);
homeIntent.setData(username, password);
startActivity(homeIntent);
}
}
Final step, here is how I receive the data in HomeActivity
public class HomeActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
//This is how we receive the data from LoginActivity
//Make sure you pass getIntent() to the HomeIntent constructor
final HomeIntent homeIntent = new HomeIntent(getIntent());
Log.d("HomeActivity", "Is action login? " + homeIntent.isActionLogIn());
Log.d("HomeActivity", "username: " + homeIntent.getUsername());
Log.d("HomeActivity", "password: " + homeIntent.getPassword());
}
}
Done! Cool :) I just want to share my experience. If you working on small project this shouldn't be the big problem. But when your working on big project, it really pain when you want to do refactoring or fixing bugs.
The passing of data between activities is mainly by means of an intent object.
First you have to attach the data to the intent object with the use of the Bundle class. Then call the activity using either startActivity() or startActivityForResult() methods.
You can find more information about it, with an example from the blog post Passing data to an Activity.
You can try Shared Preference, it may be a good alternative for sharing data between the activities
To save session id -
SharedPreferences pref = myContexy.getSharedPreferences("Session
Data",MODE_PRIVATE);
SharedPreferences.Editor edit = pref.edit();
edit.putInt("Session ID", session_id);
edit.commit();
To get them -
SharedPreferences pref = myContexy.getSharedPreferences("Session Data", MODE_PRIVATE);
session_id = pref.getInt("Session ID", 0);
You can use Intent
Intent mIntent = new Intent(FirstActivity.this, SecondActivity.class);
mIntent.putExtra("data", data);
startActivity(mIntent);
Another way could be using singleton pattern also:
public class DataHolder {
private static DataHolder dataHolder;
private List<Model> dataList;
public void setDataList(List<Model>dataList) {
this.dataList = dataList;
}
public List<Model> getDataList() {
return dataList;
}
public synchronized static DataHolder getInstance() {
if (dataHolder == null) {
dataHolder = new DataHolder();
}
return dataHolder;
}
}
From your FirstActivity
private List<Model> dataList = new ArrayList<>();
DataHolder.getInstance().setDataList(dataList);
On SecondActivity
private List<Model> dataList = DataHolder.getInstance().getDataList();
Write following code in CurrentActivity.java
Intent i = new Intent(CurrentActivity.this, SignOutActivity.class);
i.putExtra("SESSION_ID",sessionId);
startActivity(i);
Access SessionId in SignOutActivity.java is following way
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sign_out);
Intent intent = getIntent();
// check intent is null or not
if(intent != null){
String sessionId = intent.getStringExtra("SESSION_ID");
Log.d("Session_id : " + sessionId);
}
else{
Toast.makeText(SignOutActivity.this, "Intent is null", Toast.LENGTH_SHORT).show();
}
}
Start another activity from this activity pass parameters via Bundle Object
Intent intent = new Intent(getBaseContext(), YourActivity.class);
intent.putExtra("USER_NAME", "xyz#gmail.com");
startActivity(intent);
Retrieve on another activity (YourActivity)
String s = getIntent().getStringExtra("USER_NAME");
This is ok for simple kind data type.
But if u want to pass complex data in between activity u need to serialize it first.
Here we have Employee Model
class Employee{
private String empId;
private int age;
print Double salary;
getters...
setters...
}
You can use Gson lib provided by google to serialize the complex data
like this
String strEmp = new Gson().toJson(emp);
Intent intent = new Intent(getBaseContext(), YourActivity.class);
intent.putExtra("EMP", strEmp);
startActivity(intent);
Bundle bundle = getIntent().getExtras();
String empStr = bundle.getString("EMP");
Gson gson = new Gson();
Type type = new TypeToken<Employee>() {
}.getType();
Employee selectedEmp = gson.fromJson(empStr, type);
1st way: In your current Activity, when you create an object of intent to open a new screen:
String value="xyz";
Intent intent = new Intent(CurrentActivity.this, NextActivity.class);
intent.putExtra("key", value);
startActivity(intent);
Then in the nextActivity in the onCreate method, retrieve those values which you pass from the previous activity:
if (getIntent().getExtras() != null) {
String value = getIntent().getStringExtra("key");
//The key argument must always match that used send and retrieve value from one activity to another.
}
2nd way: You can create a bundle object and put values in a bundle and then put the bundle object in intent from your current activity -
String value="xyz";
Intent intent = new Intent(CurrentActivity.this, NextActivity.class);
Bundle bundle = new Bundle();
bundle.putInt("key", value);
intent.putExtra("bundle_key", bundle);
startActivity(intent);
Then in the nextActivity in the onCreate method, retrieve those values which you pass from the previous activity:
if (getIntent().getExtras() != null) {
Bundle bundle = getIntent().getStringExtra("bundle_key");
String value = bundle.getString("key");
//The key argument must always match that used send and retrieve value from one activity to another.
}
You can also use the bean class to pass data between classes using serialization.
/*
* If you are from transferring data from one class that doesn't
* extend Activity, then you need to do something like this.
*/
public class abc {
Context context;
public abc(Context context) {
this.context = context;
}
public void something() {
context.startactivity(new Intent(context, anyone.class).putextra("key", value));
}
}
I recently released Vapor API, a jQuery flavored Android framework that makes all sorts of tasks like this simpler. As mentioned, SharedPreferences is one way you could do this.
VaporSharedPreferences is implemented as Singleton so that is one option, and in Vapor API it has a heavily overloaded .put(...) method so you don't have to explicitly worry about the datatype you are committing - providing it is supported. It is also fluent, so you can chain calls:
$.prefs(...).put("val1", 123).put("val2", "Hello World!").put("something", 3.34);
It also optionally autosaves changes, and unifies the reading and writing process under-the-hood so you don't need to explicitly retrieve an Editor like you do in standard Android.
Alternatively you could use an Intent. In Vapor API you can also use the chainable overloaded .put(...) method on a VaporIntent:
$.Intent().put("data", "myData").put("more", 568)...
And pass it as an extra, as mentioned in the other answers. You can retrieve extras from your Activity, and furthermore if you are using VaporActivity this is done for you automatically so you can use:
this.extras()
To retrieve them at the other end in the Activity you switch to.
Hope that is of interest to some :)
First Activity:
Intent intent = new Intent(getApplicationContext(), ClassName.class);
intent.putExtra("Variable name", "Value you want to pass");
startActivity(intent);
Second Activity:
String str= getIntent().getStringExtra("Variable name which you sent as an extra");
Use a global class:
public class GlobalClass extends Application
{
private float vitamin_a;
public float getVitaminA() {
return vitamin_a;
}
public void setVitaminA(float vitamin_a) {
this.vitamin_a = vitamin_a;
}
}
You can call the setters and the getters of this class from all other classes.
Do do that, you need to make a GlobalClass-Object in every Actitity:
GlobalClass gc = (GlobalClass) getApplication();
Then you can call for example:
gc.getVitaminA()

Pass int value from one activity to two other activities in android [duplicate]

I have a scenario where, after logging in through a login page, there will be a sign-out button on each activity.
On clicking sign-out, I will be passing the session id of the signed in user to sign-out. Can anyone guide me on how to keep session id available to all activities?
Any alternative to this case
In your current Activity, create a new Intent:
String value="Hello world";
Intent i = new Intent(CurrentActivity.this, NewActivity.class);
i.putExtra("key",value);
startActivity(i);
Then in the new Activity, retrieve those values:
Bundle extras = getIntent().getExtras();
if (extras != null) {
String value = extras.getString("key");
//The key argument here must match that used in the other activity
}
Use this technique to pass variables from one Activity to the other.
The easiest way to do this would be to pass the session id to the signout activity in the Intent you're using to start the activity:
Intent intent = new Intent(getBaseContext(), SignoutActivity.class);
intent.putExtra("EXTRA_SESSION_ID", sessionId);
startActivity(intent);
Access that intent on the next activity:
String sessionId = getIntent().getStringExtra("EXTRA_SESSION_ID");
The docs for Intents has more information (look at the section titled "Extras").
Passing Intent extras is a good approach as Erich noted.
The Application object is another way though, and it is sometimes easier when dealing with the same state across multiple activities (as opposed to having to get/put it everywhere), or objects more complex than primitives and Strings.
You can extend Application, and then set/get whatever you want there and access it from any Activity (in the same application) with getApplication().
Also keep in mind that other approaches you might see, like statics, can be problematic because they can lead to memory leaks. Application helps solve this too.
Source class:
Intent myIntent = new Intent(this, NewActivity.class);
myIntent.putExtra("firstName", "Your First Name Here");
myIntent.putExtra("lastName", "Your Last Name Here");
startActivity(myIntent)
Destination Class (NewActivity class):
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.view);
Intent intent = getIntent();
String fName = intent.getStringExtra("firstName");
String lName = intent.getStringExtra("lastName");
}
You just have to send extras while calling your intent.
Like this:
Intent intent = new Intent(getApplicationContext(), SecondActivity.class);
intent.putExtra("Variable name", "Value you want to pass");
startActivity(intent);
Now on the OnCreate method of your SecondActivity you can fetch the extras like this.
If the value you sent was in long:
long value = getIntent().getLongExtra("Variable name which you sent as an extra", defaultValue(you can give it anything));
If the value you sent was a String:
String value = getIntent().getStringExtra("Variable name which you sent as an extra");
If the value you sent was a Boolean:
Boolean value = getIntent().getBooleanExtra("Variable name which you sent as an extra", defaultValue);
It helps me to see things in context. Here are two examples.
Passing Data Forward
Main Activity
Put the data you want to send in an Intent with a key-value pair. See this answer for naming conventions for the key.
Start the Second Activity with startActivity.
MainActivity.java
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
// "Go to Second Activity" button click
public void onButtonClick(View view) {
// get the text to pass
EditText editText = (EditText) findViewById(R.id.editText);
String textToPass = editText.getText().toString();
// start the SecondActivity
Intent intent = new Intent(this, SecondActivity.class);
intent.putExtra(Intent.EXTRA_TEXT, textToPass);
startActivity(intent);
}
}
Second Activity
You use getIntent() to get the Intent that started the second activity. Then you can extract the data with getExtras() and the key you defined in the first activity. Since our data is a String we will just use getStringExtra here.
SecondActivity.java
public class SecondActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
// get the text from MainActivity
Intent intent = getIntent();
String text = intent.getStringExtra(Intent.EXTRA_TEXT);
// use the text in a TextView
TextView textView = (TextView) findViewById(R.id.textView);
textView.setText(text);
}
}
Passing Data Back
Main Activity
Start the Second Activity with startActivityForResult, providing it an arbitrary result code.
Override onActivityResult. This is called when the Second Activity finishes. You can make sure that it is actually the Second Activity by checking the result code. (This is useful when you are starting multiple different activities from the same main activity.)
Extract the data you got from the return Intent. The data is extracted using a key-value pair. I could use any string for the key but I'll use the predefined Intent.EXTRA_TEXT since I'm sending text.
MainActivity.java
public class MainActivity extends AppCompatActivity {
private static final int SECOND_ACTIVITY_REQUEST_CODE = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
// "Go to Second Activity" button click
public void onButtonClick(View view) {
// Start the SecondActivity
Intent intent = new Intent(this, SecondActivity.class);
startActivityForResult(intent, SECOND_ACTIVITY_REQUEST_CODE);
}
// This method is called when the second activity finishes
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// check that it is the SecondActivity with an OK result
if (requestCode == SECOND_ACTIVITY_REQUEST_CODE) {
if (resultCode == RESULT_OK) {
// get String data from Intent
String returnString = data.getStringExtra(Intent.EXTRA_TEXT);
// set text view with string
TextView textView = (TextView) findViewById(R.id.textView);
textView.setText(returnString);
}
}
}
}
Second Activity
Put the data that you want to send back to the previous activity into an Intent. The data is stored in the Intent using a key-value pair. I chose to use Intent.EXTRA_TEXT for my key.
Set the result to RESULT_OK and add the intent holding your data.
Call finish() to close the Second Activity.
SecondActivity.java
public class SecondActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
}
// "Send text back" button click
public void onButtonClick(View view) {
// get the text from the EditText
EditText editText = (EditText) findViewById(R.id.editText);
String stringToPassBack = editText.getText().toString();
// put the String to pass back into an Intent and close this activity
Intent intent = new Intent();
intent.putExtra(Intent.EXTRA_TEXT, stringToPassBack);
setResult(RESULT_OK, intent);
finish();
}
}
Updated Note that I had mentioned the use of SharedPreference. It has a simple API and is accessible across an application's activities. But this is a clumsy solution, and is a security risk if you pass around sensitive data. It's best to use intents. It has an extensive list of overloaded methods that can be used to better transfer many different data types between activities. Have a look at intent.putExtra. This link presents the use of putExtra quite well.
In passing data between activities, my preferred approach is to create a static method for the relevant activity that includes the required parameters launch the intent. Which then provides easily setup and retrieve parameters. So it can look like this
public class MyActivity extends Activity {
public static final String ARG_PARAM1 = "arg_param1";
...
public static getIntent(Activity from, String param1, Long param2...) {
Intent intent = new Intent(from, MyActivity.class);
intent.putExtra(ARG_PARAM1, param1);
intent.putExtra(ARG_PARAM2, param2);
return intent;
}
....
// Use it like this.
startActivity(MyActvitiy.getIntent(FromActivity.this, varA, varB, ...));
...
Then you can create an intent for the intended activity and ensure you have all the parameters. You can adapt for fragments to. A simple example above, but you get the idea.
Try to do the following:
Create a simple "helper" class (factory for your Intents), like this:
import android.content.Intent;
public class IntentHelper {
public static final Intent createYourSpecialIntent(Intent src) {
return new Intent("YourSpecialIntent").addCategory("YourSpecialCategory").putExtras(src);
}
}
This will be the factory for all your Intents. Everytime you need a new Intent, create a static factory method in IntentHelper. To create a new Intent you should just say it like this:
IntentHelper.createYourSpecialIntent(getIntent());
In your activity. When you want to "save" some data in a "session" just use the following:
IntentHelper.createYourSpecialIntent(getIntent()).putExtra("YOUR_FIELD_NAME", fieldValueToSave);
And send this Intent. In the target Activity your field will be available as:
getIntent().getStringExtra("YOUR_FIELD_NAME");
So now we can use Intent like same old session (like in servlets or JSP).
You can also pass custom class objects by making a parcelable class. Best way to make it parcelable is to write your class and then simply paste it to a site like http://www.parcelabler.com/. Click on build and you will get new code. Copy all of this and replace the original class contents.
Then-
Intent intent = new Intent(getBaseContext(), NextActivity.class);
Foo foo = new Foo();
intent.putExtra("foo", foo);
startActivity(intent);
and get the result in NextActivity like-
Foo foo = getIntent().getExtras().getParcelable("foo");
Now you can simply use the foo object like you would have used.
Another way is to use a public static field in which you store data, i.e.:
public class MyActivity extends Activity {
public static String SharedString;
public static SomeObject SharedObject;
//...
The most convenient way to pass data between activities is by passing intents. In the first activity from where you want to send data, you should add code,
String str = "My Data"; //Data you want to send
Intent intent = new Intent(FirstActivity.this, SecondActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.putExtra("name",str); //Here you will add the data into intent to pass bw activites
v.getContext().startActivity(intent);
You should also import
import android.content.Intent;
Then in the next Acitvity(SecondActivity), you should retrieve the data from the intent using the following code.
String name = this.getIntent().getStringExtra("name");
You can use SharedPreferences...
Logging. Time store session id in SharedPreferences
SharedPreferences preferences = getSharedPreferences("session",getApplicationContext().MODE_PRIVATE);
Editor editor = preferences.edit();
editor.putString("sessionId", sessionId);
editor.commit();
Signout. Time fetch session id in sharedpreferences
SharedPreferences preferences = getSharedPreferences("session", getApplicationContext().MODE_PRIVATE);
String sessionId = preferences.getString("sessionId", null);
If you don't have the required session id, then remove sharedpreferences:
SharedPreferences settings = context.getSharedPreferences("session", Context.MODE_PRIVATE);
settings.edit().clear().commit();
That is very useful, because one time you save the value and then retrieve anywhere of activity.
From Activity
int n= 10;
Intent in = new Intent(From_Activity.this,To_Activity.class);
Bundle b1 = new Bundle();
b1.putInt("integerNumber",n);
in.putExtras(b1);
startActivity(in);
To Activity
Bundle b2 = getIntent().getExtras();
int m = 0;
if(b2 != null){
m = b2.getInt("integerNumber");
}
The standard approach.
Intent i = new Intent(this, ActivityTwo.class);
AutoCompleteTextView textView = (AutoCompleteTextView) findViewById(R.id.autocomplete);
String getrec=textView.getText().toString();
Bundle bundle = new Bundle();
bundle.putString(“stuff”, getrec);
i.putExtras(bundle);
startActivity(i);
Now in your second activity retrieve your data from the bundle:
Get the bundle
Bundle bundle = getIntent().getExtras();
Extract the data…
String stuff = bundle.getString(“stuff”);
Kotlin
Pass from First Activity
val intent = Intent(this, SecondActivity::class.java)
intent.putExtra("key", "value")
startActivity(intent)
Get in Second Activity
val value = intent.getStringExtra("key")
Suggestion
Always put keys in constant file for more managed way.
companion object {
val KEY = "key"
}
You can send data between activities using intent object.
Consider you have two activities namely FirstActivity and SecondActivity.
Inside FirstActivity:
Using Intent:
i = new Intent(FirstActivity.this,SecondActivity.class);
i.putExtra("key", value);
startActivity(i)
Inside SecondActivity
Bundle bundle= getIntent().getExtras();
Now you can use different bundle class methods to get values passed from FirstActivity by Key.
E.g.
bundle.getString("key"),bundle.getDouble("key") ,bundle.getInt("key") etc.
If you want to tranfer bitmap between Activites/Fragments
Activity
To pass a bitmap between Activites
Intent intent = new Intent(this, Activity.class);
intent.putExtra("bitmap", bitmap);
And in the Activity class
Bitmap bitmap = getIntent().getParcelableExtra("bitmap");
Fragment
To pass a bitmap between Fragments
SecondFragment fragment = new SecondFragment();
Bundle bundle = new Bundle();
bundle.putParcelable("bitmap", bitmap);
fragment.setArguments(bundle);
To receive inside the SecondFragment
Bitmap bitmap = getArguments().getParcelable("bitmap");
Transfering Large Bitmaps
If you are getting failed binder transaction, this means you are exceeding the binder transaction buffer by transferring large element from one activity to another activity.
So in that case you have to compress the bitmap as an byte's array and then uncompress it in another activity, like this
In the FirstActivity
Intent intent = new Intent(this, SecondActivity.class);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPG, 100, stream);
byte[] bytes = stream.toByteArray();
intent.putExtra("bitmapbytes",bytes);
And in the SecondActivity
byte[] bytes = getIntent().getByteArrayExtra("bitmapbytes");
Bitmap bmp = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
Intent intent = new Intent(YourCurrentActivity.this, YourActivityName.class);
intent.putExtra("NAme","John");
intent.putExtra("Id",1);
startActivity(intent);
You can retrieve it in another activity. Two ways:
int id = getIntent.getIntExtra("id", /* defaltvalue */ 2);
The second way is:
Intent i = getIntent();
String name = i.getStringExtra("name");
Supplemental Answer: Naming Conventions for the Key String
The actual process of passing data has already been answered, however most of the answers use hard coded strings for the key name in the Intent. This is usually fine when used only within your app. However, the documentation recommends using the EXTRA_* constants for standardized data types.
Example 1: Using Intent.EXTRA_* keys
First activity
Intent intent = new Intent(getActivity(), SecondActivity.class);
intent.putExtra(Intent.EXTRA_TEXT, "my text");
startActivity(intent);
Second activity:
Intent intent = getIntent();
String myText = intent.getExtras().getString(Intent.EXTRA_TEXT);
Example 2: Defining your own static final key
If one of the Intent.EXTRA_* Strings does not suit your needs, you can define your own at the beginning of the first activity.
static final String EXTRA_STUFF = "com.myPackageName.EXTRA_STUFF";
Including the package name is just a convention if you are only using the key in your own app. But it is a necessity to avoid naming conflicts if you are creating some sort of service that other apps can call with an Intent.
First activity:
Intent intent = new Intent(getActivity(), SecondActivity.class);
intent.putExtra(EXTRA_STUFF, "my text");
startActivity(intent);
Second activity:
Intent intent = getIntent();
String myText = intent.getExtras().getString(FirstActivity.EXTRA_STUFF);
Example 3: Using a String resource key
Although not mentioned in the documentation, this answer recommends using a String resource to avoid dependencies between activities.
strings.xml
<string name="EXTRA_STUFF">com.myPackageName.MY_NAME</string>
First activity
Intent intent = new Intent(getActivity(), SecondActivity.class);
intent.putExtra(getString(R.string.EXTRA_STUFF), "my text");
startActivity(intent);
Second activity
Intent intent = getIntent();
String myText = intent.getExtras().getString(getString(R.string.EXTRA_STUFF));
Here is my best practice and it helps a lot when the project is huge and complex.
Suppose that I have 2 activities, LoginActivity and HomeActivity.
I want to pass 2 parameters (username & password) from LoginActivity to HomeActivity.
First, I create my HomeIntent
public class HomeIntent extends Intent {
private static final String ACTION_LOGIN = "action_login";
private static final String ACTION_LOGOUT = "action_logout";
private static final String ARG_USERNAME = "arg_username";
private static final String ARG_PASSWORD = "arg_password";
public HomeIntent(Context ctx, boolean isLogIn) {
this(ctx);
//set action type
setAction(isLogIn ? ACTION_LOGIN : ACTION_LOGOUT);
}
public HomeIntent(Context ctx) {
super(ctx, HomeActivity.class);
}
//This will be needed for receiving data
public HomeIntent(Intent intent) {
super(intent);
}
public void setData(String userName, String password) {
putExtra(ARG_USERNAME, userName);
putExtra(ARG_PASSWORD, password);
}
public String getUsername() {
return getStringExtra(ARG_USERNAME);
}
public String getPassword() {
return getStringExtra(ARG_PASSWORD);
}
//To separate the params is for which action, we should create action
public boolean isActionLogIn() {
return getAction().equals(ACTION_LOGIN);
}
public boolean isActionLogOut() {
return getAction().equals(ACTION_LOGOUT);
}
}
Here is how I pass the data in my LoginActivity
public class LoginActivity extends AppCompatActivity {
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
String username = "phearum";
String password = "pwd1133";
final boolean isActionLogin = true;
//Passing data to HomeActivity
final HomeIntent homeIntent = new HomeIntent(this, isActionLogin);
homeIntent.setData(username, password);
startActivity(homeIntent);
}
}
Final step, here is how I receive the data in HomeActivity
public class HomeActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
//This is how we receive the data from LoginActivity
//Make sure you pass getIntent() to the HomeIntent constructor
final HomeIntent homeIntent = new HomeIntent(getIntent());
Log.d("HomeActivity", "Is action login? " + homeIntent.isActionLogIn());
Log.d("HomeActivity", "username: " + homeIntent.getUsername());
Log.d("HomeActivity", "password: " + homeIntent.getPassword());
}
}
Done! Cool :) I just want to share my experience. If you working on small project this shouldn't be the big problem. But when your working on big project, it really pain when you want to do refactoring or fixing bugs.
The passing of data between activities is mainly by means of an intent object.
First you have to attach the data to the intent object with the use of the Bundle class. Then call the activity using either startActivity() or startActivityForResult() methods.
You can find more information about it, with an example from the blog post Passing data to an Activity.
You can try Shared Preference, it may be a good alternative for sharing data between the activities
To save session id -
SharedPreferences pref = myContexy.getSharedPreferences("Session
Data",MODE_PRIVATE);
SharedPreferences.Editor edit = pref.edit();
edit.putInt("Session ID", session_id);
edit.commit();
To get them -
SharedPreferences pref = myContexy.getSharedPreferences("Session Data", MODE_PRIVATE);
session_id = pref.getInt("Session ID", 0);
You can use Intent
Intent mIntent = new Intent(FirstActivity.this, SecondActivity.class);
mIntent.putExtra("data", data);
startActivity(mIntent);
Another way could be using singleton pattern also:
public class DataHolder {
private static DataHolder dataHolder;
private List<Model> dataList;
public void setDataList(List<Model>dataList) {
this.dataList = dataList;
}
public List<Model> getDataList() {
return dataList;
}
public synchronized static DataHolder getInstance() {
if (dataHolder == null) {
dataHolder = new DataHolder();
}
return dataHolder;
}
}
From your FirstActivity
private List<Model> dataList = new ArrayList<>();
DataHolder.getInstance().setDataList(dataList);
On SecondActivity
private List<Model> dataList = DataHolder.getInstance().getDataList();
Write following code in CurrentActivity.java
Intent i = new Intent(CurrentActivity.this, SignOutActivity.class);
i.putExtra("SESSION_ID",sessionId);
startActivity(i);
Access SessionId in SignOutActivity.java is following way
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sign_out);
Intent intent = getIntent();
// check intent is null or not
if(intent != null){
String sessionId = intent.getStringExtra("SESSION_ID");
Log.d("Session_id : " + sessionId);
}
else{
Toast.makeText(SignOutActivity.this, "Intent is null", Toast.LENGTH_SHORT).show();
}
}
Start another activity from this activity pass parameters via Bundle Object
Intent intent = new Intent(getBaseContext(), YourActivity.class);
intent.putExtra("USER_NAME", "xyz#gmail.com");
startActivity(intent);
Retrieve on another activity (YourActivity)
String s = getIntent().getStringExtra("USER_NAME");
This is ok for simple kind data type.
But if u want to pass complex data in between activity u need to serialize it first.
Here we have Employee Model
class Employee{
private String empId;
private int age;
print Double salary;
getters...
setters...
}
You can use Gson lib provided by google to serialize the complex data
like this
String strEmp = new Gson().toJson(emp);
Intent intent = new Intent(getBaseContext(), YourActivity.class);
intent.putExtra("EMP", strEmp);
startActivity(intent);
Bundle bundle = getIntent().getExtras();
String empStr = bundle.getString("EMP");
Gson gson = new Gson();
Type type = new TypeToken<Employee>() {
}.getType();
Employee selectedEmp = gson.fromJson(empStr, type);
1st way: In your current Activity, when you create an object of intent to open a new screen:
String value="xyz";
Intent intent = new Intent(CurrentActivity.this, NextActivity.class);
intent.putExtra("key", value);
startActivity(intent);
Then in the nextActivity in the onCreate method, retrieve those values which you pass from the previous activity:
if (getIntent().getExtras() != null) {
String value = getIntent().getStringExtra("key");
//The key argument must always match that used send and retrieve value from one activity to another.
}
2nd way: You can create a bundle object and put values in a bundle and then put the bundle object in intent from your current activity -
String value="xyz";
Intent intent = new Intent(CurrentActivity.this, NextActivity.class);
Bundle bundle = new Bundle();
bundle.putInt("key", value);
intent.putExtra("bundle_key", bundle);
startActivity(intent);
Then in the nextActivity in the onCreate method, retrieve those values which you pass from the previous activity:
if (getIntent().getExtras() != null) {
Bundle bundle = getIntent().getStringExtra("bundle_key");
String value = bundle.getString("key");
//The key argument must always match that used send and retrieve value from one activity to another.
}
You can also use the bean class to pass data between classes using serialization.
/*
* If you are from transferring data from one class that doesn't
* extend Activity, then you need to do something like this.
*/
public class abc {
Context context;
public abc(Context context) {
this.context = context;
}
public void something() {
context.startactivity(new Intent(context, anyone.class).putextra("key", value));
}
}
I recently released Vapor API, a jQuery flavored Android framework that makes all sorts of tasks like this simpler. As mentioned, SharedPreferences is one way you could do this.
VaporSharedPreferences is implemented as Singleton so that is one option, and in Vapor API it has a heavily overloaded .put(...) method so you don't have to explicitly worry about the datatype you are committing - providing it is supported. It is also fluent, so you can chain calls:
$.prefs(...).put("val1", 123).put("val2", "Hello World!").put("something", 3.34);
It also optionally autosaves changes, and unifies the reading and writing process under-the-hood so you don't need to explicitly retrieve an Editor like you do in standard Android.
Alternatively you could use an Intent. In Vapor API you can also use the chainable overloaded .put(...) method on a VaporIntent:
$.Intent().put("data", "myData").put("more", 568)...
And pass it as an extra, as mentioned in the other answers. You can retrieve extras from your Activity, and furthermore if you are using VaporActivity this is done for you automatically so you can use:
this.extras()
To retrieve them at the other end in the Activity you switch to.
Hope that is of interest to some :)
First Activity:
Intent intent = new Intent(getApplicationContext(), ClassName.class);
intent.putExtra("Variable name", "Value you want to pass");
startActivity(intent);
Second Activity:
String str= getIntent().getStringExtra("Variable name which you sent as an extra");
Use a global class:
public class GlobalClass extends Application
{
private float vitamin_a;
public float getVitaminA() {
return vitamin_a;
}
public void setVitaminA(float vitamin_a) {
this.vitamin_a = vitamin_a;
}
}
You can call the setters and the getters of this class from all other classes.
Do do that, you need to make a GlobalClass-Object in every Actitity:
GlobalClass gc = (GlobalClass) getApplication();
Then you can call for example:
gc.getVitaminA()

Multiple Intents in a Single Activity

Having issues with sending multiple pieces of data (in this case, three arrays(two int, one string)) over to a second activity page.
I am unsure of how this is done. What I would like to know is how to send these arrays in one Start Activity method, if that is possible. My current code is:
public void onClickGoToTeamSummary(View view)
{
Intent intentTeamNames = new Intent(MainActivity.this, ResultsActivity.class);
Intent intentTeamPoints = new Intent(MainActivity.this, ResultsActivity.class);
Intent intentTeamGoals = new Intent(MainActivity.this, ResultsActivity.class);
intentTeamNames.putExtra("footballClubs", myTeams);
intentTeamPoints.putExtra("clubPoints", pointsAttained);
intentTeamGoals.putExtra("clubGoals", goalsScored);
startActivity(intentTeamPoints);
startActivity(intentTeamNames);
startActivity(intentTeamGoals);
}
I had tried:
startActivity(intentTeamPoints, intentTeamNames, intentTeamGoals);
to no avail. To help, my getIntent in the next activity looks like this:
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_results);
Intent intentClubNames = getIntent();
String[] club_names = intentClubNames.getStringArrayExtra("footballClubs");
Intent intentClubPoints = getIntent();
int[] team_points = intentClubPoints.getIntArrayExtra("clubPoints");
Intent intentTeamGoals = getIntent();
int[] club_goals = intentTeamGoals.getIntArrayExtra("clubGoals");
}
The code itself works provided only one startActivity is used. I would like to know how to pass all my arrays into the second activity page through one activity if anyone can help me.
Try this..
You can send all values in single Intent
public void onClickGoToTeamSummary(View view)
{
Intent intentTeamNames = new Intent(MainActivity.this, ResultsActivity.class);
intentTeamNames.putExtra("footballClubs", myTeams);
intentTeamNames.putExtra("clubPoints", pointsAttained);
intentTeamNames.putExtra("clubGoals", goalsScored);
startActivity(intentTeamNames);
}
and
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_results);
Intent intentClubNames = getIntent();
String[] club_names = intentClubNames.getStringArrayExtra("footballClubs");
int[] team_points = intentClubNames.getIntArrayExtra("clubPoints");
int[] club_goals = intentClubNames.getIntArrayExtra("clubGoals");
}
You don't use multiple Intents but multiple extras.
// create your Intent as normal
Intent myIntent = new Intent(MainActivity.this, ResultsActivity.class);
// then you can add multiple extras
myIntent.putExtra("footballClubs", myTeams);
myIntent.putExtra("clubPoints", pointsAttained);
myIntent.putExtra("clubGoals", goalsScored);
startActivity(myIntent);
Then receiving them would be the same. You would just receive the one Intent and use the key as normal for each extra Array.

Categories

Resources