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);
Related
I'm stuck by a problem and I don't know how too resolve it.
I want to click on my item in my recycler view, and at this click the layout with the recylcer view will be closed, and my mainActivity will be refresh with the data of the item who i have click on.
you start new activity to get Data but here you start a normal intent you need to start Activity For Result like
startActivityForResult(intent,REQUEST_CODE);
or new Way
ActivityResultLauncher<Intent> result = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), new ActivityResultCallback<ActivityResult>() {
#Override
public void onActivityResult(ActivityResult result) {
if(result.getResultCode() == RESULT_OK){
String data = result.getData().getStringExtra("Data");
// here your data come from next Activity
}
}
});
then call result by
result.launch(Intent);
and in other Activity activity
you need to call
setResult(RESULT_OK,Intent);
finish();
this intent hold your data and will return to previous activity with it
After 2 hours in the sauce I have resolve that and I'm very happy.
The problem with the setResult() and the finish() but if you apply this code
((StructureEnFeuActivity)context).setResult(RESULT_OK, intent);
((StructureEnFeuActivity)context).finish();
You will not have the probleme with "static".
So I'm happy.
And thank you for all.
I am working in android studio.I have a bottom-navigation fragment. For the last switch case, I need a button to navigate to the HomeActivity (home screen). I tried:
...
case SUMMARY:
navNextText.setText(R.string.end);
navNextImageView.setOnClickListener(v -> navigateHome());
navNextText.setOnClickListener(v -> navigateHome());
break;
default:
Log.w(TAG, "Executing a default case in navigateNext(). CTX: " + contextState.toString());
}
private void navigateHome() {
Objects.requireNonNull(getActivity()).finish();
Intent in = new Intent(getActivity(), HomeActivity.class);
startActivity(in);
}
This works to an extent. I can navigate home, but when I click back into the activity that the navigation fragment resides, the navigation bar resumes where it was previous to changing activity.
I have also tried adding onStop() and onDestroy to private void navigateHome, but that seemed to do nothing.
I am just wondering what is the cleaner way to close an activity from a fragment and start a new one.
just add finish() if you want to remove the current activity from the backstack
As you're in a fragment, use requireActivity().finish()
Also to make sure you have no activities in back stack, you can remove all using below intent flag
private void navigateHome() {
Objects.requireNonNull(getActivity()).finish();
Intent in = new Intent(getActivity(), HomeActivity.class);
in.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); // <<<<< flag
startActivity(in);
requireActivity().finish(); // <<< finish the current activity
}
I have 3 activities: A,B,C. When I click on an item in RecyclerView in activity A activity B will be opened. There are a few String values which I have passed from A to B.
In activity B when I click on a button I go to activity C. In C when I press back button from my phone(android default back button) it comes back normally to activity B. But I have also put a back button in ToolBar using parent activity. When I press that button it shows me error that the String value trying to retrieve in activity B is null. I understand why the error is showing. It's obviously because there is no string passed from C to B to fetch.
But why am I not getting this error when I press back from my phones default button? How can I solve this?
Activity A
Intent intent = new Intent(getActivity(), Chat.class);
intent.putExtra("Recievers_Id", userId);
intent.putExtra("Recievers_Name", userName);
startActivity(intent);
Activity B
MessageSenderId = mAuth.getCurrentUser().getUid();
MessageRecieverId = getIntent().getStringExtra("Recievers_Id");
MessageRecieverName = getIntent().getStringExtra("Recievers_Name");
Activity C
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
Getting an error on
MessageRecieverId = getIntent().getStringExtra("Recievers_Id");
MessageRecieverName = getIntent().getStringExtra("Recievers_Name");
because obviously nothing to fetch... how do i solve this
Add onClickListener to the back button of your toolbar:
toolbar.setNavigationOnCLickListener(new View.OnClickListener){
#Override
public void onClick(View view) {
finish();
}
});
If you are getting error for null then try this:
if(getIntent().getStringExtra("Recievers_Id") != null){
MessageRecieverId = getIntent().getStringExtra("Recievers_Id");
}
if(getIntent().getStringExtra("Recievers_Name") != null){
MessageRecieverName = getIntent().getStringExtra("Recievers_Name");
}
On activity B you should check is Intent has rquired Extra.
Intent i = getIntent();
if (i.hasExtra("Recievers_Id")) {
messageRecieverId = i.getStringExtra("Recievers_Id");
}
if (i.hasExtra("Recievers_Name")) {
messageRecieverName= i.getStringExtra("Recievers_Name");
}
You can set the working of back button on toolbar as:
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
switch (id) {
// Respond to the action bar's Up/Home button
case android.R.id.home:
//NavUtils.navigateUpFromSameTask(this);
onBackPressed();
return true;
}
return super.onOptionsItemSelected(item);
}
First of all, you need to understand what happens when user presses navigation up button and what happens when onBackPressed.
Based on the documentation:
If the parent activity has launch mode <singleTop>, or the up intent contains FLAG_ACTIVITY_CLEAR_TOP, the parent activity is brought
to the top of the stack, and receives the intent through its
onNewIntent() method.
If the parent activity has launch mode , and the up intent does not contain FLAG_ACTIVITY_CLEAR_TOP, the parent activity
is popped off the stack, and a new instance of that activity is
created on top of the stack to receive the intent.
Where as when back button is pressed, it navigate, in reverse chronological order, through the history of screens. In this case Activity won't be re-created.
To summarize, the lauch mode of your ActivityB in AndroidManifest.xml must be standard. In this case the activity will be recreated when you press the navigation up button. But when back button is pressed, ActivityB is just brought to front, hence the difference in behavior.
Solution:
Approach 1: handle Up button by yourself
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if(item.getItemId()== android.R.id.home {
onBackPressed();
return true;
}
return super.onOptionsItemSelected(item);
}
Approach 2:
Set launch mode of Activity B to singleTop in AndroidManifest.xml. Remember to check the implication of changing the launch mode.
The "standard" and "singleTop" modes differ from each other in just
one respect: Every time there's a new intent for a "standard"
activity, a new instance of the class is created to respond to that
intent. Each instance handles a single intent. Similarly, a new
instance of a "singleTop" activity may also be created to handle a new
intent. However, if the target task already has an existing instance
of the activity at the top of its stack, that instance will receive
the new intent (in an onNewIntent() call); a new instance is not
created.
I was wondering if anyone could tell me how I could check a checkBox in an activity from another activity.
I'm making a homework app and I want to put a check next to the questions that have been completed.
So the first activity has a list of questions and next to them are unchecked boxes. When you click a question, the app takes you to the second activity. In the second activity, I want to check the box of the question that was completed.
You should use SharedPreferences for that. call this in the first activity:
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
prefs.putBoolean("KEY", <your value>).apply();
and something similar in another activity:
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
boolean isTicked = prefs.getBoolean("KEY", <default boolean value>);
where KEY can be anything, for example, your question's number
You should use intent and bundle logic for passing data between activities.(in most cases)
In the first activity, whenever you are creating the second activity, you pass your data.
Intent intent = new Intent(FirstActivity.this,SecondActivity.class);
intent.putExtra("checked",checkBox.isChecked());
startActivity(intent);
In the second activity you receive your data by using :
Intent receivedIntent = getIntent();
boolean finalChecked = receivedIntent.getExtras().getBoolean("checked");
//now you can apply your logic with finalChecked variable
You can save checked check question to a bundle and pass it as extra to your second activity through intent and read it from that intent inside your second activity
In your first activity do something like this
public class FirstActivity extends Activity {
public static final String EXTRA_CHECKED_QUESTION = "Checked Question";
// other codes here
private void startSecondActivity() {
String checkedQuestion = getCheckedQuestion(); // a method to get checked question
Intent intent = new Intent(this, SecondActivity.class);
intent.putExtra(FirstActivity.EXTRA_CHECKED_QUESTION, checkedQuestion);
startActivity(intent);
}
}
then in your second activity
public class SecondActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstance) {
// other codes
String checkedQuestion = getIntent().getStringExtra(FirstActivity.EXTRA_CHECKED_QUESTION);
// do whatever you want with checkQuestion
}
}
Please note that the string which you pass as first parameter to putExtra() method in FirstActivity, should be same as the string you are using with getStringExtra() to retrieve your extra in SecondActivity, otherwise you can not retrieve your passed extra in SecondActivity.
Also, I did not write these codes inside idea, so there might be syntax error
Read more about intent here
I have 3 activities, First Activity(Main), Middle Activity, and Final Activity. Currently, I'm sending Serializable Arraylists via Intent. Which works great when I create an intent to start Final Activity from within First Activity, although it skips over Middle Activity which needs to be displayed. The problem I'm running into is that all of the data originates in First Activity, and I can't seem to send it from First Activity, to Final Activity, and still display Middle Activity. I'm wondering if I should try to send the Arraylists via SharedPreferences instead?
List<String> proStrings = new ArrayList<>();
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.SendButton:
Intent intent = new Intent(FirstActivity.this, MiddleActivity.class);
intent.putExtra("proGolferArray", String.valueOf(i));
//CREATE BUNDLE AND ADD ARRAYLIST AS SERIALIZABLE
Bundle bundle = new Bundle();
bundle.putSerializable("PROGOLFER", (Serializable) proStrings);
//START NEW INTENT WITH ARRAYLIST BUNDLE PASSED IN
intentFinal = new Intent(this, FinalActivity.class);
intentFinal.putExtra("KEY", bundle);
startActivity(intent);
//startActivity(intentFinal);
//this doesn't look right, I must be doing this wrong....
break;
}
}
}
From MiddleActivity, I start the FinalActivity, but when I do, the data from the ArrayList in First Activity doesn't appear in FinalActivity at all. Is there a way to start 'finalIntent' from Middle Activity so that the data is sent to FinalActivity properly?
If you are trying to display MiddleActivity and then FinalActivity, try the following?
Launch MiddleActivity from FirstActivity along with the arraylist
Get the arraylist in onCreate() of MiddleActivity
Start FinalActivity from MiddleActivity along with the arraylist retrieved in step 2
And by the way the code you posted in the question is wrong. You should attach the bundle to intent and not finalintent