Can't make the app save variables when it exits - java

I am making an app where the user keeps pressing a button to get in-app money, my problem is whenever the app is closed or paused when i return the app's Money counter resets to zero. So i tried to make a Shared Preferences code to save my variables when the app pauses or stops, However when i resume the app the Counter doesn't reset to zero but as soon as i click on the button to generate money it resets to zero? Any help would be appreciated.
The Code being executed when the button is pressed:
myBalance += 1;
TextView balanceShow = findViewById(R.id.balanceShow);
balanceShow.setText("Balance: " + myBalance + "Coin");
And this is the code executed on the application exit event (The code that saves the user balance):
TextView balanceShow = findViewById(R.id.balanceShow);
String balance = balanceShow.getText().toString();
SharedPreferences data = getSharedPreferences("MySavedData", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = data.edit();
editor.putString("BALANCE", balance);
editor.commit();
Toast.makeText(this, "Saved!", Toast.LENGTH_SHORT).show();
And finally this is the code executed on the app's resume that loads the user's balance when he comes back:
TextView balanceShow = findViewById(R.id.balanceShow);
SharedPreferences data = getSharedPreferences("MySavedData", Context.MODE_PRIVATE);
String balance = data.getString("BALANCE", "No Data Found!");
balanceShow.setText(balance);
Toast.makeText(this, "Loaded!", Toast.LENGTH_SHORT).show();
To make things more clear:
1- The app starts with a "0" Coins balance.
2- I click on the button, to generate "1" Coin every time i press it which triggers the first code i posted.
3- Let's say i made "80" Coin.
4- Now i close the app.
5- I open the app, I find that my balance is "80" Coins. Great!
6- I press on the button, then the balance resets to "0" Coins and starts from scratch again!
Please help it's been hours since i am trying to figure what's happening, and i couldn't, What's wrong with the code? Also i tried numerous other saving codes and they all crash the app, this is the only Saving code that seems to work with me, Any help would be highly appreciated! Thanks!

TextView balanceShow = findViewById(R.id.balanceShow);
SharedPreferences data = getSharedPreferences("MySavedData", Context.MODE_PRIVATE);
String balance = data.getString("BALANCE", "No Data Found!");
balanceShow.setText(balance);
Toast.makeText(this, "Loaded!", Toast.LENGTH_SHORT).show();
Herein lies your problem. You are only updating the value of the TextField, whereas the value of the counter behind the TextField (here myBalance) is zero. Instead of saving the data stored in the TextField to SharedPreferences, you should instead store the integer data in the myBalance counter to the preferences and load that when you resume the app.
In short, in order to save coins:
private void saveCoinsToPreferences() {
SharedPreferences data = getSharedPreferences("MySavedData", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = data.edit();
editor.putInt("BALANCE", myBalance);
editor.commit();
Toast.makeText(this, "Saved!", Toast.LENGTH_SHORT).show();
}
And in order to retrieve coins:
private int retrieveCoins() {
TextView balanceShow = findViewById(R.id.balanceShow);
SharedPreferences data = getSharedPreferences("MySavedData", Context.MODE_PRIVATE);
myBalance = data.getInt("BALANCE", -1);
balanceShow.setText("Balance: " + myBalance + "Coin");
Toast.makeText(this, "Loaded!", Toast.LENGTH_SHORT).show();
}

Try this
private void saveCoins(Context context, String coin) {
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context);
SharedPreferences.Editor spe = sp.edit();
spe.putString(context.getString(R.string.pref_coin), coin);
spe.apply();
}
to retrieve the coins
private String getPaymentSelected(Context c) {
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(c);
return sp.getString(c.getString(R.string.pref_coin), "0");
}
create a string variable pref_coin in strings.xml (inside values folder)

Related

Shared Preferences Not working over multiple contexts

Put into shared preferences code:
PreferenceManager.getDefaultSharedPreferences(Bookmarks.this).edit()
.putString("togoto", link).apply();
String togoto = PreferenceManager.getDefaultSharedPreferences(Bookmarks.this)
.getString("togoto", "no");
Toast.makeText(Bookmarks.this, "Will go to "+togoto, Toast.LENGTH_SHORT).show();
setContentView(R.layout.activity_proxy_browser);
Intent myIntent = new Intent(Bookmarks.this, ProxyBrowserActivity.class);
startActivity(myIntent);
Get from shared prferences (In other context):
String togoto = PreferenceManager.getDefaultSharedPreferences(ProxyBrowserActivity.this).getString("togoto", "nogo");
Toast.makeText(ProxyBrowserActivity.this, "1 Going to "+togoto, Toast.LENGTH_SHORT).show();
if (togoto != "no") {
Toast.makeText(ProxyBrowserActivity.this, "Going to "+togoto, Toast.LENGTH_SHORT).show();
PreferenceManager.getDefaultSharedPreferences(ProxyBrowserActivity.this)
.edit().putString("togoto", "no").apply();
} else {
// no shared preferences
}
This does not appear to work and togoto returns no on the other context. How do I allow it to work over multiple contexts?
Please use
getSharedPreferences(KEY, MODE_PRIVATE) rather than
PreferenceManager.getDefaultSharedPreferenceManager.
Your code is fine when you replace this.
If u create a default SharedPreference, it' name is context.getPackageName() + "_preferences". And getDefaultSharedPreferences get that. When u set a name like "MyApp_preferences", getDefaultSharedPreferences will find nothing. Use getSharedPreferences.

How to pass an integer from one activity to another in android application [duplicate]

This question already has answers here:
How do I pass data between Activities in Android application?
(53 answers)
Closed 2 years ago.
I am trying to learn android and i don't know how to pass data from one activity to another
public void onNextClick(View view){
Intent intent = new Intent(this,Expenses.class);
intent.putExtra(EXTRA_SUM, sum);
startActivity(intent);
editSalary = (EditText) findViewById(R.id.salayText);
editIncome = (EditText) findViewById(R.id.incomeText);
salary = Integer.parseInt(editSalary.getText().toString());
income = Integer.parseInt(editIncome.getText().toString());
sum = salary + income;
}
public void onNextClick2(View view){
Intent intent2 = new Intent(Expenses.this,Budget.class);
intent2.putExtra(EXTRA_EXPENSE, expense);
startActivity(intent2);
editRent = (EditText) findViewById(R.id.rentText);
editBills = (EditText) findViewById(R.id.billsText);
editEveryday = (EditText) findViewById(R.id.everydayText);
editOther = (EditText) findViewById(R.id.otherText);
rent = Integer.parseInt(editRent.getText().toString());
bills = Integer.parseInt(editRent.getText().toString());
everyday = Integer.parseInt(editEveryday.getText().toString());
other = Integer.parseInt(editOther.getText().toString());
expense = rent + bills + everyday + other;
}
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_budget);
Intent intent = getIntent();
summary = intent.getIntExtra(MainActivity.EXTRA_SUM ,0);
expenses = intent.getIntExtra(Expenses.EXTRA_EXPENSE, 0);
totalBudget = summary - expenses;
textBudget = (TextView) findViewById(R.id.budgetView);
textBudget.setText(String.valueOf(totalBudget));
}
I am trying to get "sum" from activity 1 and "expenses" from activity 2 and subtract them in activity 3 but i keep getting null
You can't pass a value from first activity to third activity directly.First you have to pass it to first-> second then second-> third.
Else there is a simple solution like you can store it on Shared Preferences
Store sum value on shared preferences while moving from first activity to second activity.Then store the expenses value on shared preferences when you move from second to third activity.After that in onCreate method of third activity you can get the both values and subtract.
There are many ways to do this.
View Model
Singleton
Pass it in the Intent that launched the new active

After Watching Rewarded Video, how to stop showing all ads in the android app for 1 day?

I am trying to implement stop showing all ads in my android app for 1 day when a user watches rewarded video. Is it possible and how? Should I use a counter with stored variables locally or something is possible through subscriptions on play console?
I think the easiest and most direct way to do this is keeping expired date in SharedPreferences :
// use this code on onRewarded function to store the datetime when user completed his AD.
SharedPreferences sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putLong("ExpiredDate", new Date().getTime());
editor.apply();
then check that if expire date is 24 hours old then continue else show the error notification.
// use this code to check before showing AD
SharedPreferences sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
long startDateValue = sharedpreferences.getLong("ExpiredDate");
long endDateValue = new Date().getTime();
long diff = startDateValue - endDateValue;
long seconds = diff / 1000;
long minutes = seconds / 60;
long hours = minutes / 60;
long days = hours / 24;
if(hours < 24){
//show error that you have completed only "+ hours +" till now, wait more to see next ad.
} else {
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.remove("ExpiredDate");
editor.apply();
// show ads now...
}
i have not tested this code but it should work..

How to know if a value in firebase has increased or decreased?

I'm developing an android app in which there is this option to Follow/Unfollow a user. Whenever someone follows him, the counter in FirebaseDatabase gets increased by 1 and when someone unfollows him, the counter gets decreased by 1.
I'm trying to notify user every time someone follows him by starting a service as soon as he leave the app and writing the code in the Service.
Here's the code in onCreate() of the Service:
firebaseDatabaseFollowers.child("***").child("***").child("followers").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
b = sharedPref2.getBoolean(SettingsActivity.KEY_PREF_NOTIF_FOLLOW, true);
Toast.makeText(getBaseContext(), "b: " + String.valueOf(b), Toast.LENGTH_SHORT).show();
if (dataSnapshot.getValue() != null) {
if (String.valueOf(b).equals("true")) {
final int m = (int) ((new Date().getTime() / 1000L) % Integer.MAX_VALUE);
Intent notificationIntent = new Intent(getBaseContext(), NotificationARBroadcastReceiver.class);
notificationIntent.putExtra(NotificationARBroadcastReceiver.NOTIFICATION, getNotificationService());
PendingIntent pendingIntent = PendingIntent.getBroadcast(getBaseContext(), m, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, 0, pendingIntent);
}
} else {
Toast.makeText(getBaseContext(), "database is null", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
The notification part is working fine. The only problem is that the notification is delivered even when someone unfollows the user and I don't want this to happen.
So, is there any way to know that if the counter in FirebaseDatabase increased or decreased so that I can notify accordingly?
Please let me know.
I would store a global variable in your app that holds the number of followers that the user currently has. When the database sends down new info, you can compare it to the number you have saved by using if new number > or < than saved number. This could be problematic, however, in case the user goes offline and comes back online after, say 1 user unfollowed and 2 others followed. In this case, the user would just get a +1 follower notification. What I might recommend is sending down the username of the user that followed, just like Instagram does. For example, "John Smith followed you!" or "James Smith unfollowed you!".

Acess a sharedpreference file from different app [duplicate]

This question already has answers here:
Android: Retrieving shared preferences of other application
(6 answers)
Closed 9 years ago.
I am triying to acess to a shared preferences file wich was created in a different applicaction. I followed some tutorials but not works. This is my case:
App1 (com.example.remoteservice)
SharedPreferences configuracion2;
configuracion2 = getSharedPreferences("telo", Context.MODE_WORLD_READABLE);
Editor editor = configuracion2.edit();
editor.putFloat("x21", Float.parseFloat(x21.getText().toString()));
editor.commit();
App2 (com.example.grafica)
Context con = createPackageContext("com.example.remoteservice", MODE_WORLD_WRITEABLE);
SharedPreferences pref = con.getSharedPreferences(
"telo",MODE_WORLD_READABLE);
ancho = pref.getFloat("x21", 0);
Log.i("smash", "ancho" + String.valueOf(ancho));
And returns 0 because not exists "telo". why??
thanks
App1 (com.example.remoteservice)
SharedPreferences configuracion2;
configuracion2 = getSharedPreferences("telo", Context.MODE_WORLD_READABLE);
Editor editor = configuracion2.edit();
editor.putFloat("x21", Float.parseFloat(x21.getText().toString()));
editor.commit();
App2 (com.example.grafica)
Context con = createPackageContext("com.example.remoteservice", Context.CONTEXT_IGNORE_SECURITY);
SharedPreferences pref = con.getSharedPreferences(
"telo",MODE_WORLD_READABLE);
ancho = pref.getFloat("x21", 0);
Log.i("smash", "ancho" + String.valueOf(ancho));
This should solve it. Also do not call the getSharedPreferences() of current context before this call.

Categories