i carried some edittext string data from a second activity to the first and placed the string data into textviews in the first activity.
this worked fine.
when i go from the first activity back to the second activity (done using the options menu), i want to carry the previously entered edittext data back into the edit texts in the second activity. i cant get it to carry over - the second activity edittexts go back to the original edittext settings (empty).
this is my second activity code:
public void goToMain(View view) { //run when a button is clicked
Intent intent = new Intent(setPlayersActivity.this, MainActivity.class);
intent.putExtra("P1",p1EditText.getText().toString());
startActivity(intent);
}
and in my first activity code i have in the on create:
Intent name = getIntent();
p1TextView.setText(name.getStringExtra("P1"));
to go from the first activity to the second
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
if (item.getItemId() == R.id.resetAll) {
updateScoreTeamA(scoreA = 0);
} else if (item.getItemId() == R.id.setPlayers) {
Intent intent = new Intent(MainActivity.this, setPlayersActivity.class);
startActivity(intent);
}
return super.onOptionsItemSelected(item);
}
up to here is working fine.
upon returning to the second activity though, the edittexts are again empty (i want to carry the previously entered data back to this activity).
to fill the edittexts with the previously entered string data, i tried the following in the on create of the second activity.
p1EditText.setText(getIntent().getStringExtra("P1"));
thanks in advance for the help. i am a beginner with programming and cannot imagine making any progress without this community.
When your changing activity you have to provide data to that certain intent. Otherwise it won't work
Intent intent = new Intent(MainActivity.this, setPlayersActivity.class);
intent.putExtra("P1","data");
startActivity(intent);
I am trying to make a simple text app in order to learn app dev with Java.
I have 2 classes/activities: DisplayActivity and EditActivity.
The goal/plan is to have a screen in EditActivity where you can edit a few edittext fields, it saves it and quits the EditActivity when you press ok, you press the button to access DisplayActivity and it shows everything previously entered.
In the EditActivity, I referenced my textfields and my button, and I convert the input to strings each string variable has its own getter.
From DisplayActivity, I made an EditActivity object that calls the getters on the textview fields, which are also referenced correctly
class EditActivity{
Button mButton;
EditText mName;
DispActivity obj = new DispActivity();
void onCreate(){
mButton = (Button)findViewById(R.id.whatever);
mName = (EditText)findViewById(R.id.whateveralso);
mButton.setOnClickListener(new View.onClickListener(){
#Override
public void onClick(View v){
//does the intent thing where it changes the activity to DispActivity
String name = mName.getText().toString();
}
});
}
in DisplayActivity, there is simply the name textview referenced.
I dont have error codes/messages or warnings: everything compiles, builds, and runs nicely, until I run the app... the DisplayActivity works fine, though it displays nothing. But when I try to run the EditActivity, it crashes...
One way to do this would be with Intent and it's result. It's a simple way to share data between activities.
In your DisplayActivity, where you start the edit activity:
Intent i = new Intent(DisplayActivity.this, EditActivity.class);
startActivityForResult(i); //start edit activity
In your EditActivity, you must set the result before you finish the activity:
Intent returnIntent = new Intent();
returnIntent.putExtra("result",resultString); //put your result string here
setResult(Activity.RESULT_OK,returnIntent);
finish(); //close edit activity
Now in your DisplayActivity you get the result by implementing the following method:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 1) {
if(resultCode == Activity.RESULT_OK){
String result=data.getStringExtra("result");
//display your string here
}
if (resultCode == Activity.RESULT_CANCELED) {
//user canceled the edit activity
}
}
}
Is there a way to access to variables on onCreate(), to reuse them in another class?
String testSubCa="";
String prixe="";
String testWiifi="";
Double testPrice=0.0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_srdata);
testSubCa = getIntent().getStringExtra(SearchRestau.txxtSub);
prixe = getIntent().getStringExtra(SearchRestau.txtprix);
testWiifi = getIntent().getStringExtra(SearchRestau.txxtWifi);
testPrice=Double.parseDouble(prixe);
refresh = (ImageButton) findViewById(R.id.imgRefresh);
refresh.setOnClickListener(this);
}
I need to use these data :/
Since you didn't really specify what exactly your plan is, it's a bit of a challenge getting a proper solution.
I'm just going to assume what you want to do is to start an activity, let the user do something inside this activity and then go back to where it was started from with the ability to use the values created inside the activity.
The easiest way to that is by not starting the activity via startActivity(Intent) but rather by using startActivityForResult(Intent, RequestCode);
In the same activity you then need to handle the event of actually getting a result. To do this you need to implement the method
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
if (resultCode == RESULT_OK)
{
//Your code to retrieve the data here!
}
}
The variables should be stored inside the Intent data and can be grabbed by using
data.getStringExtra();
To place the values inside the result you need to place this code in the activity you actually create them:
Intent intent = new Intent();
intent.putExtra("value_id", value);
setResult(RESULT_OK, intent);
finish();
I hope that helps with your problem!
GL
I have a string in activity2
String message = String.format(
"Current Location \n Longitude: %1$s \n Latitude: %2$s", lat, lng);
I want to insert this string into text field in activity1. How can I do that?
You can use intents, which are messages sent between activities. In a intent you can put all sort of data, String, int, etc.
In your case, in activity2, before going to activity1, you will store a String message this way :
Intent intent = new Intent(activity2.this, activity1.class);
intent.putExtra("message", message);
startActivity(intent);
In activity1, in onCreate(), you can get the String message by retrieving a Bundle (which contains all the messages sent by the calling activity) and call getString() on it :
Bundle bundle = getIntent().getExtras();
String message = bundle.getString("message");
Then you can set the text in the TextView:
TextView txtView = (TextView) findViewById(R.id.your_resource_textview);
txtView.setText(message);
You can send data from one actvity to another with an Intent
Intent sendStuff = new Intent(this, TargetActivity.class);
sendStuff.putExtra(key, stringvalue);
startActivity(sendStuff);
You then can retrieve this information in the second activity by getting the intent and extracting the string extra. Do this in your onCreate() method.
Intent startingIntent = getIntent();
String whatYouSent = startingIntent.getStringExtra(key, value);
Then all you have to do is call setText on your TextView and use that string.
TWO CASES
There are two situations possible when we talk about passing data between activities.
Let's say there are two activities A and B and there is a String X. and you are in Activity A.
Now let's see the two cases
A-------->B
A<--------B
CASE 1:
String X is in A and you want to get it in Activity B.
It is very straightforward.
In Activity A.
1) Create Intent
2) Put Extra value
3) startActivity
Intent i = new Intent(A.this, B.class);
i.putExtra("Your_KEY",X);
startActivity(i)
In Activity B
Inside onCreate() method retrieve string X using the key which you used while storing X (Your_KEY).
Intent i = getIntent();
String s = i.getStringExtra("Your_KEY");
Case 2:
This case is little tricky if u are new to Android
development Because you are in Activity A, you move to Activity B,
collect the string, move back to Activity A and retrieve the
collected String or data. Let's see how to deal with this situation.
In Activity A
1) Create Intent
2) start an activity with a request code.
Intent i = new Intent(A.this, B.class);
startActivityForResult(i,your_req_code);
In Activity B
1) Put string X in intent
2) Set result
3) Finish activity
Intent returnIntent = new Intent();
returnIntent .putString("KEY",X);
setResult(resCode,returnIntent); // for the first argument, you could set Activity.RESULT_OK or your custom rescode too
finish();
Again in Activity A
1) Override onActivityResult method
onActivityResult(int req_code, int res_code, Intent data)
{
if(req_code==your_req_code)
{
String X = data.getStringExtra("KEY")
}
}
Further understanding of Case 2
You might wonder what is the reqCode, resCode in the onActivityResult(int reqCode, resCode, Intent data)
reqCode is useful when you have to identify from which activity you are getting the result from.
Let's say you have two buttons, one button starts Camera (you click a photo and get the bitmap of that image in your Activity as a result), another button starts GoogleMap( you get back the current coordinates of your location as a result). So to distinguish between the results of both activities you start CameraActivty and MapActivity with different request codes.
resCode: is useful when you have to distinguish between how results are coming back to requesting activity.
For eg: You start Camera Activity. When the camera activity starts, you could either take a photo or just move back to requesting activity without taking a photo with the back button press. So in these two situations, your camera activity sends result with different resCode ACTIVITY.RESULT_OK and ACTIVITY.RESULT_CANCEL respectively.
Relevant Links
Read more on Getting result
Say there is EditText et1 in ur MainActivity and u wanna pass this to SecondActivity
String s=et1.getText().toString();
Bundle basket= new Bundle();
basket.putString("abc", s);
Intent a=new Intent(MainActivity.this,SecondActivity.class);
a.putExtras(basket);
startActivity(a);
now in Second Activity, say u wanna put the string passed from EditText et1 to TextView txt1 of SecondActivity
Bundle gt=getIntent().getExtras();
str=gt.getString("abc");
txt1.setText(str);
Intent intent = new Intent(activity1.this, activity2.class);
intent.putExtra("message", message);
startActivity(intent);
In activity2, in onCreate(), you can get the String message by retrieving a Bundle (which contains all the messages sent by the calling activity) and call getString() on it :
Bundle bundle = getIntent().getExtras();
String message = bundle.getString("message");
Intents are intense.
Intents are useful for passing data around the android framework. You can communicate with your own Activities and even other processes. Check the developer guide and if you have specific questions (it's a lot to digest up front) come back.
You can use the GNLauncher, which is part of a utility library I wrote in cases where a lot of interaction with the Activity is required. With the library, it is almost as simple as calling a function on the Activity object with the required parameters. https://github.com/noxiouswinter/gnlib_android/wiki#gnlauncher
In order to insert the text from activity2 to activity1, you first need to create a visit function in activity2.
public void visitactivity1()
{
Intent i = new Intent(this, activity1.class);
i.putExtra("key", message);
startActivity(i);
}
After creating this function, you need to call it from your onCreate() function of activity2:
visitactivity1();
Next, go on to the activity1 Java file. In its onCreate() function, create a Bundle object, fetch the earlier message via its key through this object, and store it in a String.
Bundle b = getIntent().getExtras();
String message = b.getString("key", ""); // the blank String in the second parameter is the default value of this variable. In case the value from previous activity fails to be obtained, the app won't crash: instead, it'll go with the default value of an empty string
Now put this element in a TextView or EditText, or whichever layout element you prefer using the setText() function.
For those people who use Kotlin do this instead:
Create a method with a parameter containing String Object.
Navigate to another Activity
For Example,
// * The Method I Mentioned Above
private fun parseTheValue(#NonNull valueYouWantToParse: String)
{
val intent = Intent(this, AnotherActivity::class.java)
intent.putExtra("value", valueYouWantToParse)
intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
startActivity(intent)
this.finish()
}
Then just call parseTheValue("the String that you want to parse")
e.g,
val theValue: String
parseTheValue(theValue)
then in the other activity,
val value: Bundle = intent.extras!!
// * enter the `name` from the `#param`
val str: String = value.getString("value").toString()
// * For testing
println(str)
Hope This Help, Happy Coding!
~ Kotlin Code Added By John Melody~
So I was doing this but my output is weird ,
this is the 1st activity
up = findViewById(R.id.button);
up.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, updatestudents.class);
intent.putExtra("updating",updating);
startActivity(intent);
}
});
this is the 2nd activity
Bundle extras = getIntent().getExtras();
if (extras != null) {
Current_Value = getIntent().getStringExtra("updating");
}
u = findViewById(R.id.text);
u.setText("updating " + Current_Value);
Here I am retrieving String in 2nd Activity
And this is my output
enter image description here
I have a MainActivity which has a navigation drawer and a framelayout container to show different fragments. On my navigation drawer there is an option which launches another activity(lockpattern activity) to show a lockpattern (had to use activity cause the library doesn't support fragments yet. Link to Library).Once the user has set up his pattern or canceled the procedure,i want the lockpattern activity to get destroyed and show the previous mainActivity and the same fragment what was there in the container before the lockpattern activity was launched.The problem im facing is that once the backbutton is pressed or even if i call the finish() function,it doesn't show the previous activity(ie Main activity) but instead relaunches the lockpattern activity.i have even tried super.onBackPressed(); and it doesn't seem to work.Any help or ideas to get around this is gratefully accepted.
Code of Lockpattern
public class Create_Pattern extends Activity {
private static final int REQ_CREATE_PATTERN = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
// This is your preferred flag
LockPatternView.MATRIX_WIDTH = 4;
Intent intent = new Intent(LockPatternActivity.ACTION_CREATE_PATTERN,
null, getBaseContext(), LockPatternActivity.class);
startActivityForResult(intent, REQ_CREATE_PATTERN);
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case REQ_CREATE_PATTERN: {
if (resultCode == RESULT_OK) {
char[] pattern = data
.getCharArrayExtra(LockPatternActivity.EXTRA_PATTERN);
DataBaseHandler handler = new DataBaseHandler(this);
handler.open();
String PatternToWrite = new String(pattern);
handler.createPattern(PatternToWrite);
handler.close();
Log.d("DEBUG", new String(pattern));
Toast.makeText(getApplicationContext(), "Pattern Recorded",
Toast.LENGTH_LONG).show();
finish();
}
if (resultCode == RESULT_CANCELED) {
finish();
}
break;
}// REQ_CREATE_PATTERN
}
}
}
You should create a new Intent that points to the Activity you want to navigate to next, start that activity by calling startActivity(intent). Then you can call finish() to destroy the current Activity.
Another approach, (which I have not tried yet) is to create an 'up button' hierarchy and manually call NavUtils.navigateUpFromSameTask(this);
Documentation:
http://developer.android.com/training/implementing-navigation/ancestral.html
http://developer.android.com/reference/android/support/v4/app/NavUtils.html