SharedPreferences loses data when application is destroyed - java

So I am trying to save data in sharePreferences in onPaus() method, I've tried same thing in onCreate() too, didn't work , here is a code :
public class Favorite extends Activity implements ListView.OnItemClickListener
{
private static final String PREFS_FILE = "com.example.stewiesh.eduguide.preferences1";
private static final String KEY_FAVORITE = "Key_favorite";
static ArrayList<String> uniID = new ArrayList<String>();
/** SharedPreferences preferences;
SharedPreferences.Editor editor; **/
ArrayAdapter<String> adapter;
ListView list;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.favorite);
list = (ListView) findViewById(R.id.favoriteList);
adapter = new ArrayAdapter<String>(this, R.layout.list_layout);
list.setOnItemClickListener(this);
list.setAdapter(adapter);
// preferences = getSharedPreferences(PREFS_FILE, Context.MODE_PRIVATE);
// editor = preferences.edit();
// setData();
runOnUiThread(new Runnable() {
public void run() {
System.out.println("i am out");
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
adapter.add(settings.getString(KEY_FAVORITE,"none of them is here bitch"));
adapter.notifyDataSetChanged();
}
});;
}
/**
public void setData()
{
for (int i = 0; i < Page2.responses.length; i++)
{
for(int j=0;j<uniID.size();j++)
{
if(Page2.responses[i].getPrograma().toString().equals(uniID.get(j)))
{
editor.clear();
editor.putString(KEY_FAVORITE,Page2.responses[i].getFakulteti()+" -- "+Page2.responses[i].getUniversiteti()+" "+Page2.responses[i].getPrograma().toString());
// editor.commit();
// editor.apply();
}
}
}
}
**/
#Override
protected void onPause() {
super.onPause();
// preferences = getSharedPreferences(PREFS_FILE, Context.MODE_PRIVATE);
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
SharedPreferences.Editor editor = preferences.edit();
for (int i = 0; i < Page2.responses.length; i++)
{
for(int j=0;j<uniID.size();j++)
{
if(Page2.responses[i].getPrograma().toString().equals(uniID.get(j)))
{
editor.clear();
editor.putString(KEY_FAVORITE,Page2.responses[i].getFakulteti()+" -- "+Page2.responses[i].getUniversiteti()+" "+Page2.responses[i].getPrograma().toString());
editor.commit();
}
}
}
//editor.apply();
}
public void onItemClick(AdapterView<?> parent, View view, int position, long id)
{
}
}
when I destroy app, than launch it , it gives me nothing, I can't get why it's not saving data,I've tried various things but...

First of all you should remove
runOnUiThread(new Runnable()
{
public void run() {
});
this part from your code:
runOnUiThread(new Runnable() {
public void run() {
System.out.println("i am out");
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
adapter.add(settings.getString(KEY_FAVORITE,"none of them is here bitch"));
adapter.notifyDataSetChanged();
}
});
because you are already running that part of your code in the UI thread, so adding runOnUiThread again is meaningless.
The reason why you weren't able to save anything is because you called
editor.clear() in the loop.
According to the Documentation:
clear() - Mark in the editor to remove all values from the preferences.
All you need to do is just put and commit(), no need to call editor.apply()
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
SharedPreferences.Editor editor = preferences.edit();
for (int i = 0; i < Page2.responses.length; i++)
{
for(int j=0;j<uniID.size();j++)
{
if(Page2.responses[i].getPrograma().toString().equals(uniID.get(j)))
{
editor.putString(KEY_FAVORITE,Page2.responses[i].getFakulteti()+" -- "+Page2.responses[i].getUniversiteti()+" "+Page2.responses[i].getPrograma().toString());
}
}
}
editor.commit();
You don't need to kept on committing, only commit when you are done putting data.

Related

How can i retrive data from shared prefrances by on click or on click listiner?

public void saveData(View view) {
SharedPreferences mySharedPreferences = getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor myEditor = mySharedPreferences.edit();
savedPage = pdfView.getCurrentPage();
myEditor.putInt("retrievedPage",savedPage);
myEditor.apply();
if (true){
Toast.makeText(getApplicationContext(), "تم حفظ الصفحة", Toast.LENGTH_SHORT).show();
}
else {
Toast.makeText(getApplicationContext(), "لم يتم حفظ الصفحة", Toast.LENGTH_SHORT).show();
}
}
public void RetriveData(View view){
SharedPreferences mySharedPreferences = getPreferences(Context.MODE_PRIVATE);
savedPage = mySharedPreferences.getInt("retrievedPage",0);
pagenumber = savedPage;
}
You can use this code to retrieve data from shared preferences.
To write data:
SharedPreferences mySharedPreferences = getSharedPreferences("AUTHENTICATION_FILE_NAME", Context.MODE_PRIVATE);
SharedPreferences.Editor myEditor= preferences.edit();
savedPage = pdfView.getCurrentPage();
myEditor.putInt("retrievedPage",savedPage);
myEditor.apply();
To Read data:
SharedPreferences prfs = getSharedPreferences("AUTHENTICATION_FILE_NAME", Context.MODE_PRIVATE);
Int savedPage = prfs.getInt("retrievedPage", "");
I did it. I put it in on create and get it from on click.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
SharedPreferences mySharedPreferences = getPreferences(Context.MODE_PRIVATE);
savedPage = mySharedPreferences.getInt("retrievedPage",0);
pagenumber = savedPage;
public void retriveData(View view){
finish();
startActivity(getIntent());
}

Unable to save data via SharedPreferences in Android

I'm unable to save data from textView when I'm opening an app again I'm getting error in textview:
Error message Field XXXXX should be numeric
I think it's not saving any data or I'm using an incorrect method. Thank you in advance!
class MyJavaScriptInterface {
#JavascriptInterface
#SuppressWarnings("unused")
public void processHTML(final String html) {
myWebView.post(new Thread() {
#Override public void run() {
TextView text = findViewById(R.id.textView);
if(!sharedPreferences.contains("statusKey")){
sharedPreferences = getSharedPreferences("prefID", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("statusKey", html);
editor.apply();
text.setText(html);
}
else {
text.setText(sharedPreferences.getString("statusKey", ""));
}
}
});
}
}
You initiating sharedPreference late after checking condition. So first fix that.
class MyJavaScriptInterface {
#JavascriptInterface
#SuppressWarnings("unused")
public void processHTML(final String html) {
myWebView.post(new Thread() {
#Override public void run() {
TextView text = findViewById(R.id.textView);
sharedPreferences = getSharedPreferences("prefID", Context.MODE_PRIVATE);
if(!sharedPreferences.contains("statusKey")){
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("statusKey", html);
editor.apply();
text.setText(html);
}
else {
text.setText(sharedPreferences.getString("statusKey", ""));
}
}
});
}
}
class MyJavaScriptInterface {
#JavascriptInterface
#SuppressWarnings("unused")
public void processHTML(final String html) {
myWebView.post(new Thread() {
#Override public void run() {
TextView text = findViewById(R.id.textView);
sharedPreferences = getSharedPreferences("prefID", Context.MODE_PRIVATE);
if(!sharedPreferences.contains("statusKey")){
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("statusKey", html);
editor.apply();
text.setText(html);
}
else {
text.setText(sharedPreferences.getString("statusKey", ""));
}
}
});
}
}
Try above code

shared preference not able to get data

I am trying to make promo code for my app when the user gives correct value in the EditText I will set a boolean value false and a number will be stored in shared preferences. But don't know why the value is not getting decremented and even if it decreases and even if I do it multiple times then only it moves from 30 to 29.
So I created a test app where I am setting the value in onClick what happens when the promo code is equal. So the decrement thing is when the user open the app the number will get decreased and stored back when the boolean value is false
public class MainActivity extends AppCompatActivity {
TextView textView;
Button button, button1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = (TextView) findViewById(R.id.textView);
button = (Button) findViewById(R.id.button);
button1 = (Button) findViewById(R.id.button2);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SharedPreferences prefs = getSharedPreferences("Admob", 0);
SharedPreferences.Editor editor = prefs.edit();
editor.putBoolean("ShowAd", false);
editor.putLong("daycounter", 30);
editor.commit();
}
});
caller();
}
#Override
protected void onResume() {
super.onResume();
caller();
}
#Override
protected void onPause() {
super.onPause();
caller();
}
public void caller() {
SharedPreferences settings = getSharedPreferences("Admob", 0);
boolean ad_start = settings.getBoolean("ShowAd", true);
long ad = settings.getLong("daycounter", 0);
SharedPreferences prefs = getSharedPreferences("apprater", 0);
SharedPreferences.Editor editor = prefs.edit();
Log.e("toaster", "" + ad_start);
if (!ad_start) {
long ads = ad -1 ;
if (ad > 0) {
editor.putLong("daycounter", ads);
editor.putBoolean("ShowAd", true);
editor.commit();
Toast.makeText(MainActivity.this, "" + ads, Toast.LENGTH_SHORT).show();
textView.setText(ad + "R" + ad_start);
}
}
}
}
In the dummy app I am showing the data in TextView so I am calling onResume and onPause method otherwise I know onCreate is enough. I don't understand whats wrong in the algorithm. I am not getting any error at all and in the toast I am only able to decrease the value till 29 . I have tried all types of decrement operation. Any advice will be helpful.**I am able to save the data onle problem is with the lonng value is not getting saved and not getting decremented **
Put these methods in your utils class and use
public static void cacheBoolean(Context ctx, String k, Boolean v) {
SharedPreferences prefs = getSharedPreferences(ctx);
prefs.edit().putBoolean(k, v).apply();
}
public static Boolean getCachedBoolean(Context ctx, String k, Boolean defaultValue) {
SharedPreferences prefs = getSharedPreferences(ctx);
return prefs.getBoolean(k, defaultValue);
}
public static void cacheString(Context ctx, String k, String v) {
SharedPreferences prefs = getSharedPreferences(ctx);
prefs.edit().putString(k, v).apply();
}
public static String getCachedString(Context ctx, String k, String defaultValue) {
SharedPreferences prefs = getSharedPreferences(ctx);
return prefs.getString(k, defaultValue);
}
public static void cacheInt(Context ctx, String k, int v) {
SharedPreferences prefs = getSharedPreferences(ctx);
prefs.edit().putInt(k, v).apply();
}
public static int getCachedInt(Context ctx, String k, int defaultValue) {
SharedPreferences prefs = getSharedPreferences(ctx);
return prefs.getInt(k, defaultValue);
}
public static void clearCachedKey(Context context, String key) {
getSharedPreferences(context).edit().remove(key).apply();
}
You don't need to put shared preferences everywhere, just initialize it inside onCreate method and access from constant String, so will easy to access it.
public class MainActivity extends AppCompatActivity {
TextView textView;
Button button, button1;
SharedPreferences prefs;
SharedPreferences.Editor editor;
final String pref_name = "Admob";
final String ad_name = "ShowAd";
final String day_count = "daycounter";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = (TextView) findViewById(R.id.textView);
button = (Button) findViewById(R.id.button);
button1 = (Button) findViewById(R.id.button2);
prefs = getSharedPreferences(pref_name, 0);
editor = prefs.edit();
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
editor.putBoolean(ad_name, false);
editor.putLong(day_count, 30);
editor.commit();
}
});
caller();
}
#Override
protected void onResume() {
super.onResume();
caller();
}
#Override
protected void onPause() {
super.onPause();
caller();
}
public void caller() {
boolean ad_start = prefs.getBoolean(ad_name, true);
long ad = prefs.getLong(day_count, 0);
Log.e("toaster", "" + ad_start);
if (!ad_start) {
long ads = ad -1 ;
if (ad < 0) {
editor.putBoolean(ad_name, true);
}
editor.putLong(day_count, ads);
editor.commit();
Toast.makeText(MainActivity.this, "" + ads, Toast.LENGTH_SHORT).show();
textView.setText(ad + "R" + ad_start);
}
}
}
I was making mistake in this method part thx to Ahmed sir My mistake was setting the value equal to
if (ad > 0) so when the value is more than zero the boolean was st as true and the data never get a chance to get decremented more
public void caller() {
SharedPreferences settings = getSharedPreferences("Admob", 0);
boolean ad_start = settings.getBoolean("ShowAd", true);
long ad = settings.getLong("daycounter", 0);
Log.e("toaster", "" + ad_start);
if (!ad_start) {
SharedPreferences prefs = getSharedPreferences("Admob", 0);
SharedPreferences.Editor editor = prefs.edit();
long ads = ad - 1;
if (ad < 0) {
editor.putBoolean("ShowAd", true);
}
editor.putLong("daycounter", ads);
editor.commit();
Toast.makeText(MainActivity.this, "" + ads, Toast.LENGTH_SHORT).show();
textView.setText(ad + "R" + ad_start);
}
}

Using threads to apply UI changes in android

I ran into a problem and need some help. I want to remove some user's files after a button click and also show the files removing progress (in progressbar) and also show some Fancy UI. First i changed the layout after button click and hide some elements and visible the others. after that i called methods to remove files. The problem is that i can not see any UI changes and system hangs until all user file removed and after that based on my scenario it go to another activity. I've google around and found that i should use thread or UI thread but exactly don't know how. Here is my code :
new Thread() {
public void run() {
try {
runOnUiThread(new Runnable() {
#Override
public void run() {
ProgressBar spinner;
spinner = (ProgressBar) findViewById(R.id.progressBar);
listview.setVisibility(View.GONE);
spinner.setVisibility(View.VISIBLE);
preresult.setVisibility(View.VISIBLE);
resulttxt.setVisibility(View.VISIBLE);
wv.setVisibility(View.VISIBLE);
btnClear.setVisibility(View.GONE);
wv.loadUrl("file:///android_asset/rocket.gif");
resulttxt.setText("");
}
});
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}.start();
Thread b = new Thread() {
#Override
public void run() {
Long TotalJunk = 0L;
for (Apps social : checkedSocial) {
if (social.getName() == "Telegram") {
preresult.setText("Calculating Files :");
resulttxt.setText("Telegram");
preresult.setText("Removing Files...");
clearMediashistory(social.path);
TotalJunk = TotalJunk + social.junksize;
}
}
SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
SharedPreferences.Editor editor = pref.edit();
editor.putString("FreeUp", formatSize(TotalJunk));
//commits your edits
editor.commit();
}
};
b.start();
What is wrong with my code. Is there any better method to do that?
Use AsyncTask instead of Thread
https://developer.android.com/reference/android/os/AsyncTask.html
Android AsyncTask example and explanation
Try
new AsyncTask<String, String, String> () {
#Override
protected void onPreExecute() {
//show loader if requried
}
#Override
protected String doInBackground(String... params) {
Long TotalJunk = 0L;
for (Apps social : checkedSocial) {
if (social.getName() == "Telegram") {
preresult.setText("Calculating Files :");
resulttxt.setText("Telegram");
preresult.setText("Removing Files...");
clearMediashistory(social.path);
TotalJunk = TotalJunk + social.junksize;
}
}
SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
SharedPreferences.Editor editor = pref.edit();
editor.putString("FreeUp", formatSize(TotalJunk));
//commits your edits
editor.commit();
}
#Override
protected void onPostExecute(String result){
ProgressBar spinner;
spinner = (ProgressBar) findViewById(R.id.progressBar);
listview.setVisibility(View.GONE);
spinner.setVisibility(View.VISIBLE);
preresult.setVisibility(View.VISIBLE);
resulttxt.setVisibility(View.VISIBLE);
wv.setVisibility(View.VISIBLE);
btnClear.setVisibility(View.GONE);
wv.loadUrl("file:///android_asset/rocket.gif");
resulttxt.setText("");
}
}.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTER);

switch button with preference activity

I want to use switch button in my preference/settings activity to disable some code in my app when the switch is off. Please can anyone give me a little tutorial using shared preferences that uses switch/toggle button.
I have this code but can't figure out where to put my on click listener and how to use it so it disables a certain part of my code when the button is set to off
preference.xml:
<SwitchPreference
android:key="test"
android:title="Test" />
PreferenceActivity:
public class TestPrefActivity extends PreferenceActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.sample);
}}
In main activity
SharedPreferences sharedPrefs = PreferenceManager
.getDefaultSharedPreferences(MainActivity.this);
sharedPrefs.registerOnSharedPreferenceChangeListener(new OnSharedPreferenceChangeListener() {
#Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
boolean test = sharedPreferences.getBoolean("test", false);
Log.e(TAG, "Value:" + test);
}
});
Here is a simple example:
<SwitchPreference
android:key="test"
android:title="Test"
android:defaultValue="false" />
In your code:
public class TestPrefActivity extends PreferenceActivity implements onSharedPreferenceChangeListener {
public SwitchPreference testPref;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.sample);
testPref = (SwitchPreference) findPreference("test"); //Preference Key
}
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
if (key.equals("test")) {
boolean test = sharedPreferences.getBoolean("test", false);
//Do whatever you want here. This is an example.
if (test) {
testPref.setSummary("Enabled");
} else {
testPref.setSummary("Disabled");
}
}
#Override
public void onResume() {
super.onResume();
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(TestPrefActivity.this);
boolean test = preferences.getBoolean("test", false);
if (test) {
testPref.setSummary("Enabled");
} else {
testPref.setSummary("Disabled");
}
}
}
The SwitchPreference will save your key value automatically. You don't have to write code for it. It will be saved as a boolean.
You can then retrieve it from any activity you want like:
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
boolean test = sharedPreferences.getBoolean("test", false);
Use these methods to save preferences and load preferences:
//save prefs
public void savePrefs(String key, Boolean value){
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putBoolean(key, value);
editor.commit();
}
//get prefs
private Boolean loadPrefs(String key, Boolean value){
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
Boolean data = sharedPreferences.getBoolean(key, value);
return data;
}
}
When you are saving values with this method you can do so like this:
boolean toggleButton = true;
savePrefs("toggle", toggleButton);
When you are retrieving values follow this example:
boolean toggleButton = loadPrefs("toggle", toggleButton);

Categories