I'm trying to pass the value of an editText from a class to another. In the first class, I use this code to obtain the value of the editText:
number = (EditText) this.findViewById(R.id.editText10);
text=number.getText().toString();//obtain the value
where "text" is a static string. Later I use this code that returns the STATIC string "text":
public static String rete()
{
return text;
}
And finally, I get the value in the second class using this:
String text2 = Pruebita2.rete();
where Pruebita2 is the name of the first class.
What am i doing wrong?
Easiest way to transfer data between classes is to pass the string "text" via an intent to the second class.
Eg.
Activity1: Create the intent
Intent intent = new Intent(this, Activity2.class);
intent.putExtra("text_key", text);
context.startActivity(intent);
Activity2: Get the vlaue
text = getIntent().getStringExtra("text_key");
Related
https://developer.android.com/training/basics/firstapp/starting-activity
public class MainActivity extends AppCompatActivity {
public static final String SIGNUP_EMAIL = "com.example.myapplication.SIGNUP_EMAIL";
public static final String SIGNUP_PASSWORD = "com.example.myapplication.SIGNUP_PASSWORD";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void signup(View view) {
Intent intent = new Intent(this, SignupResultActivity.class);
EditText signup_email = (EditText) findViewById(R.id.signup_email);
EditText signup_password = (EditText) findViewById(R.id.signup_password);
String email = signup_email.getText().toString();
String password = signup_password.getText().toString();
intent.putExtra(SIGNUP_EMAIL, email);
intent.putExtra(SIGNUP_PASSWORD, password);
startActivity(intent);
}
}
public static final String SIGNUP_EMAIL = null;
public static final String SIGNUP_PASSWORD = null;
why should not use "null" in this code?
if you put SIGNUP_EMAIL=null and SIGNUP_PASSWORD=null, is not working
Intent is similar to Map, the value of these variables are the keys to index this map. Not only those keys must be non-null, but they must be different from each other.
Quoted from Start another activity (emphasis mine):
The putExtra() method adds the EditText's value to the intent. An Intent can carry data types as key-value pairs called extras. Your key is a public constant EXTRA_MESSAGE because the next activity uses the key to retrieve the text value. It's a good practice to define keys for intent extras using your app's package name as a prefix. This ensures the keys are unique, in case your app interacts with other apps.
SIGNUP_EMAIL and SIGNUP_PASSWORD are not default values for mail and password, they are string keys used to pass ang get the values, so they cannot be null.
They are public constants so that the intent can know them to retreive the value.
EDIT: note that the strings are declared final so that the keys cannot be changed afterwards, having a property declared final with a null value should have raised a mental flag as it is a bit useless..
when you want to pass a data from one activity to another one you should use intent.putExtra(name,data);
first parameter is the name and second is data that you want to send
you can use any string that you want for name parameter but it cant be null
in second activity you use it to get data from first activity by this code :
intent.getStringExtra(name)
You can use any unique string to map the values. Null wont work but "null" will work. But keep one thing in mind that for two different values you need to assign different keys also.
Like this:
public static final String SIGNUP_EMAIL = "null";
public static final String SIGNUP_PASSWORD = "Null";
I know about this and it works fine
Intent i1 = new Intent(Login.this, Welcome.class);
i1.putExtra("username","the name");
startActivity(i1);
and this in the next layout:
String username = getIntent().getStringExtra("username");
but i need to tranfer a final string, I tried this but it doesnt work:
public static final String ADMIN_USERNAME= "user";
Intent intent = new Intent(Login.this,SignUp.class);
intent.putExtra("admin_username",ADMIN_USERNAME);
startActivity(intent);
and this in the next layout:
public final String ADMIN_USERNAME= getIntent().getStringExtra("admin_username");
im getting this error:
Attempt to invoke virtual method 'java.lang.String android.content.Intent.getStringExtra(java.lang.String)' on a null object reference
When you declare a string constant as static like this:
public static final String ADMIN_USERNAME= "user";
you don't need to use intent extras to access to the value in another activity, just access the ADMIN_USERNAME string constant directly:
if (someString.equals(MyActivity.ADMIN_USERNAME)) {
//Do something....
}
Your intent is null. İt's a early call in lifecycle
String username = getIntent().getStringExtra("admin_username");
Make sure you call this line in onCreate if you are calling inside onAttach
Also make sure your key is correct. Please notice I fixed it also as "admin_username"
Good luck
Emre
i'm new in developing android in xamarin i just want to ask in how to pass data through other activity using intent ? This thing work (https://developer.xamarin.com/recipes/android/fundamentals/activity/pass_data_between_activity/) but i want to collect first all the data in 2 activity before they show the summary in my 3rd activity.(by the way i'm creating a registration app thanks for the future answers :) )
On the first activity you create the second activity by an intent and use the method PutExtra to pass the data you want with a relevant key name that you will need after starting the new activity to retrieve the data.
var secondActivity = new Intent (this, typeof(SecondActivity));
secondActivity.PutExtra ("Data", "Sample Data");
StartActivity(secondActivity);
On second activity OnCreate retrieve the data using the key name it was stored with and the correct method relevant to the data type passed. In this example as is a string by calling Intent.GetStringExtra.
string text = Intent.GetStringExtra ("Data") ?? "Data not available";
You can repeat 1 & 2 for the summary activity.
you can pass whole object and desterilize that in another activity like this
//To pass:
intent.putExtra("yourKey", item);
// To retrieve object in second Activity
getIntent().getSerializableExtra("yourKey");
For only single value you can use
//Method 1
string code = Intent.GetStringExtra("id") ?? string.Empty;
string name = Intent.GetStringExtra("Name") ?? string.Empty;
//OR
//Method 2
string Id = Intent.GetStringExtra("id") ?? string.Empty;
Item item = new Item();
item = itemRepo.Find(Convert.ToInt32(id));
I am currently learning how to program in Android. I read that the keys for Extras (to be put in an intent) usually start with the word "EXTRA", for example:
public static final String EXTRA_USER_CHEATED = "some unique string";
And that keys to objects that are to be saved in the Bundle usually start with the word "KEY", for example:
public static final String KEY_USER_CHEATED = "some other unique string";
What if I have a variable that I need to pass to another activity as an Extra, but I also need to be able to save that same variable in the Bundle for an activity? Should I
have two keys for the variable (i.e. have both EXTRA_USER_CHEATED and KEY_USER_CHEATED), or
have a single key for the variable (this idea seems better to me, but I am a total Android newbie)? If so, what should it be called (should it be called EXTRA_USER_CHEATED, KEY_USER_CHEATED, just USER_CHEATED, or something else)?
I can't be sure of the answer, but from my understanding, the EXTRA_MESSAGE OR the KEY is merely a key to some value. You can have 2 different keys which point to the same data, so to answer your question, maybe just have both (i.e. option 1).
This short code snippet might give you a clue... notice that String message is the value associated with the key which is EXTRA_MESSAGE (see documentation for the putExtra method).
public static final String EXTRA_MESSAGE = "com.whatever.appName.MESSAGE";
public void sendMessage(View view){
Intent intent = new Intent(this, DisplayMessageActivity.class);
EditText editText = (EditText) findViewById(R.id.edit_message);
String message = editText.getText().toString();
intent.putExtra(EXTRA_MESSAGE, message);
startActivity(intent);
}
I would like to be able to transfer data from one activity to another activity. How can this be done?
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>);
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/
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);
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); }
Hopefully you will find the answer from here Send Data to Another Activity - Simple Android Login
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);
Your Purpose
Suppose You want to Go From Activity A to Activity B.
So We Use an Intent to switch activity
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");
}
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.