Unable to save data via SharedPreferences in Android - java

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

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

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

Get value from int type of SharedPreferences to a String

I'm stuck with this, problem, I need to save a color from users choice via SharedPreferences and I did that with this code:
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
final SharedPreferences.Editor editor = preferences.edit();
imgBtnDarkBlue.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
tvColorScheme.setTextColor(getResources().getColor(R.color.colorPrimary));
editor.putString("color", tvColorScheme.getTextColors().toString());
editor.commit();
}
});
imgBtnGreen.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
tvColorScheme.setTextColor(getResources().getColor(R.color.green));
editor.putInt("color", getResources().getColor(R.color.green));
editor.commit();
}
});
imgBtnBlue.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
tvColorScheme.setTextColor(getResources().getColor(R.color.blue));
editor.putInt("color", getResources().getColor(R.color.blue));
editor.commit();
}
});
And retrieving it in another Activity:
int colorScheme = preferences.getInt("color", 0);
if (colorScheme == 0) {
imgViewColorScheme.setBackgroundColor(getResources().getColor(R.color.colorPrimary));
} else {
imgViewColorScheme.setBackgroundColor(colorScheme);
}
Now I need to check which color has user selected and put it's value in String. How do I do that?
Print in the log first as
Log.d("somestring", ""+colorScheme );
Then try this way.
String.valueOf(colorScheme);

Method did not work without warning in AndroidStudio

This app using a AndroidAnnotations.
I don't get any errors. I try implement loadVariable() in onCreate, but it is not imposible by Framework docs, because onCreate can't have a views. So question is how to show data right after launching application from SharedPreference? Additionaly, when i checked boxes, textView did not show numbers od checked boxes.
What i should do now ?
#EActivity(R.layout.activity_main2)
public class Main2Activity extends AppCompatActivity implements CompoundButton.OnCheckedChangeListener {
private int numberOfTrue;
#ViewById(R.id.tv1)
TextView tv1;
#ViewById(R.id.cb1)
CheckBox cb1;
#ViewById(R.id.cb2)
CheckBox cb2;
#ViewById(R.id.cb3)
CheckBox cb3;
#ViewById(R.id.cb4)
CheckBox cb4;
#AfterViews
void update() {
cb1.setChecked(getFromSP("cb1"));
cb2.setChecked(getFromSP("cb2"));
cb3.setChecked(getFromSP("cb3"));
cb4.setChecked(getFromSP("cb4"));
}
#Click
void b2() {
Intent output = new Intent();
output.putExtra("number", numberOfTrue);
setResult(Activity.RESULT_OK, output);
finish();
}
#AfterViews
void update2() {
loadVariable();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
switch(buttonView.getId()){
case R.id.cb1:
saveInSp("cb1",isChecked);
if (isChecked == true){
numberOfTrue++;
}
else
{
numberOfTrue--;
}
break;
case R.id.cb2:
saveInSp("cb2",isChecked);
if (isChecked == true){
numberOfTrue++;
}
else
{
numberOfTrue--;
}
break;
case R.id.cb3:
saveInSp("cb3",isChecked);
if (isChecked == true){
numberOfTrue++;
}
else
{
numberOfTrue--;
}
break;
case R.id.cb4:
saveInSp("cb4",isChecked);
if (isChecked == true){
numberOfTrue++;
}
else
{
numberOfTrue--;
}
break;
}
saveVariable(numberOfTrue);
loadVariable();
}
private boolean getFromSP(String key){
SharedPreferences preferences = getApplicationContext().getSharedPreferences("PROJECT_NAME", android.content.Context.MODE_PRIVATE);
return preferences.getBoolean(key, false);
}
private void saveInSp(String key,boolean value) {
SharedPreferences preferences = getApplicationContext().getSharedPreferences("PROJECT_NAME", android.content.Context.MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putBoolean(key, value);
editor.commit();
}
private void saveVariable(int numberOfTrue){
SharedPreferences sharedPref = this.getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putInt("key2", numberOfTrue);
editor.commit();
}
private void loadVariable(){
SharedPreferences sharedPref = this.getPreferences(Context.MODE_PRIVATE);
int number = sharedPref.getInt("key2", 0);
tv1.setText(""+number);
numberOfTrue=number;
}
}

SharedPreferences loses data when application is destroyed

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.

Categories