Acess a sharedpreference file from different app [duplicate] - java

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.

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.

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..

iOS UserDefaults Sharing Preferences Across Multiple Applications Android Equivalent

For our iOS application, we have the ability for the user to enter in simple key-value preferences that should persist in 6 other applications within the same app group. This means the user will not need to re-enter those preferences 6 more times each time they open the other applications. We do this simply by calling UserDefaults(suiteName:) which returns a dictionary that is collectively readable/writable in all 7 iOS applications, which is quite convenient and useful. Is there an Android java equivalent of this? We don't want all of our Android users being forced to enter in the same information 7 times. I have tried creating a file that would be world readable/writable but cannot seem to find an appropriate directory that can be accessed by all 7 applications.
I had to write a hack to achieve this functionality, which was not preferred, but the requirement was necessary. I followed some of the accepted answer in this thread as suggested by Morrison Chang, but ended up having to loop through and compare to see which preference file was updated most recently and then make the updates to the app running the code, accordingly.
public static SharedPreferences getSharedPreferences(Activity activity) {
SharedPreferences prefs = activity.getApplicationContext().getSharedPreferences(SHARED_PREFS_KEY,
Context.MODE_PRIVATE);
long lastUpdate = prefs.getLong("lastUpdate", 0);
Context packageContext;
for (String app : new String[] { "app1", "app2", "app3", "app4", "app5", "app6" }) {
try {
packageContext = activity.createPackageContext(SHARED_PREFS_KEY + "." + app, 0);
SharedPreferences sharedPrefs = packageContext.getSharedPreferences(SHARED_PREFS_KEY, Context.MODE_PRIVATE);
long sharedLastUpdate = sharedPrefs.getLong("lastUpdate", 0);
if (sharedPrefs != null && sharedLastUpdate > lastUpdate) {
SharedPreferences.Editor editor = prefs.edit();
editor.clear();
for (Map.Entry<String, ?> entry : sharedPrefs.getAll().entrySet()) {
if (entry.getValue() instanceof Boolean)
editor.putBoolean(entry.getKey(), (Boolean) entry.getValue());
else if (entry.getValue() instanceof Float)
editor.putFloat(entry.getKey(), (Float) entry.getValue());
else if (entry.getValue() instanceof Integer)
editor.putInt(entry.getKey(), (Integer) entry.getValue());
else if (entry.getValue() instanceof Long)
editor.putLong(entry.getKey(), (Long) entry.getValue());
else if (entry.getValue() instanceof String)
editor.putString(entry.getKey(), (String) entry.getValue());
}
editor.commit();
break;
}
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
}
}
return prefs;
}

Can't make the app save variables when it exits

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)

Error when trying to get a bundle from another activity [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 5 years ago.
I'm trying to retrieve a bundle from another activity but when I try this, the following error appears in my logs: java.lang.NullPointerException: Attempt to invoke virtual method 'int android.os.Bundle.getInt(java.lang.String)' on a null object reference
The part of the code where I try to retrieve and show the bundle is this:
Bundle bundlefrankrijk = getIntent().getExtras();
int scorefrankrijk = bundlefrankrijk.getInt("finalScoreFrankrijk");
TextView highscoreLabelfranrkijk = (TextView) findViewById(R.id.highscorefrankrijk);
SharedPreferences settingsfrankrijk = getSharedPreferences("GAME_DATA", Context.MODE_PRIVATE);
int highScorefrankrijk = settingsfrankrijk.getInt("HIGH_SCORE", 0);
if (scorefrankrijk > highScorefrankrijk) {
highscoreLabelfranrkijk.setText("High Score : " + scorefrankrijk);
SharedPreferences.Editor editor = settingsfrankrijk.edit();
editor.putInt("HIGH_SCORE", scorefrankrijk);
editor.commit();
} else {
highscoreLabelfranrkijk.setText("High Score : " + highScorefrankrijk);
}
This is how I'm sending the intent to the current activity:
Intent i = new Intent(QuizActivityFrankrijk.this,
QuizResultaatFrankrijk.class);
Bundle bundlefrankrijk = new Bundle(0);
bundlefrankrijk.putInt("finalScoreFrankrijk", mScoreFrankrijk);
i.putExtras(bundlefrankrijk);
QuizActivityFrankrijk.this.finish();
startActivity(i);
Thanks in advance!
Better if you could post the code to see how you are sending the intent with extras to current activity too, for what I´m seeing here, the error is in this line:
Bundle bundlefrankrijk = getIntent().getExtras(); // is returning null object
And when youre trying to:
int scorefrankrijk = bundlefrankrijk.getInt("finalScoreFrankrijk"); // NullPointerException throwed
Cause your bundle is null from beginning, you should check if you´re sending correctly the intent with extras, please use the method:
mIntent.putExtra("key", intValue)
and check that youre receiving it like this:
if (getIntent().getExtras() != null){
getIntent().getExtras().getInt("key");}
or just like this too:
if (getIntent().getExtras() != null){
getIntent().getExtras().get("key");}
Remember, if the key is just different in some character, it will return NULL.
Please read this for more info: https://developer.android.com/reference/android/content/Intent.html

Categories