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;
}
}
Related
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);
}
}
I am trying to get a saved value from an activity by this Settings.getMode(); Here is the Settings class :
public class Set extends AppCompatActivity implements CompoundButton.OnCheckedChangeListener {
private static String isNightMode;
Switch aSwitch;
Boolean mode;
#Override
protected void onCreate(Bundle savedInstanceState) {
SharedPreferences sharedPreferences = getSharedPreferences("xyz", MODE_PRIVATE);
isNightMode = sharedPreferences.getString("isNightMode", "no");
mode = sharedPreferences.getBoolean("mode", false);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_set);
aSwitch = (Switch) findViewById(R.id.switch1);
aSwitch.setChecked(mode);
if (aSwitch.isChecked()) {
isNightMode = "yes";
} else {
isNightMode = "no";
}
aSwitch.setOnCheckedChangeListener(this);
}
public static String getMode() {
return isNightMode;
}
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
isNightMode = "yes";
mode = true;
SharedPreferences.Editor editor = getSharedPreferences("xyz", MODE_PRIVATE).edit();
editor.putString("isNightMode", isNightMode);
editor.putBoolean("mode", mode);
editor.commit();
Intent intent = new Intent(this, MainActivity.class);
startActivity(intent);
} else {
isNightMode = "no";
mode = false;
SharedPreferences.Editor editor = getSharedPreferences("xyz", MODE_PRIVATE).edit();
editor.putString("isNightMode", isNightMode);
editor.putBoolean("mode", mode);
editor.commit();
Intent intent = new Intent(this, MainActivity.class);
startActivity(intent);
}
}
}
When I change the value in Settings activity , the value is saved perfectly. But problem is , I am not getting the saved value when the app starts . When the app starts, the getMode() method returns null. There must be something wrong while getting saved value at the time of starting the app. I can't figure out the wrong.
1.you can use it MyApplication .
2.and call MyApplication.getMode(); in your Activity .
Try this .
public class MyApplication extends Application {
private static String isNightMode;
Boolean mode;
#Override
public void onCreate() {
super.onCreate();
SharedPreferences sharedPreferences = getSharedPreferences("xyz", MODE_PRIVATE);
isNightMode = sharedPreferences.getString("isNightMode", "no");
mode = sharedPreferences.getBoolean("mode", false);
}
public static String getMode() {
return isNightMode;
}
}
And add in the manifest
<application
android:name=".yourPackage.MyApplication"
... />
This modification might help you. Modification in onCreate() method:
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this); // this - Activity
and
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(this).edit(); // this - Activity
if (isChecked) {
isNightMode = "yes";
mode = true;
} else {
isNightMode = "no";
mode = false;
}
editor.putString("isNightMode", isNightMode);
editor.putBoolean("mode", mode);
editor.apply();
Intent intent = new Intent(this, MainActivity.class);
startActivity(intent);
}
i'm working with a RecyclerView wich has a Switch that lets the user organize the list from A to Z when the switch is on, and from Z to A when it is off, in order to implement the OnClick method i need to now the position of each element, but the element could be in two different positions (depending on the sorting chosen by the user) so in order to know where the element is, i need to know the status of the Switch from the class that implements the OnClick method.
This is my Switch-sorting implementation :
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if(isChecked){
switchStatus.setText("Sorting alphabetically");
Collections.sort(categories, new Comparator<Categories>() {
#Override
public int compare(Categories lhs, Categories rhs) {
return lhs.title.compareTo(rhs.title);
}
});
ca.notifyDataSetChanged();
}else{
switchStatus.setText("Sorting by popularity");
Collections.sort(categories, new Comparator<Categories>() {
#Override
public int compare(Categories rhs, Categories lhs) {
return lhs.title.compareTo(rhs.title);
}
});
ca.notifyDataSetChanged();
}
}
});
//check the current state before we display the screen
if(categoriesSortingSwitch.isChecked()){
switchStatus.setText("Sorting alphabetically");
Collections.sort(categories, new Comparator<Categories>() {
#Override
public int compare(Categories lhs, Categories rhs) {
return lhs.title.compareTo(rhs.title);
}
});
}
else {
switchStatus.setText("Sorting by popularity");
Collections.sort(categories, new Comparator<Categories>() {
#Override
public int compare(Categories rhs, Categories lhs) {
return lhs.title.compareTo(rhs.title);
}
});
}
}
//I CREATED THIS METHOD THINKING IN USING IT IN THE OTHER CLASS TO GET THE STATUS
public boolean getSwitchstatus(){
if(categoriesSortingSwitch.isChecked()){
return true;
}
else return false;
}
And this is the method of the other class where i need to get the status :
#Override
public void onClick(View v) {
final Intent intent;
int position = getAdapterPosition();
if (position==0){
if(/** find a way to see if it is on or off and if it is on do this**/){
intent = new Intent(context, nose.class);
context.startActivity(intent);
}
else/** if it is off**/{
}
}
}
In resume, i need to find a way to get the status of the switch so i can tell the position of the element.
Thanks very much.
Thanks to MkiiSoft advice this is what i did and works perfectly :
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if(isChecked){
switchStatus.setText("Sorting alphabetically");
Collections.sort(categories, new Comparator<Categories>() {
#Override
public int compare(Categories lhs, Categories rhs) {
return lhs.title.compareTo(rhs.title);
}
});
ca.notifyDataSetChanged();
//JUST ADDED THIS SHARED PREFERENCE WITH THE STRINGS ("it's","on") WHEN THE SWITCH IS ON
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
SharedPreferences.Editor editor = preferences.edit();
editor.putString("it's","on");
editor.apply();
}else{
switchStatus.setText("Sorting by popularity");
Collections.sort(categories, new Comparator<Categories>() {
#Override
public int compare(Categories rhs, Categories lhs) {
return lhs.title.compareTo(rhs.title);
}
});
ca.notifyDataSetChanged();
//JUST ADDED THIS SHARED PREFERENCE WITH THE STRINGS ("it's","off") WHEN THE SWITCH IS OFF
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
SharedPreferences.Editor editor = preferences.edit();
editor.putString("it's", "off");
editor.apply();
}
}
});
Then in Class where i needed to now the status of the switch i simply compared the strings and based on the matching or missmatching of the strings oppened a different Activity, this way :
public void onClick(View v) {
final Intent intent;
int position = getAdapterPosition();
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
String onoff = preferences.getString("it's", "");
//IF IT IS ON DO THIS
if(onoff.equalsIgnoreCase("on"))
{
if (position==0){
intent = new Intent(context, nose.class);
context.startActivity(intent);
}
//IF IT IS OFF DO THIS
} else if (onoff.equalsIgnoreCase("off")){
if (position==0){
intent = new Intent(context, nose2.class);
context.startActivity(intent);
}
}
}
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);
I have an android application similar to wheel of fortune where users have the option to purchase one consumable, $1000, and two entitlements, where they unlock two images as wheel styles. I am using the Amazon In-App Purchasing API. The user should be able to purchase as many consumables as they want but once they purchase the entitlements the unlocked image should be the only image that they see and they should no longer see the locked image. These in-app purchases work fine the first instance I initiate these purchases.
However, the consumable field will only update once and even though I can still go through the process of completing purchases for the consumable, the text view containing the score, or money, does not update other then that first initial purchase. Also the wheels return to the locked image rather then remaining as the unlocked image despite the fact that when I initiate the purchase for these entitlements I am told that I already own these items. Therefore I believe it may be something to do with my SharedPreferences. In short my purchases update my views once and then never again, however the backend code i.e the responses I receive from the Amazon client when completing purchases are correct. Can anyone see where I have made a mistake? Why does the textView containing the score update on the 1st purchase and never again from then on? Also how do I save the changes toe the wheel style so that when it reopens they no longer have the option to purchase the wheel? I have three classes and have included the code below. All and any help is greatly appreciated.
Game Class
public class Game extends Activity {
private ImageView wheel;
private int rand;
private int[] amounts = {100,650,-1,650,300,-1,800,250,-1,500};
private int score = 0;
private TextView scoreText;
private AnimatorSet set;
protected boolean animationDone = true;
private SharedPreferences prefs;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_game);
prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
prefs.registerOnSharedPreferenceChangeListener(prefsChanged);
wheel = (ImageView) findViewById(R.id.imageView1);
scoreText = (TextView) findViewById(R.id.score);
score = prefs.getInt("score", 0);
scoreText.setText("$" + String.valueOf(score));
}
private OnSharedPreferenceChangeListener prefsChanged = new OnSharedPreferenceChangeListener() {
#Override
public void onSharedPreferenceChanged(SharedPreferences prefs,
String key) {
if(key.equals("money") && prefs.getBoolean(key, false)) {
score += 1000;
scoreText.setText("$" + String.valueOf(score));
prefs.edit().putBoolean("money", false);
}
}
};
#Override
protected void onStart() {
super.onStart();
InAppObserver obs = new InAppObserver(this);
PurchasingManager.registerObserver(obs);
}
#Override
protected void onPause() {
if(this.isFinishing())
{
prefs.edit().putInt("score", score).commit();
}
super.onPause();
}
#Override
protected void onStop() {
prefs.edit().putInt("score", score).commit();
super.onStop();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(resultCode != RESULT_CANCELED) {
String style = data.getStringExtra("wheel");
if(style.equals("camo"))
wheel.setImageResource(R.drawable.camowheel);
if(style.equals("gold"))
wheel.setImageResource(R.drawable.goldwheel);
if(style.equals("normal"))
wheel.setImageResource(R.drawable.wheel);
}
}
public void spinTheWheel(View v) {
if(animationDone) {
wheel.setRotation(0);
rand = (int) Math.round(2000 + Math.random()*360);
set = new AnimatorSet();
set.play(ObjectAnimator.ofFloat(wheel, View.ROTATION, rand));
set.setDuration(2000);
set.setInterpolator(new DecelerateInterpolator());
set.start();
animationDone = false;
set.addListener(new AnimatorListenerAdapter() {
#Override
public void onAnimationEnd(Animator animation) {
calculateResult();
animationDone = true;
}
});
}
}
private void calculateResult() {
int angle = (int) wheel.getRotation();
angle %= 360;
angle = (int) Math.floor(angle/36);
if(amounts[angle] == -1) {
Intent intent = new Intent(this, GameOver.class);
intent.putExtra("score", score);
prefs.edit().putInt("score", 0).commit();
score = 0;
startActivity(intent);
}
else {
score += amounts[angle];
scoreText.setText("$"+String.valueOf(score));
prefs.edit().putInt("score", 0).commit();
}
}
public void upgradeWheel(View v) {
Intent intent = new Intent(getApplicationContext(), ChangeWheel.class);
startActivityForResult(intent, 1);
}
public void endGame(View v) {
Intent intent = new Intent(getApplicationContext(), GameOver.class);
intent.putExtra("score", score);
prefs.edit().putInt("score", 0).commit();
score = 0;
startActivity(intent);
}
public void addMoney(View v) {
PurchasingManager.initiatePurchaseRequest("money");
}
}
ChangeWheel Class
public class ChangeWheel extends Activity {
private Button buyCamoButton;
private Button buyGoldButton;
private ImageButton goldButton;
private ImageButton camoButton;
private SharedPreferences prefs;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_change_wheel);
prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
prefs.registerOnSharedPreferenceChangeListener(prefsChanged);
buyCamoButton = (Button) findViewById(R.id.buyCamo);
buyGoldButton = (Button) findViewById(R.id.buyGold);
goldButton = (ImageButton) findViewById(R.id.goldButton);
camoButton = (ImageButton) findViewById(R.id.camoButton);
goldButton.setEnabled(false);
camoButton.setEnabled(false);
}
private OnSharedPreferenceChangeListener prefsChanged = new OnSharedPreferenceChangeListener() {
#Override
public void onSharedPreferenceChanged(SharedPreferences prefs,
String key) {
if(key.equals("camo") && prefs.getBoolean(key, false)) {
camoButton.setImageResource(R.drawable.camowheel);
camoButton.setEnabled(true);
buyCamoButton.setVisibility(View.INVISIBLE);
}
else if(key.equals("gold") && prefs.getBoolean(key, false)) {
goldButton.setImageResource(R.drawable.goldwheel);
goldButton.setEnabled(true);
buyGoldButton.setVisibility(View.INVISIBLE);
}
}
};
#Override
protected void onStart() {
super.onStart();
InAppObserver obs = new InAppObserver(this);
PurchasingManager.registerObserver(obs);
}
public void camoClick(View v) {
Intent intent = new Intent(getApplicationContext(), Game.class);
intent.putExtra("wheel", "camo");
setResult(RESULT_OK, intent);
finish();
}
public void goldClick(View v) {
Intent intent = new Intent(getApplicationContext(), Game.class);
intent.putExtra("wheel", "gold");
setResult(RESULT_OK, intent);
finish();
}
public void normalClick(View v) {
Intent intent = new Intent(getApplicationContext(), Game.class);
intent.putExtra("wheel", "normal");
setResult(RESULT_OK, intent);
finish();
}
public void buyCamo(View v) {
String req = PurchasingManager.initiatePurchaseRequest("camo");
prefs.edit().putString(req, "camo").commit();
}
public void buyGold(View v) {
String req = PurchasingManager.initiatePurchaseRequest("gold");
prefs.edit().putString(req, "gold").commit();
}
}
InAppObserver Class
public class InAppObserver extends BasePurchasingObserver {
private SharedPreferences prefs;
public InAppObserver(Activity caller) {
super(caller);
prefs = PreferenceManager.getDefaultSharedPreferences(caller.getApplicationContext());
}
#Override
public void onSdkAvailable(boolean isSandboxMode) {
PurchasingManager.initiatePurchaseUpdatesRequest(Offset.BEGINNING);
}
#Override
public void onPurchaseUpdatesResponse(PurchaseUpdatesResponse res) {
for(String sku : res.getRevokedSkus()) {
prefs.edit().putBoolean(sku, false).commit();
}
switch (res.getPurchaseUpdatesRequestStatus()) {
case SUCCESSFUL:
for(Receipt rec : res.getReceipts()) {
prefs.edit().putBoolean(rec.getSku(), true).commit();
}
break;
case FAILED:
// do something
break;
}
}
#Override
public void onPurchaseResponse(PurchaseResponse res) {
switch(res.getPurchaseRequestStatus()) {
case SUCCESSFUL:
String sku = res.getReceipt().getSku();
prefs.edit().putBoolean(sku, true).commit();
break;
case ALREADY_ENTITLED:
String req = res.getRequestId();
prefs.edit().putBoolean(prefs.getString(req, null), true).commit();
break;
case FAILED:
// do something
break;
case INVALID_SKU:
// do something
break;
}
}
}
It could be that you are not using the same editor.
preferences.edit().putString(PreferenceKey.DISTANCE, distance);
preferences.edit().commit();
two different SharedPreferences.Editors are being returned. Hence the
value is not being committed. Instead, you have to use:
SharedPreferences.Editor spe = preferences.edit();
spe.putString(PreferenceKey.DISTANCE, distance);
spe.commit();
From... SharedPreferences not working across Activities