Android activity refreshes flow - android

I have an activity A, it has a button to open B, which inserts a record. A can then refresh the view inside onActivityResult. This is a normal flow.
However, B can accept share intent to insert a record also. How can A know when this action is done from B to refresh the view just like the normal flow? (of course, I assume act A already running on background task)
I can, of course, detect the change using onResume inside A, but i wish to know if it is a proper method.
thank you

You can use onResume to refresh the view for activity A. Because other method would be using broadcastReceiver and broadcastIntent and that would create unnecessary load.
You can use sharedPreference to store if data has been changed in Activity B and then in onResume of Activity A fetch that shared Preference and refresh the view
#Override
protected void onResume() {
super.onResume();
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
boolean isChanged = sharedPreferences.getBoolean("isChanged",false);
if(isChanged){
//refresh your views
//clear the shared prefernce
SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(this).edit();
editor.putBoolean("isChanged",false);
editor.apply();
}
}
Remember you have set that shared preference in ActivityB while loading data
SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(this).edit();
editor.putBoolean("isChanged",true);
editor.apply();

Related

Shared Preference data not cleared when activity is closed

in my application, I used place picker.and data that place picker gave is sent to 3 different activities using shared preference.and show this data in TextView.problem is when I closed activity and again open that activity my data still visible in TextView.even when I cleared it in onDestroy().
here is my code for send data from place picker:
SharedPreferences settings = getSharedPreferences("city_address", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = settings.edit();
editor.putString("city_address", (String) cityAddress);
editor.putString("city_name", (String) city);
editor.commit();
Intent intent = new Intent(this, CleanlinessActivity.class);
startActivity(intent);
set data using this code in onCreate() of CleanlinessActivity
SharedPreferences settings = getSharedPreferences("city_address", Context.MODE_PRIVATE);
String n = settings.getString("city_name", "Enter Location");
String a = settings.getString("city_address", "");
cityname.setText(n);
cetlocation.setText(a);
and i cleared data using this code in CleanlinessActivity
#Override
protected void onDestroy() {
super.onDestroy();
SharedPreferences settings = getSharedPreferences("city_address", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = settings.edit();
editor.remove("city_address");
editor.clear().commit();
}
By closing the app you mean just clicking the home button then onDestroy() is never called, you can get a refresher of the android life cycles here
If what you are doing is simply clicking the home button then consider moving your code to the onStop() otherwise you need to commit() following the remove(...) The android documentation states "Mark in the editor that a preference value should be removed, which will be done in the actual preferences once commit() is called."
You have an instance of SharedPreferences called city_address which is having two fields or (Columns if we call it),but inside onDestroy()you are trying to to clear only one field of it called city_address,and the other field city_name field is left unchanged,if you want to completely remove the content of the city_address SharedPreferences use editor.clear().commit();
or``editor.clear().apply();`

How to display different content depending on whether the app is opened first time?

How to display different content depending on whether the app is opened first time or the user setup something?
Imagine a activity A, B, If the user open the app first time or haven't setup something in activity B, Then display activity B, otherwise display activity A.
How to overcome this? Thank you.
Use PreferenceManager. In activity A add check for the preference firstLaunch. If it's not set, launch activity B. Then, in activity B, set it.
It could look like:
Activity A
#Override
protected void onResume() {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
// By default assume "true", which means this is the first launch.
if (prefs.getBoolean("firstLaunch", true)) {
// Start Activity B and finish myself.
Intent i = new Intent(getApplicationContext(), ActivityB.class);
startActivity(i);
finish();
}
}
Activity B
// Do it after you've initialized everything, so Activity A can be launched:
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this)
SharedPreferences.Editor editor = prefs.edit();
// Set "fistLaunch" to "false", so Activity A will start next time.
editor.putBoolean("firstLaunch", false);
editor.commit();
If you want to show different activity if user opened the app first time and different activity second or third time and so on then you can use below approach.
You can use the SharedPreference to achieve this.
Check the condition like this in the Splash Activity :
SharedPreferences preferences = getSharedPreferences("prefName", MODE_PRIVATE);
if(!preferences.getBoolean("isFirstRun", false)) {
// This mean App Launch First Time
SharedPreferences preferences = getSharedPreferences("prefName", MODE_PRIVATE);
SharedPreferences.Editor edit= preferences.edit();
edit.putBoolean("isFirstRun", true);
edit.commit();
// Open the B Activity
} else {
// This mean App Launch Second or third ... time and start the A Activity
}

How to save a result in android?

I'm a rookie in android programming. I have a small problem. When I click a ImageView, I make that ImageView invisible and set a Button to visible. My problem is that how do you save this? For eg, I click the ImageView, Button shows up and ImageView disappears. And I exit the app and enter back into that same activity and I want that Button to remain there. How do I go about doing that?
Thanks!
Use SharedPreferences. here is a good tutorial on how to use them. example
But basically you are good to go by adding this code to your Activity
private boolean isVisible;
#Override
public void onCreate(Bundle myBundle){
super.onCreate(myBundle);
isVisible = getPreferences(MODE_PRIVATE).getBoolean("visible", true);
.... your code
if (isVisible){
// show ImageView
} else {
//don't
}
}
}
public void onPause(){
if(isFinishing()){
getPreferences(MODE_PRIVATE)
.edit().
putBoolean("visible", isVisible).commit();
}
}
Use a shared preference to save the state, i.e. say in your case a boolean value to indicate whether imageview was visible or not when you exit the app.
When you launch the app, use this value and accordingly perform the action.
For usage of shared preference,
How to use SharedPreferences in Android to store, fetch and edit values
you can store the state in shared preference when you leave your app onPause() or on the click event and can get result back on onCreate() method from that preferences
To store data in shared preference(in OnPause() or on the click event):
SharedPreferences prefs = getSharedPreferences("yourPrefName", MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
// save values
editor.putBoolean("isButtonVisible", true);
editor.commit();
To get data from sharedPrefs(in onCreate()):
SharedPreferences prefs = getSharedPreferences("yourPrefName", MODE_PRIVATE);
boolean btnstatus = prefs.getBoolean(Constants.IS_LOGIN, false);
if (btnstatus) {
//put the code to show button and hide imageview
}

Handling runtime changes in Android for a simple app - do I need to use a Bundle?

I am making my first Android app, which consists of just editText's and Spinner's. Reading up on the activity cycle, I am wondering if it is even necessary to use the Bundle mechanism in my situation.
Since the state of the widgets are automatically persisted -
could I just call the getSelectedItem() method on the spinners and getText() on the EditText's within the onCreate() method for the Activity and pass that on to my newly re-created model object rather than using the Bundle mechanism? What are the advantages and disadvatanges of this approach?
The state of widgets it not automatically persisted. When you activity is destroyed it loses all the information about state. I recommend you saving you application state using shared preferences. Here is an example from google developers site. it allows you to save your application state by storing key-value pairs and it should suffice for your app.
Save the text and spinner item position in shared preferences when your activity is stopped - onStop() and restore the state in onCreate().
public class Calc extends Activity {
public static final String PREFS_NAME = "MyPrefsFile";
#Override
protected void onCreate(Bundle state){
super.onCreate(state);
. . .
// Restore preferences
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
boolean silent = settings.getBoolean("silentMode", false);
setSilent(silent);
}
#Override
protected void onStop(){
super.onStop();
// We need an Editor object to make preference changes.
// All objects are from android.context.Context
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putBoolean("silentMode", mSilentMode);
// Commit the edits!
editor.commit();
}
}
Although you can save your application state by onSaveInstanceState(Bundle) method, usually the better way will be to do that in onPause() or onStop() methods(the data will be saved for sure). Documentation says:
Note that it is important to save persistent data in onPause() instead
of onSaveInstanceState(Bundle) because the latter is not part of the
lifecycle callbacks, so will not be called in every situation as
described in its documentation.

How to implement a registration activity in android that works only for once?

I'm designing an application that has an activity for registration process, this activity launches on default. I want this activity to be disabled forever once the registration process has been completed successfully and then it should be replaced by a different activity as the default activity for the rest of the lifetime of the application.I've tried to search my way through this problem but I've hardly found anything.Any help will be much appreciated.
Thanks in advance.
Once registration is complete, commit some value to the SharedPreferences, then in your splash screen or some other opening Activity, check the preferences. If the value indicates that the registration is complete, start a different Activity instead of the Registration one...
Example:
public class SplashScreen extends Activity {
public void onCreate(Bundle state) {
super.onCreate(state);
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
boolean regComplete = prefs.getBoolean("registration", false);
if(regComplete) {
startActivity(new Intent(this, SomeActivity.class));
} else {
startActivity(new Intent(this, Registration.class));
}
}
Better still:
Always launch the registration, but in onCreate(), simply launch a different Activity immediately and finish() the registration Activity if the prefs indicate that registration is complete.
Edit
SharedPreferences explained:
SharedPreferences lets you persist primitive values in your app. You grab the SharedPreferences by doing:
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
then you write to SharedPreferences by getting the Editor. To do this, you call
SharedPreferences.Editor editor = prefs.Edit();
then you can commit values to the editor by using key/values:
editor.putBoolean("some string as a key here", true/false);
Then to actually save that, you call editor.commit();
Then you grab values back from SharedPreferences by simply calling
prefs.getBoolean("some previously chosen string as a key here", true/false);
where true/false is the default value that will be returned if no such key exists...
This is convenient and lets you do simple things like:
editor.putInt("some important number", 55);
editor.commit();
......later
int i = prefs.getInt("some important number", -1);
if(i != -1) {
//do stuff
} else {
//do other stuff
}
Also, please see: http://developer.android.com/guide/topics/data/data-storage.html#pref
Don't have the registration Activity be the default. Instead have another Activity as the default, and then at runtime it can check to see which Activity it should send the user to. If they haven't registered then startIntent( RegistrationActivity.class ).

Categories

Resources