Saving Fragment's State Through out the application - android

I have an application where app has both online & offline mode.
Once the fragment is loaded a network call is made and data is set.
The user makes some changes into fragment UI like adding buttons, Editing TextBoxes etc. I have to maintain that state throughout the application.
I have next & previous buttons, when i press on previous button on the fragment is reloading even though i tried to adding it to back stack while replacing it and calling getActivity().onBackPressed();.
Things I have Tried :
1) saving the values into bundles is too much data & hard ti retrieve due to bulk of data/values.

If you use viewpager, you can keep the last state of the fragments and it will not reload untill the offscreen limit u set as below.
mViewPager.setOffscreenPageLimit(limit); //limit: integer value >=1

If you have large number of data you want to save, use SQLite, otherwise you can use Shared Preferences
For more info visit this link
First get the reference to your shared preferences file
Context context = getActivity();
SharedPreferences sharedPref = context.getSharedPreferences("my_preferences", Context.MODE_PRIVATE);
after this write to Shared Preferences with
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString("key", "value");
//use editor.apply() if you want to save your data imedialtly
editor.commit();
when you want to retrieve the data (onCreateView/onViewCreated)
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
EditText editex = (EditText) view.findViewById(R.id.your_view_id);
editext.setText(sharedPref.getString("key", defaultValue))
}
But keep in mind, Shared Preferences will save and keep your data even if your app is killed/destoyed

Related

SharedPreferences in Android saving the visibility of an ImageView

I have a menu activity that acts as a level selector. When the user finishes a level (activity) and returns to the menu, I want it to set an image visible in the menu to show that said level has been completed. Also, I want this info to save from a session to another.
My aproach has been to try SharedPreferences. This is the code from the level activity that writes the save:
private int levelNumber
SharedPreferences save = getSharedPreferences("SaveGame", MODE_PRIVATE);
SharedPreferences.Editor editor = save.edit();
editor.putInt("levelComplete",levelNumber);
editor.commit();
GameActivity.this.finish();
This is the relevant code from the menu that reads the save and sets the image visible based on the levelNumber:
clear_stage = new ImageView[clear];
clear_stage[0] = (ImageView)findViewById(R.id.clear1);
clear_stage[1] = (ImageView)findViewById(R.id.clear2);
clear_stage[2] = (ImageView)findViewById(R.id.clear3);
clear_stage[3] = (ImageView)findViewById(R.id.clear4);
clear_stage[4] = (ImageView)findViewById(R.id.clear5);
SharedPreferences save = getApplicationContext().getSharedPreferences("SaveGame", MODE_PRIVATE);
clear = save.getInt("levelComplete", 0);
clear_stage[clear].setVisibility(View.VISIBLE);
I have the visibility set to "gone" in the xml, by the way.
Now, my main problem is that the visible image changes every time that a level is completed, and the last image goes invisible again (gets overwritten).
Is there a way to store the clear value each time a level is complete?
I tried with:
SharedPreferences saveall = getSharedPreferences("SaveGame", MODE_PRIVATE);
SharedPreferences.Editor editor = saveall.edit();
editor.putInt("clear_stage",clear);
editor.commit();
But it isn't working, and I don't really know what I should do next. Ask me anything if the post wasn't clear enough.
I think your problem is that your'e loading as an int, not an array. I would look here for a better explanation. Is it possible to add an array or object to SharedPreferences on Android particularyly sherifs' answer

How to store strings in Shared Preferences

I would like the user to be able to create a nickname for a string that shows up in their textview. The app will feed a string into the activity through a service and display it in a textview. I would then like the user to be able to nickname that string, so that every time the string is displayed again the nickname will show up instead of the original string.
My question is, can I use shared preferences to do this? What would be the logic behind the user being able to assign nicknames? If you could point out any literature or sample code that would be greatly appreciated as well. Thank you for any help.
Algorhithm:
At a certain point in your app lifecycle, write a preference using a "name" and a value.
Retrieve the value when the app starts and compare it to something.
Act consequently.
From the reference site: http://developer.android.com/guide/topics/data/data-storage.html#pref
Using Shared Preferences
The SharedPreferences class provides a general framework that allows you to save and retrieve persistent key-value pairs of primitive data types. You can use SharedPreferences to save any primitive data: booleans, floats, ints, longs, and strings. This data will persist across user sessions (even if your application is killed).
User Preferences
Shared preferences are not strictly for saving "user preferences," such as what ringtone a user has chosen. If you're interested in creating user preferences for your application, see PreferenceActivity, which provides an Activity framework for you to create user preferences, which will be automatically persisted (using shared preferences).
To get a SharedPreferences object for your application, use one of two methods:
getSharedPreferences() - Use this if you need multiple preferences files identified by name, which you specify with the first parameter.
getPreferences() - Use this if you need only one preferences file for your Activity. Because this will be the only preferences file for your Activity, you don't supply a name.
To write values:
Call edit() to get a SharedPreferences.Editor.
Add values with methods such as putBoolean() and putString().
Commit the new values with commit()
To read values, use SharedPreferences methods such as getBoolean() and getString().
Here is an example that saves a preference for silent keypress mode in a calculator:
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();
}
}

How to display the server response on textview that should be displayed on all the screens in Header in android?

I want to display the server response on multiple screen in header bar in Android? Please, tell me how to do that? I created an abstract class and defined the Asynctask class. In onPostExecute method i am using the textview for displaying the result. Now my question is how all the activities access this textview?
I am new with Android. Please, give me the proper way to solve this?
May be you can use the shared preference feature of android to save the response.
References are How to use SharedPreferences in Android to store, fetch and edit values and http://www.vogella.com/tutorials/AndroidFileBasedPersistence/article.html
On each activity, you can set the header by referring the value from shared preference.
Create one base activity and extend that created base activity instead of activity. Create one xml file in base activity, in it only declare your header. nothing else, now to display use that xml and for the other contents you can use your actual xml file. So this one is for to set global header. Now, save your response to Shared preferences and use it throughout the app whenever you need.
Store the value into Shared preferences
SharedPreferences sharedPref = context.getSharedPreferences("app_prefs", Context.MODE_PRIVATE);
// saving
sharedPref.edit().putString("key", "value").commit();
// reading
sharedPref.getString("key", "default");
You need to store the response values in Stringbuffer
StringBuffer value =new StringBuffer("your response value");
SharedPreferences prefs = getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.putString("Identifier",value);
editor.commit(); //important, otherwise it wouldn't save.
Get the value in next activity
SharedPreferences prefs = getSharedPreferences(PREFS_NAME, 0);
final String myVariable = prefs.getString("Identifier", "value");

How to pre populate data between the screens in android

I have an app with 3 screens.
For each screens i have next button in each screen to go to the next screen.
problem:
Scenario 1:
--> I filled the data in first screen
--> I go to the second screen.
--> When i come back to the first page i am able to see the data what i filled.
-->But when i again go to the second page i am not able to see the data what i filled in the second form.
How can i manage this in android?
Thanks in advance...
You can save the data in Shared preferences. Check this : Shared Preferences Android and Example
Hope this helps.
You need to save the state yourself using your activities' lifecycle methods. Read this: http://developer.android.com/training/basics/activity-lifecycle/recreating.html
You can save temporary data in application data. Once in the onCreate method, you can reuse that data, or you can use an activity flag to ensure that there's only one instance of your activity in the backstack.
try
{
//in first run app. go to catch and in other go to try
SharedPreferences pref = getSharedPreferences("pref",0);
SharedPreferences.Editor edit = pref.edit();
String x= pref.getString("login", null);
edit.commit();
if(x.equals("first"))
{
//here you can fill editbox by value you entered before
edt1.setText(x);
//and make this way to all edittext
}
}
catch(Exception e)
{
SharedPreferences pref = getSharedPreferences("pref",0);
SharedPreferences.Editor edit = pref.edit();
edit.putString("login",edt1.getText().toString());
//edt1.getText().toString() value(s) you want to save
edit.commit();
Intent intent = new Intent(getApplicationContext(), First.class);
startActivity(intent);
}

How to keep the project always be open using login page on android/eclipse

I have one log in page for the project 'x'.My need is if at first i entered into the project by providing proper values in to the log in page of the project.The project always want to be signed-in, whenever i try to open the project.How to achieve this concept?
Thanks for your precious time!..
Many applications may provide a way to capture user preferences on the settings of a specific application or an activity. For supporting this, Android provides a simple set of APIs.
Preferences are typically name value pairs. They can be stored as “Shared Preferences” across various activities in an application (note currently it cannot be shared across processes). Or it can be something that needs to be stored specific to an activity.
Shared Preferences: The shared preferences can be used by all the components (activities, services etc) off the applications.
Activity handled preferences: These preferences can only be used with in the activity and can not be used by other components of the application.
Shared Preferences:
The shared preferences are managed with the help of the getSharedPreferences method of the Context class. The preferences are stored in a default file(1) or you can specify a file name(2) to be used to refer to the preferences.
(1) Here is how you get the instance when you specify the file name
public static final String PREF_FILE_NAME = "PrefFile";
SharedPreferences preferences = getSharedPreferences(PREF_FILE_NAME, MODE_PRIVATE);
MODE_PRIVATE is the operating mode for the preferences. It is the default mode and means the created file will be accessed by only the calling application. Other two mode supported are MODE_WORLD_READABLE and MODE_WORLD_WRITEABLE. In MODE_WORLD_READABLE other application can read the created file but can not modify it. In case of MODE_WORLD_WRITEABLE other applications also have write permissions for the created file.
(2) The recommended way is to use by the default mode, without specifying the file name:
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
Finally, once you have the preferences instance, here is how you can retrieve the stored values from the preferences:
int storedPreference = preferences.getInt("storedInt", 0);
To store values in the preference file SharedPreference.Editor object has to be used. Editor is the nested interface of the SharedPreference class.
SharedPreferences.Editor editor = preferences.edit();
editor.putInt("storedInt", storedPreference); // value to store
editor.commit();
Editor also support methods like remove() and clear() to delete the preference value from the file.
Activity Preferences:
The shared preferences can be used by other application components. But if you do not need to share the preferences with other components and want to have activities private preferences. You can do that with the help of getPreferences() method of the activity. The getPreference method uses the getSharedPreferences() method with the name of the activity class for the preference file name.
Following is the code to get preferences:
SharedPreferences preferences = getPreferences(MODE_PRIVATE);
int storedPreference = preferences.getInt("storedInt", 0);
The code to store values is also same as in case of shared preferences.
SharedPreferences preferences = getPreference(MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putInt("storedInt", storedPreference); // value to store
editor.commit();
You can also use other methods like storing the activity state in database. Note Android also contains a package called android.preference. The package defines classes to implement application preferences UI.
To see some more examples check Android's Data Storage post on developers site.
For more info, check this link:
Making data persistent in android
Whenever you login set the user inside the preference file. Then in your main activity give a check whether you have value for this preference or not. If present, goto the landing page. Otherwise show the login page.
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
getLandingPage();
}
private void getLandingPage() {
if (isLoggedIn()) {
//goto login page
} else {
//goto landing page
}
}
/**
* Checks whether preference contains any value
*
* #return
*/
private boolean isLoggedIn() {
return ProjectPreferences.getUserName() == ProjectPreferences.NULL_STRING
? true
: false;
}
}
Also don't forget to set username while you login.

Categories

Resources