SharedPreferences in Android saving the visibility of an ImageView - android

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

Related

save button state on android studio

I am creating an app with lot of buttons. I programmed the buttons so if I don't click them, the background color stays white and if I click them the background color turns to green. I want to save this green button. so if I close the app and reopen it I want previously turned green buttons to remain green but unfortunately reopening the apps makes the button white. What can I do?
We can solve this with SharedPreferences.
SharedPreferences will store the data that you want.
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(activity);
prefs.edit().putBoolean("button1", true).apply();
This above code for to write your data to SharedPreferences
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(activity);
boolean isButtonPressed = prefs.getBoolean("button1", false);
Above code for read your button value with key ("button1"). default value would be false beacuse if you not stored any values for that key it will return as false.
I think your best choice would be to just use SharedPreferences. SharedPreferences let you easily save values. For example:
When you press a button
final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(activity);
prefs.edit().putBoolean("button_1_pressed", true).apply();
When you start your activity. I.e (OnCreate())
final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(activity);
boolean isButtonPressed = prefs.getBoolean("button_1_pressed", false);
if (isButtonPressed) {
// TODO make button green
}

Saving Fragment's State Through out the application

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

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);
}

Set<String> in android sharedpreferences does not save on force close

Im trying to use androids sharedpreferences, I´ve logged everything and the code below really commits the string set. The problem is when I force close the app and start again, the settings.getStringSet returns an empty set. No errormessages anywhere.
I´ve tried PreferenceManager.getDefaultSharedPreferences but that does not work for me either.
Thanks for you time.
public static final String PREFS_NAME = "MyPrefsFile";
private static final String FOLLOWED_ROUTES = "followedRoutes";
and later on when saved is called:
public void onFollowClicked(View view){
SharedPreferences settings = getSharedPreferences(PREFS_NAME, MODE_PRIVATE);
SharedPreferences.Editor editor = settings.edit();
Set<String> follows = settings.getStringSet(FOLLOWED_ROUTES, new HashSet<String>());
follows.add(routeId);
editor.putStringSet(FOLLOWED_ROUTES, follows);
editor.commit();
}
You can also work around the bug mentioned by g00dy this way:
Get the set from sharedPreferences and save it in a variable.
Then just delete the set in sharedpreferences before adding it again when saving.
SharedPreferences.Editor editor= sharedPref.edit();
editor.remove("mSet");
editor.apply();
editor.putStringSet("mSet", mSet);
editor.apply();
Make sure to use apply() or commit() twice.
Alternatively, if you are working in Kotlin simply :
PreferenceManager.getDefaultSharedPreferences(applicationContext)
.edit {
this.remove("mSet")
this.apply()
this.putStringSet("mSet", mSet)
}
Take a look here.
Also for refference:
SharedPreferences
SharedPreferences.Editor
EDIT:
There's actually a bug with this one, see here. An extract from there:
This problem is still present on the 17 API level.
It is caused because the getStringSet() method of the
SharedPreferences class doesn't return a copy of the Set object: it
returns the entire object and, when you add new elements to it, the
commitToMemory method of the SharedPrefencesImpl.EditorImpl class see
that the existing value is equal to the previous one stored.
The ways to workaround this issue is to make a copy of the Set
returned by SharedPreferences.getStringSet or force the write to
memory using other preference that always change (for example, a
property that stores the size of the set each time)
EDIT2:
There might be a solution here, take a look.

Categories

Resources