shared preference not able to get data - java

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

Related

Android: How to save the best score in a game?

I am a beginner programmer and I create a game for android and I came across a problem that I want after finishing the game to show me the best score that I managed to achieve in playing this game I made a condition
if(DOD> sharedPreferences.getInt("DOD_SHA",0));
of course I use sharedPreferences to save the best score here but this condition doesn't work at all and my sharedPreference takes any value even less than the last score
public class EndScreen extends AppCompatActivity {
TextView Levelwys,war;
Button GotoMenu;
int DOD,ODE,MNO,PIE,DZI,POT,SIL,LOG;
SharedPreferences sharedPreferences;
SharedPreferences.Editor editor;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_end_screen);
Levelwys = findViewById(R.id.textView15);
war = findViewById(R.id.textView19);
GotoMenu = findViewById(R.id.button);
sharedPreferences = getSharedPreferences("com.example.goodmath", Context.MODE_PRIVATE);
editor = sharedPreferences.edit();
Intent intent = getIntent();
int number = intent.getIntExtra(GameSingleActivity.LEVEL, 0);
DOD = intent.getIntExtra("DOD", 0);
ODE = intent.getIntExtra("ODE", 0);
MNO = intent.getIntExtra("MNO", 0);
PIE = intent.getIntExtra("PIE", 0);
DZI = intent.getIntExtra("DZI", 0);
POT = intent.getIntExtra("POT", 0);
SIL = intent.getIntExtra("SIL", 0);
LOG = intent.getIntExtra("LOG", 0);
Levelwys.setText(String.valueOf(number));
String test = String.valueOf(DOD);
Toast.makeText(getApplicationContext(), test, Toast.LENGTH_LONG).show();
Save();
GotoMenu.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
GotoMenu();
}
});
}
#Override
public void onBackPressed() {
}
void GotoMenu()
{
Intent intent1 = new Intent(this, MenuActivity.class);
startActivity(intent1);
}
void Save()
{
if(DOD> sharedPreferences.getInt("DOD_SHA",0));
{
editor.putInt("DOD_SHA",DOD);
editor.apply ();
editor.commit();
Toast.makeText(getApplicationContext(), "cos", Toast.LENGTH_LONG).show();
war.setText(String.valueOf(sharedPreferences.getInt("DOD_SHA",DOD)));
}
}
}
You have typo in your if condition:
if(DOD> sharedPreferences.getInt("DOD_SHA",0));
You have added extra semicolon at the end of this line. Because of this, the code below this condition was always called.
Delete this semicolon and everything should works fine:
if(DOD> sharedPreferences.getInt("DOD_SHA",0))
{
editor.putInt("DOD_SHA",DOD);
editor.apply ();
editor.commit();
Toast.makeText(getApplicationContext(), "cos", Toast.LENGTH_LONG).show();
war.setText(String.valueOf(sharedPreferences.getInt("DOD_SHA",DOD)));
}

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

My step counter does not reset the steps, even after uninstall

I use Sensor.TYPE_STEP_COUNTER I know it only resets when rebooting. Is there an alternative way to reset the steps to 0 when pressing a button?
Please see my code, you will find the Runactivity.class
Maybe I can do it in another way which resets the steps.
without having me to reboot every time.
public class RunActivity extends AppCompatActivity implements SensorEventListener{
private SensorManager sensorManager;
private TextView count;
boolean activityRunning;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_run);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
Bundle bundle = getIntent().getExtras();
final String naam = bundle.getString("naam");
TextView NaamView = null;
Button stopRun = (Button) findViewById(R.id.stopRun);
count = (TextView) findViewById(R.id.countView);
sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
NaamView = (TextView) findViewById(R.id.naamRunText);
NaamView.setText(naam);
stopRun.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String countValue = count.getText().toString();
Log.d("countVAL", String.valueOf(countValue));
Intent myIntent = new Intent(RunActivity.this, HomeScreenActivity.class);
Bundle bundle = new Bundle();
bundle.putString("naam", naam);
sensorManager.flush(RunActivity.this);
sensorManager.unregisterListener(RunActivity.this);
count.setText("0");
onStop();
myIntent.putExtras(bundle);
startActivity(myIntent);
}
});
}
#Override
protected void onResume() {
super.onResume();
activityRunning = true;
Sensor countSensor = sensorManager.getDefaultSensor(Sensor.TYPE_STEP_COUNTER);
if(countSensor != null){
sensorManager.registerListener(this, countSensor, SensorManager.SENSOR_DELAY_UI);
}else{
Toast.makeText(this, "Jouw apparaat heeft geen sensor!", Toast.LENGTH_LONG) .show();
}
}
#Override
public void onSensorChanged(SensorEvent event) {
if(activityRunning){
count.setText(String.valueOf(event.values[0]));
}else{
event.values[0] = 0;
}
}
#Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(this);
activityRunning = false;
}
#Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
protected void onDestroy() {
super.onDestroy();
}
}
When you click the reset button in the app save the current step count to SharedPreferences. And you'll need a way to find out when was the last reboot because every time you reboot the saved count number gets invalid.
private Integer stepsInSensor;
private Integer stepsAtReset;
void onCreate() {
SharedPreferences prefs = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE);
stepsAtReset = prefs.getInt("stepsAtReset", 0);
}
public void onClick(View v) {
stepsAtReset = stepsInSensor;
if (stepsAtReset != null) {
SharedPreferences.Editor editor =
getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE).edit();
editor.putInt("stepsAtReset", stepsAtReset);
editor.commit();
}
// you can now display 0:
count.setText(String.valueOf(0));
}
#Override
public void onSensorChanged(SensorEvent event) {
if(activityRunning){
stepsInSensor = Integer.valueOf(event.values[0]);
if (stepsAtReset = null) {
stepsAtReset = stepsInSensor;
}
int stepsSinceReset = stepsInSensor - stepsAtReset;
if (stepsSinceReset < 0) {
stepsAtReset = stepsInSensor;
stepsSinceReset = 0;
}
count.setText(String.valueOf(stepsSinceReset));
}else{
event.values[0] = 0;
}
}
I searched on it and tried to do it with different ways. Nothing Helped.
Then I found the most simple way possible.
In onSensorChanged() just add the counter so when ever onSensorChanged() will be called (it will be called on every step), counter will simply count the steps then show this counter to your UI instead of showing the value of event.values[0]
on your Reset button make the counter 0 again.
Nope, based on the Sensor API
A sensor of this type returns the number of steps taken by the user
since the last reboot while activated. The value is returned as a
float (with the fractional part set to zero) and is reset to zero only
on a system reboot.
It can only be reset when the system is rebooted

updating shared prefrences in android

well i'm just testing the idea of shared preferences to save the user progress, but this simple code is not working, when i pass lev1 it should update preffile so that at next app start it should opens directly to lev2Activity, everything is ok even log cat is clean but nothing happens, i don't know whats wrong with my code, any help will be appreciated.
MainActivity.java
private Button b1;
public static final String levstate= "levstate";
private Context mycontext;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mycontext= this;
b1= (Button) findViewById(R.id.b1);
b1.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v) {
MainActivity.savelevstate(1, mycontext);
Intent i= new Intent(MainActivity.this, Lev1Activity.class);
startActivity(i);
}
});
}
public static void savelevstate(int state, Context mycontext)
{
SharedPreferences pref= mycontext.getSharedPreferences("preffile", MODE_APPEND);
Editor editor= pref.edit();
editor.putInt("levstate", state);
editor.commit();
}
public static int getlevstate(Context mycontext)
{
SharedPreferences pref= mycontext.getSharedPreferences("preffile", MODE_APPEND);
int state= pref.getInt("levstate", 1);
return state;
}
Lev1Activity.java
private EditText et1;
private Button b1;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_lev1);
et1= (EditText) findViewById(R.id.et1);
b1= (Button) findViewById(R.id.b1);
}
public void Next (View v)
{
String value= et1.getText().toString();
int finalvalue= Integer.parseInt(value);
if(finalvalue==22)
{
Intent i = new Intent (this, Lev2Activity.class);
startActivity(i);
MainActivity.savelevstate(2, this);
this.finish();
}
}
Your idea of using sharedPreferences is excellent. However, if you look at your MainActivity's onCreate(), you can see that you never check the last level state before starting the intent. The app runs, the user clicks on button "b1" and it immediately starts Lev1Activity. Assuming you want the correct level to start when the user presses that same button, you'd have to check for the current level state and then link that state to its appropriate level Activity.
For example (MainActivity.java):
b1.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v) {
Intent i;
switch(getlevstate(myContext)) {
case 1:
i = new Intent(myContext, Lev1Activity.class);
break;
case 2:
i = new Intent(myContext, Lev2Activity.class);
break;
case 3:
i = new Intent(myContext, Lev3Activity.class);
break;
case 4
i = new Intent(myContext, Lev4Activity.class);
break;
...
}
startActivity(i);
}
});
Using MODE_APPEND should work as well as using MODE_PRIVATE, however it is recommended to use the latter.
I would recommend to you to create a new class for working with SharedPreferences.
Here is a example for saving and retrieving data from shared preferences:
public class SharedPreferenceSettings {
private static final String PREFS_NAME = "MY_APP_SETTINGS";
private static final String PREFS_LANGUAGE = "LANGUAGE";
private static final String PREFS_CITY = "CITY";
private final SharedPreferences settings;
public SharedPreferenceSettings(Context context) {
settings = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
}
public void setLanguage(String language) {
settings.edit().putString(PREFS_LANGUAGE, language).apply();
}
public String getlanguage() {
return settings.getString(PREFS_LANGUAGE, "english");
}
public void setCity(String city) {
settings.edit().putString(PREFS_CITY, city).apply();
}
public String getCity() {
return settings.getString(PREFS_CITY, "london");
}
}
For more info, check official Android documentation - link
You are only saving the states, but you aren't checking it anywhere in the code.
In MainActivity try this :
b1.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v) {
if(getlevstate(MainActivity.this)==2) {
Intent i= new Intent(MainActivity.this, Lev2Activity.class);
startActivity(i);
} else {
MainActivity.savelevstate(1, mycontext);
Intent i= new Intent(MainActivity.this, Lev1Activity.class);
startActivity(i);
}
}
});
Not sure this is the problem, but when I use Preferences I use Context.MODE_PRIVATE this is the only difference between my code and yours, maybe it will help!
Edit : I might be wrong, but I don't see anywhere the call to getlevstate. After setting this
et1= (EditText) findViewById(R.id.et1);
You shoud do somehing like this :
et1.setText(""+getlevstate(this))

Categories