How do you pass a string from one activity to another? [duplicate] - java

This question already has answers here:
How do I pass data between Activities in Android application?
(53 answers)
Closed 9 years ago.
I'm wondering how to pass and read a string that is in one activity from another activity. I have two activities. I'll call them Activity1 and Activity2. I have a string in Activity1 called course. I want to read that string in Activity2.
I've tried doing this but the string came out empty.
public class Activity2 extends Activity1 {
I've seen people use the Intent function but I couldn't figure out how to use it.
Any suggestions? Thanks!

Pass values using intents.
In your first activity
Intent i= new Intent("com.example.secondActivity");
i.putExtra("key",mystring);
// for explicit intents
// Intent i= new Intent(ActivityName.this,SecondActivity.class);
// parameter 1 is the key
// parameter 2 is the value
// your value
startActivity(i);
In your second activity retrieve it.
Bundle extras = getIntent().getExtras();
if (extras != null) {
String value = extras.getString("key");
//get the value based on the key
}
To pass custom objects you can have a look at this link
http://www.technotalkative.com/android-send-object-from-one-activity-to-another-activity/

your first activity, Activity1
public class Activity1 extends Activity {
Button btn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity1);
btn=(Button) findViewById(R.id.payBtn);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
Intent intent=new Intent(Activity1.this,Activity2.class);
intent.putExtra("course", "courseValue");
startActivity(intent);
}
});
}
}
Activity2
public class Activity2 extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity2);
String course=getIntent().getExtras().getString("course").toString();
Log.d("course",course);
}
}
Hope this will help you.

You're on the right track - you're using an intent to launch the second activity. All you have to do is add intent.putExtra("title", stringObject); where stringObject is the string you want to pass, and title is the name you want to give that object. You use that name to refer the object passed in the second activity as follows:
String s = (String)getIntent().getExtras().getSerializable("title");

From Activity 1 call something like this :
Intent intent= new Intent("path.secondActivity");
intent.putExtra("keyString",sampleString);
startActiivty(intent);
and in activity 2 try something like this :
Bundle values = getIntent().getExtras();
if (values != null) {
String keyString = values.getString("keyString");
}

In your MainActivity
Intent i= new Intent(MainActivity.this,SecondActivity.class);
i.putExtra("key",yourstring);
startActiivty(i);
In your second activity onCreate()
Bundle extras = getIntent().getExtras();
if (extras != null) {
String value = extras.getString("key");
}

Try this
public class Activity2 extends Activity1

Related

Pass a string from first activity to last activity but running another activity before starting last activity

I'm very new in Android, if the question is repeated please avoid and send the link.
There are three activities A, B and C. Activity A gets a username which I want to get displayed in activity C, but I want to run Activity B first and then run Activity C. The problem using intent is that I have to run C first. If singleton, bundle, or parcelable is the solution can you please provide the code?
Activity A
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final EditText nameText = findViewById(R.id.nameText);
nameText.setOnEditorActionListener(new OnEditorActionListener() {
#Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
String name = nameText.getText().toString();
return true;
}
});
}
Activity B
public class qPage2 extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_q_page2);
android.os.SystemClock.sleep(500);
}
}
Activity C
public class lastPage extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_last_page);
}
}
It's easy than you thought. For example if you want to send a Tasif string from A to C via B.
In activity A
Intent intent = new Intent(A.this, B.class);
intent.putExtra("username", "Tasif");
startActivity(intent);
In activity B
Intent intent = new Intent(B.this, C.class);
intent.putExtras(getIntent()); // Add this line, it will copy all data in intent which starts activity B (including `username`).
startActivity(intent);
In activity C
String username = getIntent().getStringExtra("username");
Declare the String inside Activity "A" as public static and store the string in it from Activity "A" .
eg: Activity A.java
public static String first = "hello";
Then in Activity "C" call it like
Actiivity C.java
String last = A.first;
There are many options for this :
You can use intent as you mentioned
You can make a static Class and declare a static variable with type string
and access it in the C activity .
Code For first option :
For adding value to intent
Intent n = new Intent(FirstActivity.class,SecondActivity.class);
n.putExtra("name" , name);
n.startActivity();
For retrieving it :
Intent intent = getIntent();
String name = intent.getStringExtra("name");
2.Create a static class member and acess it
class static StaticClass{
static name = " ";
}
Update this variable in the first activity and retrive it in last activity
You can store that string in SharedPreferences and can access that string anywhere in your project. If you are not familiar with SharedPreferences read the documentation from this SharedPrefernces Link
A simple and clean approach is to use SharedPreferences data storage option. It is used to save a small collection of data like Key-Value pair.
Save the username in SharedPreferences as below in Activity A:
SharedPreferences sharedPref = getSharedPreferences(
getString("MyKeyPairFileName"), Context.MODE_PRIVATE);
sharedPref.edit().putString("userKey", "Your username").apply;
Read the value from any Activity(B or C or D or...Z) as below:
SharedPreferences sharedPref = getSharedPreferences(
getString("MyKeyPairFileName"), Context.MODE_PRIVATE);
String username = sharedPref.getString("userKey", null);
/*null is the default value, if value for the key is not available*/);
Be careful when using getSharedPreferences vs getPreferences from Activity. You can read more on SharedPreferences here

Sending value from onpostexecute

I am using AsyncTask to perform Background task, After completing my task, I want to set the resultant string from onPostExecute method to another activity's constructor and from there I want to set that string to TextView. when I print log inside the constructor it's printing the string, but when i set the same string on textview, it gives empty string.(the string set on textview is empty, so it simply prints nothing.)
My AsyncTask Code :
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
Log.d("Answer1",s);
new Answer(s);
}
My Answer Activity, in which I am setting the string via constructor and setting value of this string on textview, but this string is empty.
public class Answer extends AppCompatActivity {
TextView textView;
String str;
// Dont Delete this
Answer(){
}
// Here, Log will print right string, but not on textview
Answer(String str){
this.str = str;
Log.d("Answer2",this.str);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_answer);
textView = findViewById(R.id.SetSteps);
// The String set here is empty, can you please elaborate???
textView.setText(str);
}
}
You should never instantiate an Activity youself. The correct way is to pass the desired data througn an intent to the new activity:
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
Intent intent = new Intent(CurrentActivity.this, Answer.class);
intent.putExtra("MY_DATA", s);
startActivity(intent);
}
Then in your Answer activity you can receive the value:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_answer);
textView = findViewById(R.id.SetSteps);
String result = getIntent().getExtras().getString("MY_DATA","");
textView.setText(result);
}
1 - Add a Context variable to your AsyncTask
Context context = getApplicationContext();
2 - in onPostExecute, create a new intent, add your string to the intent and start the activity :
Intent intent = new Intent(context, Answer.class);
intent.putExtra("Answer1",s);
context.startActivity(intent);
3- in your Answer activity, you can get the string from the intent like below:
Intent intent = getIntent();
String answer = intent.getStringExtra("Answer1");
if(answer !=null){
// do what you want
}
PS: Please please, remove constructors from your Activity, it is not recommended

Sending data without having to start a new Activity

So basically my question is just explained in the title. How can I send data between activities without having to start that activity which receive the data. Here's my code: This is the main activity sending the data :
public class MainActivity extends Activity {
private EditText mainedit1;
private TextView maintext1;
private Button mainadd1;
private Button maindone1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
maindone1=(Button) findViewById(R.id.maindone);
mainedit1=(EditText)findViewById(R.id.mainedit1);
maintext1=(TextView)findViewById(R.id.maintext1);
mainadd1=(Button)findViewById(R.id.mainadd);
mainadd1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String test1= mainedit1.getText().toString();
Intent intent = new Intent(MainActivity.this,test.class);
intent.putExtra("word",test1);
startActivity(intent);
}
});
And this is the activity receiving the data :
public class test extends Activity {
TextView testtext;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fortest);
testtext=(TextView)findViewById(R.id.testtext);
Intent intent = getIntent();
String Word = intent.getStringExtra("word");
testtext.setText(Word);
}
So what I did in here is to send the data but also starting the activity, and this is not what I want to share. Please show me how do I fix my code?
It seems you're just looking to save a string for later use. In your MainActivity, just do the following to save the string:
getSharedPreferences("my_prefs", Context.MODE_PRIVATE).edit().putString("word", test1).commit();
Then when you're ready to retrieve it in your test activity, just do so like this:
String Word = getSharedPreferences("my_prefs", Context.MODE_PRIVATE).getString("word", null);
testtext.setText(Word);
You can use sharedprefrence of android following code you can implement
In your MainActivity, just do the following to save the string:
getSharedPreferences("my_prefs", Context.MODE_PRIVATE).edit().putString("word", test1).commit();
Then when you're ready to retrieve it in your test activity, just do so like this:
String Word = getSharedPreferences("my_prefs", Context.MODE_PRIVATE).getString("word", null);
testtext.setText(Word);
OR
Sending data without having to start a new Acitivity, by create static variable
ex.
public class First_Activity extends Activity {
public static String USER_FORMATED_NUMBER = null;
USER_FORMATED_NUMBER="Data you want to pass";
}
public class Second_Activity extends Activity {
String data=First_Activity.USER_FORMATED_NUMBER;
}

android SharedPreferences pass integer to next activity [duplicate]

This question already has answers here:
How do I pass data between Activities in Android application?
(53 answers)
Closed 7 years ago.
how am i going to pass an integer value from the textview to the next activity?
currently im using string as my sharedpreferences and everytime im changing it to int my app force close.
here's my code on mainactivity
int scoreText=50;
public static final String PREFS_COIN= "MyPreferenceFile";
protected void onCreate(Bundle savedInstanceState) {
public void checkAnswer()
{ String answer=answerText.getText().toString();
if(isCorrect(answer))
{
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("What are you a GENIUS?!");
builder.setMessage("Nice one, Genius! You have P10!");
builder.setIcon(android.R.drawable.btn_star);
builder.setPositiveButton("View Trivia",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
scoreText+=10;
scoreNew=scoreText;
scoreTxt.setText(""+ scoreNew);
SharedPreferences settings2=getSharedPreferences(PREFS_COIN, 0);
SharedPreferences.Editor editor2=settings2.edit();
editor2.putString("coins", scoreTxt.getText().toString());
editor2.commit();
Intent intent=new Intent(getApplicationContext(), Luzon1Trivia.class);
startActivity(intent);
overridePendingTransition(R.animator.transition_fade_in, R.animator.transition_fade_out);
//startActivity(new Intent(Luzon1.this, Luzon2.class));
;} });
AlertDialog alert = builder.create();
alert.show(); // Show Alert Dialog
scoreTxt.setVisibility(View.GONE);
//disable all the buttons and textview
answerText.setEnabled(false);
answerButton.setClickable(false);
}
}
everytime the user guessed the correct answer, a +10 coin will be given. the problem is, in the second activity i cannot add/subtract the sharedpreference value since its declared as string. what happens is "60 +10" appears in the textview
here's my code in activity 2
public static final String PREFS_COIN= "MyPreferenceFile";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.luzon2);
scoreTxt = (TextView)findViewById(R.id.score);
SharedPreferences settings2=getSharedPreferences(PREFS_COIN, 0);
scoreTxt.setText(settings2.getString("coins", ""));
You shouldn't use Shared Preferences to pass information between activities, Shared Preferences is inteded to be used to store persistent information when the Application is destroyed.
To pass information between activities you should use an Intent (the same Intent that is used to start the "destiny" activity)
Intent newActivityIntent = new Intent(originActivity.this, destinyActivity.class);
newActivityIntent.putExtra(KEY_STRING, integerValue);
this.startActivity(newActivityIntent);//Assuming you're starting an activity from another one
Edit: This has been also answered here and here. I would recommend you to search before posting a question.
You have to parse the string and get a float/integer value.
int myNewInt = Integer.parseInt("theString");
in your case you have to do :
int myNewInt = Integer.parseInt(settings2.getString("coins", ""));
And I think you need to set the default value as 0 in your
settings2.getString("coins", "0")
Just use a static variable to hold this. It's much easier to implement since all you have to do is call it instead of passing it around to other intents like a mad man.
public static int coins;
To call it use your class instance name:
MyClass.coins;
So to add:
MyClass.coins+=10;
scoreTxt.setText(Integer.toString(MyClass.coins));
MyClass is your class. If your class is called MainActivity then it will be that (MainActivity).
.coins is the variable inside that class, your just making a reference to that variable.
The nice thing about static is using it as a learning tool. It's a great way to explore instances and references.
Or you can add all of this to every activity, and don't forget about handling device rotations:
Intent i = new Intent(getApplicationContext(), MyClass.class);
i.putExtra("coins","value");
startActivity(i);
To retrieve those values:
Bundle extras = getIntent().getExtras();
if (extras != null) {
coins = Integer.parseInt(extras.getString("coins"));
}
To set:
coins+=10;
scoreTxt.setText(coins);
Device rotation: Passing Extras and screen rotation

Make my class take an argument

Well I have a main Screen with 5 buttons. Each time a press a button I want to go a new screen. So far I have other 5 classes (each for each screen) and 5 xmls. But Iam sure that there will be a better way beacuse this screen and the xmls are the same, and what I want to do is change some texts and some data I fetch from a database. I am sure that I can ony another class and only one xml and then pass the values that I want as arguments. (Imagine that in its final state my app must have 15 buttons, so I think it is too mych waste of space and unnecessary to have 15 .java files and 15 xml files that look the same and only some values of images and textviews change). My code for main activity is:
public class MyActivity extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
main2Theme();}
private void main2Theme() {
setContentView(R.layout.main_new);
Button Button100 = (Button)findViewById(R.id.Button100);
Button113.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
Intent i = new Intent(this, OtherScreenName.class);
startActivity(i);
}
}); //and so on for 15 buttons
My OtherScreenName.class is:
public class OtherScreenName extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Theme();
}
#SuppressWarnings("null")
private void Theme() {
Log.d("SnowReportApp","Do first thing");
setContentView(R.layout.otherscreenname); //THIS CHANGES IN EVERY CLASS DEPENDING ON THE ID OF THE BUTTON
String result = "";
InputStream is = null;
StringBuilder sb=null;
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();//() before
nameValuePairs.add(new BasicNameValuePair("ski_id","OtherScreenName"));
TextView text1 = (TextView) findViewById(R.id.otherscreenname_1);
//THESE 2 CHANGE DEPERNDING ON THE BUTTON PRESSED
//perform action.....
//AND ALSO HERE I NEED THE ID OF THE BUTTON
b1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent i = new Intent(OtherScreenName.this,MyActivity.class);
startActivity(i);
}
});
Can anyone suggest how to give arguments to my class and what it should be the type of them?
If I understand your question correctly, you want to pass arguments to the activity. Normally it would be done through the class constructor, however, activities can't have user defined constructors, only the default one; they can be instantiated only indirectly via intent creation. If you need to pass data between activities, do it by putting extras to bundles, for example:
bundle.putInt("intName",intValue);
then you can extract the data from bundle by
int intValue = bundle.getInt("intName");
Put extras before starting the activity:
Intent i = new Intent(this, YourActivity.class);
Bundle b = new Bundle();
b.putInt("intName",intValue);
i.putExtras(b);
startActivity(i);
and then read the extras in the onCreate method:
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
Bundle b = getIntent().getExtras();
int intValue;
if (b != null)
{
intValue= b.getInt("intName");
}
}
The same way you can pass other data types as String boolean etc. If this is not sufficient and you need to pass some more complex data, then use Parcelable interface.
You can pass parameters with an Intent by adding extra's to it, something like the following:
Intent i = new Intent(this, MyActivity.class);
i.putExtra("paramName", "value");
startActivity(i);
In your activity you can use the getIntent() method to retrieve the Intent and extract your parameter(s) from it:
Intent i = getIntent();
Bundle extras = i.getExtras();
String param = extras.getString("paramName", "default value");
You can place all the different text and data in your Intent, but you can also decide based on the value of an Intent parameter which data and text to retrieve. If it is a lot of data or text you are probably better off using the second approach.
If you want to pass object instead of simple data, you must use parcelable objects as it´s explained in: [http://developer.android.com/reference/android/os/Parcelable.html][1]
Reading and writing with parcelable objects is very similar to the way with a simple data
Intent intent = new Intent(this ,newthing.class);
Bundle b = new Bundle();
b.putParcelable("results", listOfResults);
intent.putExtras(b);
startActivityForResult(intent,0);
Intent i = getIntent();
Bundle extras = i.getExtras();
String param = extras.getParcelable("results");

Categories

Resources