My MainActivity has an EditText with the hint "Weight (lb)", as well as a button that goes to the SettingsActivity. In SettingsActivity, the user is able to change the units used from US to metric. Upon exiting SettingsActivity via the built-in back button on the phone, I want the hint for the EditText to immediately change from "Weight (lb)" to "Weight (kg)".
The farthest I've gotten is using the onBackPressed() method in SettingsActivity. The button press is detected, and the code inside it is executed, but I don't want to change anything related to MainActivity's inside the SettingsActivity class.
Is there an on___() method that I should be using here that I don't know about? Any help would be appreciated.
You can use startActivityForResult for SettingsActivity and after that handle the return result as:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == PICK_CONTACT_REQUEST) {
// Make sure the request was successful
if (resultCode == RESULT_OK) {
// The user picked a contact.
// The Intent's data Uri identifies which contact was selected.
// Do something with the contact here (bigger example below)
}
}
More detail: https://developer.android.com/training/basics/intents/result.html
You can use startActivityForResult for SettingsActivity and after that handle the return result as:
In your MainActivity:
public static int CALL_SETTINGS = 1000;
startActivityForResult(new Intent(this,SettingsActivity.class),CALL_SETTINGS);
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == PICK_CONTACT_REQUEST) {
// Make sure the request was successful
if (resultCode == RESULT_OK) {
// The user picked a contact.
// The Intent's data Uri identifies which contact was selected.
// Do something with the contact here (bigger example below)
}
}
In your Settings Activity:
on backpressed write this:
Intent returnIntent = new Intent();
returnIntent.putExtra("result",data);
setResult(Activity.RESULT_OK,returnIntent);
finish();
Easy option is to store the waitUnit in shared preference and on OnResume() of the Main activity read it from there and update the widget.
You can update the preferences in your Settings activity like below:
preferences = context.getSharedPreferences(context.getString(R.string.preference_file_key),
Context.MODE_PRIVATE);
preferences.edit().putString("unit", "kg");
And you can read this changed value in OnResume() of your Main Activity
preferences.getString("unit", "default unit")
Related
"Ex: In flipkart when we open App, Home screen will load the data and when we go to next activity from home screen and again we come back to Home screen its not loading again "
Cancel all the tasks using lifecycle methods of Fragment: "onPause", "onStop" and etc (you have to choose one of them). Fragment lifecycle.
Use onActivityResult
Define constant
public static final int REQUEST_CODE = 1;
Call your custom dialog activity using intent
Intent intent = new Intent(Activity.this,
CustomDialogActivity.class);
startActivityForResult(intent , REQUEST_CODE);
Now use onActivityResult to retrieve the result
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
try {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_CODE && resultCode == RESULT_OK) {
//reload data here
}
} catch (Exception ex) {
Toast.makeText(Activity.this, ex.toString(),
Toast.LENGTH_SHORT).show();
}
}
In custom dialog activity use this code to set result
Intent intent = getIntent();
intent.putExtra("key", value);
setResult(RESULT_OK, intent);
finish();
While tap on bottom back button it will not reload, because it just finishes current activity and resumes home activity.
To prevent reload home activity while tap on back button from toolbar, you have to add
android:launchMode="singleTop"
to your home activity in your manifest file.
For more details refer here
I have an Activity which makes use of KeyguardManager.
The intention is to disallow the user to use the app, if they are unable to successfully supply their credentials.
Though the keyguard intent appears at the start of the app, pressing the device back button moves the intent away, showing the activity which started it.
Overriding the onBackPressed does not seem to help, as it isn't associated with the intent.
#Override
public void onBackPressed() {
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
KeyguardManager km = (KeyguardManager) getSystemService(KEYGUARD_SERVICE);
if (km.isKeyguardSecure()) {
setShowWhenLocked(true);
Intent i = km.createConfirmDeviceCredentialIntent("Authentication required", "password");
startActivityForResult(i, CODE_AUTHENTICATION_VERIFICATION);
}
}
What if you use finish() after startActivity() ?
EDIT:
Add finish() on your onActivityResult() if the pattern is false.
What you want to achieve can be done using a "Staging" Activity. For example, you can have a LoginActivity that will check if the user is authenticate or not then from there decide where to redirect him.
The LoginActivity should look something like this, of course you need to adapt it to your business logic :
public class LoginActivity extends AppCompatActivity {
private static final int CODE_AUTHENTICATION_VERIFICATION = 24;
private boolean isFirstLaunch = true;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
isFirstLaunch = false;
//startActivityForResult With your intent to authenticate the user
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == CODE_AUTHENTICATION_VERIFICATION){
Log.i("LOGIN", "return from key guard");
//Check the data and decide if you redirect the user to main activity or not
}
}
#Override
protected void onResume() {
super.onResume();
if(!isFirstLaunch){
Log.i("LOGIN", "resume not first launch");
// the user tried to cancel the authentication either present him with the authentication process again or finish() the activity
}
}
}
Please, N/B: Overriding the onBackPressed does help only when you create a conditional statement controlled by a boolean variable in the onBackPressed method and call it in the onActivityResult i.e when the resultCode != RESULT_OK. Another option is to exit the app when resultCode != RESULT_OK (moveTaskToBack(true)) Here is what I mean below:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == INTENT_AUTHENTICATE) {
if (resultCode == RESULT_OK) {
//do something you want when pass the security
} else //resultCode != RESULT_OK
//Option 1 Ensure you override onBackPressed() with a conditional
//statement controlled by a boolean variable.
onBackPressed();
//Option 2
moveTaskToBack(true); //Exit app when a user click the back button.
}
}
So I have 3 activities: MainActivity, AddEntryActivity, and CategoryActivity. I want to use startActivityForResult from Main -> AddEntry, and then AddEntry -> Category and have the data from Category passed back to AddEntry where it's used as a field in the Entry object result I'm sending back to Main. The problem is, when I call finish() in AddEntryActivity (after returning from CategoryActivity), CategoryActivity opens again. I think it may be a problem with the intents/contexts but I'm new to android dev so I can't figure out what the problem is. Any help would be appreciated!
I am currently calling startActivityForResult() from MainActivity (on button press) to get to AddEntry.
case R.id.addEntryButton:
Intent in = new Intent(this, AddEntryActivity.class);
startActivityForResult(in, 111);
break;
Then from AddEntryActivity, I call another startActivityForResult to get to CategoryActivity (on button press again).
case R.id.chooseCategory:
Intent catAct = new Intent(this, CategoryActivity.class);
startActivityForResult(catAct, 222);
break;
From CategoryActivity, the user can choose a category and it's sent back to AddEntryActivity (I've checked that this works).
In CategoryActivity:
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
Intent i = getIntent();
String category = (String) getListAdapter().getItem(position);
i.putExtra("Category", category);
setResult(RESULT_OK, i);
finish();
}
In AddEntryActivity:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 222 && resultCode == RESULT_OK) {
String cat = data.getStringExtra("Category");
category.setText(cat);
categoryString = cat;
}
}
Then, in AddEntryActivity, when the confirm button is pressed I want to return to MainActivity with a new Entry object containing the category field that was returned from CategoryActivity. So I have this:
case R.id.confirmEntryButton:
Entry entry = new Entry(descString, amountString, date.getText().toString(), categoryString);
Intent main = new Intent(this, MainActivity.class);
main.putExtra("newEntry", entry);
setResult(RESULT_OK, main);
finish();
The problem is, when the confirm button is pressed, the CategoryActivity screen pops up again. The weird thing is, the onActivityResult method in MainActivity (below) actually runs as when you close the CategoryActivity screen via the back button, you can see that the entry object has been added so I can't seem to figure out what's causing the category screen to pop up.
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 111 && resultCode == RESULT_OK) {
Entry entry = data.getParcelableExtra("newEntry");
entries.add(entry);
entryListView.setAdapter(eAdapter);
}
}
Check your switch case statement to make sure it isn't missing a break and falling through to the next part.
I have two activities:
ListViewActivity
AddActivity
and one object class :
todoObj
I have a list view in my ListViewActivity activity and when I click add button this will initiate AddActivity . In AddActivity when user enters Title, choose date, time and the category I want AddActivity to create a todo object and pass this back to the ListViewActivity.
Sorry I could not share the code itself, it always gives this error all the time so I uploaded on github please check it out.
Sorry again.
Many thanks.
All you have to fix onActivityResult method in ListViewActivity:
Because of you setting result code ADD_REQUEST_CODE in AddActivity "setResult(ListViewActivity.ADD_REQUEST_CODE, intent);", you should use "if (resultCode == ADD_REQUEST_CODE) {" in ListViewActivity not RESULT_OK.
You should receive intent from onActivityResult not ListViewActivity's intent. getIntent() gives ListViewActivity's intent. So use data variable:
onActivityResult(int requestCode, int resultCode, Intent data)
Final code:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == ADD_REQUEST_CODE) {
if (resultCode == ADD_REQUEST_CODE) {
Log.i("ListViewActivity", "Returned onActivityResult");
TodoObj todoObj = (TodoObj) data.getParcelableExtra("EXTRA_TODO");
Toast.makeText(ListViewActivity.this, "" + todoObj.getmYear(),
Toast.LENGTH_SHORT).show();
}
}
}
I created a 'New File' activity using
startActivityForResult(new Intent(MainActivity.this, NewFile.class),1);
The NewFile activity lets users set certain options for their text file then after clicking a button a string is saved to a static variable in my StringBuilder class and finish(); is called. How can I load this new string into the MainActivity's EditText? onCreate() is only called when the activity is first created right?
Do it on onResume or onActivityResult. It would be ideal though onActivityResult since you've used startActivityForResult, before finishing the other activity you set the setResult(int resultCode, Intent data) if you have intent to sent back or if none setResult(int resultCode). I think it is better to put the string which will be used to update your EditText as extra in the intent, then set the text using that string in onActivityResult method.
#Override
protected void onResume() {
super.onResume();
et.setText(DocumentBuilder.docText);
}
in your class NewFile.java :
String strName = "toto";
Intent intent = new Intent();
intent.putExtra("name", "toto");
setResult(1, intent);
finish();
in your MainActivity.java :
#Override
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
if (requestCode == 1) {
if (resultCode == RESULT_OK) {
// Handle successful result
String name = intent.getStringExtra("name");
editText.setText(name);
}
}
}
refer this tutorial for more explanations