22

I would like to be able to transfer data from one activity to another activity. How can this be done?

ChallengeAccepted
  • 1,684
  • 1
  • 16
  • 25
user555910
  • 2,627
  • 6
  • 22
  • 28
  • What code have you tried so far? What isn't working? – dave.c Feb 11 '11 at 10:11
  • I guess you are not trying to transfer a ZIP file. Take a look at here http://stackoverflow.com/questions/4872856/data-transfer-from-one-activity-to-another-activity-on-button-click-event – Vikas Patidar Feb 11 '11 at 10:14

8 Answers8

31

Through the below code we can send the values between activities

use the below code in parent activity

Intent myintent=new Intent(Info.this, GraphDiag.class).putExtra("<StringName>", value);
startActivity(myintent);

use the below code in child activity

String s= getIntent().getStringExtra(<StringName>);
AdamMc331
  • 16,492
  • 10
  • 71
  • 133
Pinki
  • 21,723
  • 16
  • 55
  • 88
14

There are couple of ways by which you can access variables or object in other classes or Activity.

A. Database

B. shared preferences.

C. Object serialization.

D. A class which can hold common data can be named as Common Utilities it depends on you.

E. Passing data through Intents and Parcelable Interface.

It depend upon your project needs.

A. Database

SQLite is an Open Source Database which is embedded into Android. SQLite supports standard relational database features like SQL syntax, transactions and prepared statements.

Tutorials -- http://www.vogella.com/articles/AndroidSQLite/article.html

B. Shared Preferences

Suppose you want to store username. So there will be now two thing a Key Username, Value Value.

How to store

 // Create object of SharedPreferences.
 SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(this);
 //now get Editor
 SharedPreferences.Editor editor = sharedPref.edit();
 //put your value
 editor.putString("userName", "stackoverlow");

 //commits your edits
 editor.commit();

Using putString(),putBoolean(),putInt(),putFloat(),putLong() you can save your desired dtatype.

How to fetch

SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(this);
String userName = sharedPref.getString("userName", "Not Available");

http://developer.android.com/reference/android/content/SharedPreferences.html

C. Object Serialization

Object serlization is used if we want to save an object state to send it over network or you can use it for your purpose also.

Use java beans and store in it as one of his fields and use getters and setter for that

JavaBeans are Java classes that have properties. Think of properties as private instance variables. Since they're private, the only way they can be accessed from outside of their class is through methods in the class. The methods that change a property's value are called setter methods, and the methods that retrieve a property's value are called getter methods.

public class VariableStorage implements Serializable  {

    private String inString ;

    public String getInString() {
        return inString;
    }

    public void setInString(String inString) {
        this.inString = inString;
    }


}

Set the variable in you mail method by using

VariableStorage variableStorage = new VariableStorage();
variableStorage.setInString(inString);

Then use object Serialzation to serialize this object and in your other class deserialize this object.

In serialization an object can be represented as a sequence of bytes that includes the object's data as well as information about the object's type and the types of data stored in the object.

After a serialized object has been written into a file, it can be read from the file and deserialized that is, the type information and bytes that represent the object and its data can be used to recreate the object in memory.

If you want tutorial for this refer this link

http://javawithswaranga.blogspot.in/2011/08/serialization-in-java.html

Get variable in other classes

D. CommonUtilities

You can make a class by your self which can contain common data which you frequently need in your project.

Sample

public class CommonUtilities {

    public static String className = "CommonUtilities";

}

E. Passing Data through Intents

Please refer this tutorial for this option of passing data.

http://shri.blog.kraya.co.uk/2010/04/26/android-parcel-data-to-pass-between-activities-using-parcelable-classes/

Community
  • 1
  • 1
Nikhil Agrawal
  • 26,128
  • 21
  • 90
  • 126
  • Another method is to use a Singleton class which can be acessed throughout the app – Ajith M A Jan 24 '14 at 07:54
  • Thank you man. It really helped. I had an integer value that i wanted share between different activities. In my current code i send data from activity A to activity B then from activity B to Fragment B. If data changes in Frag B I pass the change to activity B through out an interface. Then when activity B finishes i send the data back to activity A and that's not even completed and i have some unfix bugs! Using CommonUtilities class is a way better solution to my problem. I will definitely switch to it. – Alireza Ahmadi May 14 '14 at 13:48
10

When you passing data from one activity to another activity perform like this

In Parent activity:

startActivity(new Intent(presentActivity.this, NextActivity.class).putExtra("KEY_StringName",ValueData)); 

or like shown below in Parent activity

Intent intent  = new Intent(presentActivity.this,NextActivity.class);     
intent.putExtra("KEY_StringName", name);   
intent.putExtra("KEY_StringName1", name1);   
startActivity(intent);

In child Activity perform as shown below

TextView tv = ((TextView)findViewById(R.id.textViewID))
tv.setText(getIntent().getStringExtra("KEY_StringName"));

or do like shown below in child Activity

TextView tv = ((TextView)findViewById(R.id.textViewID));
TextView tv1 = ((TextView)findViewById(R.id.textViewID1))

/* Get values from Intent */
Intent intent = getIntent();         
String name  = intent.getStringExtra("KEY_StringName");
String name1  = intent.getStringExtra("KEY_StringName1");

tv.setText(name);
tv.setText(name1);
Rahul Baradia
  • 11,802
  • 17
  • 73
  • 121
1

Passing data from one activity to other in android

Intent intent = new Intent(context, YourActivityClass.class);
intent.putExtra(KEY, <your value here>);

startActivity(intent);

Retrieving bundle data from android activity

Intent intent = getIntent();
  if (intent!=null) {
  String stringData= intent.getStringExtra(KEY);
  int numberData = intent.getIntExtra(KEY, defaultValue);
  boolean booleanData = intent.getBooleanExtra(KEY, defaultValue);
  char charData = intent.getCharExtra(KEY, defaultValue);   }
katwal-Dipak
  • 3,523
  • 2
  • 23
  • 23
0

Hopefully you will find the answer from here Send Data to Another Activity - Simple Android Login

JSupport
  • 31
  • 1
  • 1
    Whilst this may theoretically answer the question, [it would be preferable](http://meta.stackexchange.com/questions/8231/are-answers-that-just-contain-links-elsewhere-really-good-answers/8259#8259) to include the essential parts of the answer here, and provide the link for reference. – Jason Sturges Oct 20 '12 at 23:05
0

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 u 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 u sent was a "String"

String value = getIntent().getStringExtra("Variable Name which you sent as an extra");

If the value u sent was a "Boolean"

Boolean value = getIntent().getStringExtra("Variable Name which you sent as an extra",defaultValue);

Mayank Saini
  • 3,017
  • 24
  • 25
0

Your Purpose

Suppose You want to Go From Activity A to Activity B.

So We Use an Intent to switch activity

Activity Switch

the typical code Looks Like this -

In Activity A [A.class]

//// Create a New Intent object
Intent i = new Intent(getApplicationContext(), B.class);

/// add what you want to pass from activity A to Activity B
i.putExtra("key", "value");

/// start the intent
startActivity(i);

In Activity B [B.class]

And to Get the Data From the Child Activity

Intent i = getIntent();

if (i!=null) {
   String stringData= i.getStringExtra("key");
}
alamin
  • 2,377
  • 1
  • 26
  • 31
0

This works best:

Through the below code we can send the values between activities

use the below code in parent activity(PARENT CLASS/ VALUE SENDING CLASS)

Intent myintent=new Intent(<PARENTCLASSNAMEHERE>.this,<TARGETCLASSNAMEHERE>.class).putExtra("<StringName>", value);
startActivity(myintent);

use the below code in child activity(TARGET CLASS/ACTIVITY)

String s= getIntent().getStringExtra(<StringName>);

Please see here that "StringName" is the name that the destination/child activity catches while "value" is the variable name, same as in parent/target/sending class.

sudoCoder
  • 115
  • 2
  • 13