switch button with preference activity - java

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

Related

How to count the admob ads click in android studio and stored in sharedprefernce?

Hello friend i am new in android and implement admob in my project i want to count how many time user click on my ads and stored in shareperfernce so if user click on my ads more than one my my ad will show next 4 days thats my scenario but the problem is that i dont know how to count number of click in interstitial ads and stored in sharedpefernce here is my code i make simple for your readability
#Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chapters);
JodaTimeAndroid.init(this);
sharedPreferences=getSharedPreferences("TimeStamp",MODE_PRIVATE);
final String getcickdate=sharedPreferences.getString("currentdate",null);
AppPrefrences.getUserClick(this);
interstitialAd.setAdListener(new AdListener() {
#Override
public void onAdClosed() {
super.onAdClosed();
startActivity(intent);
interstitialAd.loadAd(new AdRequest.Builder().build());
}
#Override
public void onAdLoaded() {
// Code to be executed when an ad finishes loading.
Toast.makeText(Chapters.this, "loaded", Toast.LENGTH_SHORT).show();
}
#Override
public void onAdFailedToLoad(int errorCode) {
// Code to be executed when an ad request fails.
}
#Override
public void onAdOpened() {
// Code to be executed when the ad is displayed.
}
#Override
public void onAdClicked() {
Date date=new Date();
SimpleDateFormat format=new SimpleDateFormat("dd-MM-yyyy");
String currnetdate=format.format(date);
AppPrefrences.setClickTime(context,currnetdate);
int clickCount =AppPrefrences.getUserClick(context);
clickCount = clickCount + 1;
AppPrefrences.setUserClick(context,clickCount);
editor.commit();
package bible.swordof.God.util;
import android.content.Context;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.widget.Toast;
import es.dmoral.toasty.Toasty;
public class AppPrefrences {
private static SharedPreferences mPrefs;
private static SharedPreferences.Editor mPrefsEditor;
public static int getUserClick(Context ctx) {
mPrefs = PreferenceManager.getDefaultSharedPreferences(ctx);
return mPrefs.getInt("click", 0);
}
public static void setUserClick(Context ctx, int value) {
mPrefs = PreferenceManager.getDefaultSharedPreferences(ctx);
mPrefsEditor = mPrefs.edit();
mPrefsEditor.putInt("click", value);
mPrefsEditor.commit();
}
public static String getClickTime(Context ctx) {
mPrefs = PreferenceManager.getDefaultSharedPreferences(ctx);
return mPrefs.getString("clickTime", "");
}
public static void setClickTime(Context ctx, String value) {
mPrefs = PreferenceManager.getDefaultSharedPreferences(ctx);
mPrefsEditor = mPrefs.edit();
mPrefsEditor.putString("clickTime", value);
mPrefsEditor.commit();
}
public static void clearAllPreferences(Context ctx) {
mPrefs = PreferenceManager.getDefaultSharedPreferences(ctx);
mPrefsEditor = mPrefs.edit();
mPrefsEditor.clear();
mPrefsEditor.commit();
}
}
when ever user click on ad onAdclick listner store value in sharedperfernce and increment existing value for example if user click on first on ad it will count 1 which i done but problem is that how to incremnet in pervious for example if user click on next on ad the store value in sharedperfence will change to 2

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

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.

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