Access data from SharedPreferences at boot time - android

I want to start service at boot time. Its working fine.I now i want to start service only if toggle button is on.I am saving state of toggle button state in SharedPreferences.
PROBLEM
I am getting default value from SharedPreferences that is false in my case
CODE of BroadcastReceiver is as follows
public class MyReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
SharedPreferences saved_values=context.getApplicationContext().getSharedPreferences( "ServiceLockTest", Context.MODE_PRIVATE);
boolean checkstate = saved_values.getBoolean("tgpref", false); // return false
int pr=saved_values.getInt("progess", 100); //return 100
TheService.SHAKE_THRESHOLD=pr;
if(checkstate)
{
Intent myIntent = new Intent(context, TheService.class);
context.startService(myIntent);
}
else
{
Toast.makeText(context,"yoooooooooooooooooooooo" , Toast.LENGTH_LONG).show();
System.out.println(pr);
System.out.println(checkstate);
}
}
}
code of saving state of toggle button
if (isChecked) {
SharedPreferences.Editor editor = preferences.edit();
editor.putBoolean("tgpref", true); // value to store
editor.commit();
// The toggle is enabled
if (mgr.isAdminActive(cn))
{
Toast.makeText(getBaseContext(),"Service is afor",Toast.LENGTH_LONG).show();
}
else
{
Log.i("Admin", "Not an admin");//mean admin is not active
showAct();//will open new activity
}
}
Please help.thanks

Related

onclicklistener for ui change does not update on first click

I have an issue where I am trying to change the foreground of a Button upon a click event. The foreground only changes after the first click.
public void muteSoundClick(View view){
playSound = preferences.getBoolean("playSound", true);
if (playSound) {
view.setForeground(getDrawable(R.drawable.foreground_padding_unmute));
editor.putBoolean("playSound", false);
editor.apply();
}
else {
view.setForeground(getDrawable(R.drawable.foreground_padding_mute));
editor.putBoolean("playSound", true);
editor.apply();
}
}
I retrieve a variable from the android SharedPrefernces, which i use to determine which foreground to use.
First you need to check playsound at the start of the activity so that the button itself would get what you are saving the first time so you need something like this :
playSound = preferences.getBoolean("playSound", true);
if(playSound)
button.setForeground(getDrawable(R.drawable.foreground_padding_mute));
else
button.setForeground(getDrawable(R.drawable.foreground_padding_unmute));
Then you can handle the clicks using the same method you have posted in your question
here is a sample example activity to sum it up :
public class SimpleActivity extends AppCompatActivity {
SharedPreferences preferences;
SharedPreferences.Editor editor;
boolean playSound;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_simple);
preferences = PreferenceManager.getDefaultSharedPreferences(this);
editor= PreferenceManager.getDefaultSharedPreferences(this).edit();
Button button = findViewById(YourButtonID);
playSound = preferences.getBoolean("playSound", true);
if(playSound)
button.setForeground(getDrawable(R.drawable.foreground_padding_mute));
else
button.setForeground(getDrawable(R.drawable.foreground_padding_unmute));
}
public void muteSoundClick(View view){
playSound = preferences.getBoolean("playSound", true);
if (playSound) {
view.setForeground(getDrawable(R.drawable.foreground_padding_unmute));
editor.putBoolean("playSound", false);
editor.apply();
}
else {
view.setForeground(getDrawable(R.drawable.foreground_padding_mute));
editor.putBoolean("playSound", true);
editor.apply();
}
}
}
It's seems that you aren't really editing the preferences. Like this.
SharedPreferences.Editor editor;
public void muteSoundClick(View view){
playSound = preferences.getBoolean("playSound", true);
if (playSound) {
editor = sharedPreferences.edit();
view.setForeground(getDrawable(R.drawable.foreground_padding_unmute));
editor.putBoolean("playSound", false);
editor.commit();
}
else {
view.setForeground(getDrawable(R.drawable.foreground_padding_mute));
editor.putBoolean("playSound", true);
editor.apply();
}
}

if application re-open SharedPreferences not saving boolean

I have the following code in my project called menu.class
f1 =(Button)findViewById(R.id.f1);
f1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v){
// TODO Auto-generated method stub
Intent intent = new Intent ();
intent.setClassName ("com.example.aplication", "com.example.application.levelone");
startActivityForResult (intent, 0);
}
});
}
public void onActivityResult (int requestCode, int resultCode, Intent intent) {
super.onActivityResult (requestCode, resultCode, intent);
f2=(Button)findViewById(R.id.f2);
f2lock=(ImageView)findViewById(R.id.f2lock);
switch (resultCode) {
case 11: f2.setVisibility(View.VISIBLE);
f2lock.setVisibility(View.GONE);
}
SharedPreferences preferences = getSharedPreferences("preferences", MODE_PRIVATE);
boolean levelTwoUnlocked = preferences.getBoolean("f2", true);
if(levelTwoUnlocked){
f2.setVisibility(View.VISIBLE);
f2lock.setVisibility(View.GONE);
}
else {
f2.setVisibility(View.GONE);
f2lock.setVisibility(View.VISIBLE);
}
f2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v){
Intent intent = new Intent ();
intent.setClassName ("com.example.application", "com.example.application.leveltwo");
startActivityForResult (intent, 0);
}
});
}
The code is working fine. f2 button is set visible and f2lock invisible.
But when I re-open the application the f2 button back to visible.
Did my Preferences code not complete?
UPDATED
i had changed the preferences code like this
SharedPreferences preferences = getSharedPreferences("preferences", MODE_PRIVATE);
SharedPreferences.Editor ed = preferences.edit();
boolean levelTwoUnlocked = preferences.getBoolean("f2", true);
ed.commit();
and when i re-open the application it still had the same problems
You are retrieving the value of f2, but it doesn't look like you're saving it anywhere.
preferences.getBoolean("f2", true);
This will return the last saved value of f2 or true if f2 doesn't exist (i.e. you've never saved it in your SharedPreference instance) - it won't create or save any value in the SharedPreferences instance for you.
To save the value, you need to create a SharedPreferences editor, set the value (or values) you want to save and commit it:
SharedPreferences.Editor editor = preferences.edit();
editor.putBoolean("f2", levelTwoUnlocked);
editor.commit();
Now the next time you read the f2 value, it will have whatever value you last committed.

android sharedPreferences to set and retrieve boolean value

I want to save boolean values and then compare them in an if-else block. but when run my application, nothing is displayed.
my Code is here:
prefs = getApplicationContext().getSharedPreferences("MyPref", MODE_PRIVATE);
editor = prefs.edit();
boolean init = false;
if (init) {
Ion.with(this)
.load("myurl")
.asJsonArray().setCallback(new FutureCallback<JsonArray>() {
#Override
public void onCompleted(Exception arg0, JsonArray data) {
// TODO Auto-generated method stub
for (int i = 0; i < data.size(); i++) {
cat.setTitle(data.get(i).getAsJsonObject()
.get("title").getAsString());
arrayList.add(cat);
db.addCategory(cat);
adapter.notifyDataSetChanged();
}
populateScroller();
editor.putBoolean("init", true).commit();
}
});
} else {
dataSource = new CategoryDataSource(this);
dataSource.open();
arrayList = dataSource.getCategoryList();
for (Categories c : arrayList) {
c.getTitle();
}
}
So my question is why shared preferences is not working? please help me.
This is how you need to work with shared preferences.
The senerio I am about to show is to check if this particular activity is running for the first time or not.
Here is what you do in your on create method:
//SharePrefernces
SharedPreferences appIntro = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
//Check if the Application is Running for the First time
appIntro = getSharedPreferences("hasRunBefore_appIntro", 0); //load the preferences
Boolean hasRun = appIntro.getBoolean("hasRun_appIntro", false); //see if it's run before, default no
//If FirstTime
if (!hasRun) {
//code for if this is the first time the application is Running
//Display Activity
super.onCreate(savedInstanceState);
setContentView(R.layout.app_intro_activity);
//Button to send Confirmation back
Button btn_ok = (Button) findViewById(R.id.appintro_btn_ok);
btn_ok.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
//Save information that this application has run for the first time
SharedPreferences settings = getSharedPreferences("hasRunBefore_appIntro", 0);
SharedPreferences.Editor edit = settings.edit();
edit.putBoolean("hasRun_appIntro", true);
edit.commit(); //apply
Intent intent = new Intent(Application_Intro_Activity.this, MainActivity.class);
startActivity(intent);
//close Activity
finish();
}
});
}//End of if(firstTime)
else {
//code if the Application has run before
super.onCreate(savedInstanceState);
//Navigate Directly to MainActivity
Intent intent = new Intent(Application_Intro_Activity.this, MainActivity.class);
startActivity(intent);
//close Activity
finish();
}
}//End of OnCreate()
you are checking always false value of init and it does not enter into your if statement,So prefs will not updated.instead do it as
boolean init = prefs.getBoolean("init",false);
and check it as
if(!init)
i.e. change
boolean init = false;
if (init) {
to
boolean init = prefs.getBoolean("init",false);
if(!init)
You are not using SharedPreferences values in above code . You might need to do like this :
SharedPreferences prefs = getApplicationContext().getSharedPreferences("MyPref", MODE_PRIVATE);
boolean prefValue = prefs.getBoolean("init", false);
if(!prefValue)
{
// add value in SharedPreferences
Ion.with(this)
.load("myurl")
.asJsonArray().setCallback(new FutureCallback<JsonArray>() {
#Override
public void onCompleted(Exception arg0, JsonArray data) {
// TODO Auto-generated method stub
for (int i = 0; i < data.size(); i++) {
cat.setTitle(data.get(i).getAsJsonObject()
.get("title").getAsString());
arrayList.add(cat);
db.addCategory(cat);
adapter.notifyDataSetChanged();
}
populateScroller();
editor = prefs.edit();
editor.putBoolean("init", true).commit();
}
});
}
else{
dataSource = new CategoryDataSource(this);
dataSource.open();
arrayList = dataSource.getCategoryList();
for (Categories c : arrayList) {
c.getTitle();
}
}
The key is : You need to check the preference values first and accordingly code
You can also use SharedPreferences like this:
/* In your onCreate method */
SharedPreferences sp = getSharedPreferences(MyPrefs, Context.MODE_PRIVATE);
if (!sp.getBoolean("first", false)) {
SharedPreferences.Editor editor = sp.edit();
editor.putBoolean("first", true);
editor.apply();
Intent intent = new Intent(this, IntroActivity.class); // Call the one tie launch java class
startActivity(intent);
}

Load preferences in another activity?

I stored a value in my MainActivity called "tgpref".
SharedPreferences.Editor editor = preferences.edit();
editor.putBoolean("tgpref", true); //value to save
editor.commit();"
In my onCreate i have
public SharedPreferences preferences;
---
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
preferences = getPreferences(MODE_PRIVATE);
I want to display the value in my widget so i try to write in the onUpdate in widget provider class this
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
boolean tgpref = preferences.getBoolean("tgpref", false)
if (tgpref == true) {
remoteViews.setTextViewText(R.id.battery, "Risp on");
} else {
remoteViews.setTextViewText(R.id.battery, "Risp off");
}
If the toggle button in the MainActivty is clicked i want that in my widget appears "Risp on" else "Risp off". Right now displays only "Risp off" so i don't know how i can do. Any helps? Nothing happen i can't load the value
it looks good, so i guess your button doesn`t trigger the value change?!
MainActiviy
private Boolean mTgpref;
private SharedPreferences prefs;
#Override
protected void onCreate(Bundle savedInstanceState) {
//...
//get value from shared preferences and update ui
prefs = this.getSharedPreferences("com.example.app", Context.MODE_PRIVATE);
mTgpref = prefs.getBoolean("tgpref", false);
setYourText();
}
private void setYourTextAndStoreToSharedPref(){
Log.i("TEST","mTgpref -> " + mTgpref); //check value
if(mTgpref){
remoteViews.setTextViewText(R.id.battery, "Risp on");
}
else
{
remoteViews.setTextViewText(R.id.battery, "Risp off");
}
prefs.edit().putBoolean("tgpref", mTgpref).commit();
//UPDATE YOUR WIDGET HERE
}
//function called on switch button click
private void onSwitchClickButtonClick(){
mTgpref = !mTgpref; //toggle Boolean
setYourText();
}
EDIT
Sorry, I misunderstood your main problem. After updating SharedPreferences, you should follow the steps described here: http://developer.android.com/guide/topics/appwidgets/index.html#UpdatingFromTheConfiguration

Android: Saving boolean values to a database (Beginner)

I am currently developing an android game and I have an options screen which at the moment has one Option in the form of a ToggleButton: Music on, or Music off.
I currently have this boolean in place, so the class checks if the music is currently playing and then this determines if the ToggleButton is checked or not:
private boolean isMyServiceRunning(String serviceCanonicalClassName) {
ActivityManager manager = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
for (RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
if (serviceCanonicalClassName.equals(service.service.getClassName())) {
return true;
}
}
return false;
}
So now I want to be able to send the values of True or False to a SQLite database I have set up. At this current moment in time, the only way I can do this is creating a TextView which changes value whether the ToggleButton is checked or not. The value in the TextView is then sent to the database successfully, but this creates problems such as not saving the current settings selected by the user.
Thank you to anyone who replies, if you require anymore code to help you answer I will supply it asap.
I have found some of the answers to be quite confusing, so I think it would be best if I just copied all of my code to here so you can get a better understanding:
public class OptionsActivity extends Activity {
private boolean isMyServiceRunning(String serviceCanonicalClassName) {
ActivityManager manager = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
for (RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
if (serviceCanonicalClassName.equals(service.service.getClassName())) {
return true;
}
}
return false;
}
Intent i; // Handles MyMusicService.java
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.options);
final TextView tSound = (TextView) findViewById(R.id.textView2);
final TextView tJoin = (TextView) findViewById(R.id.textView3);
final Button saveBtn = (Button) findViewById(R.id.optSaveBtn);
final Button tblBtn = (Button) findViewById(R.id.tableBtn);
i=new Intent(this, MyMusicService.class);
final ToggleButton soundOption = (ToggleButton) findViewById(R.id.soundPref);
final ToggleButton joinOption = (ToggleButton) findViewById(R.id.joinPref);
boolean musicPlays = isMyServiceRunning(MyMusicService.class.getCanonicalName());
boolean joinChecking = joinOption.isChecked();
soundOption.setChecked(musicPlays);
if(musicPlays==true){
tSound.setText("On");
}
if(musicPlays==false) {
tSound.setText("Off");
}
if(joinChecking==true){
tJoin.setText("Auto");
}
if(joinChecking==false){
tJoin.setText("Manual");
}
soundOption.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Perform action on clicks to control sound being on and off.
if(soundOption.isChecked()) {
Toast.makeText(OptionsActivity.this, "Music on.", Toast.LENGTH_SHORT).show();
startService(i);
}
else {
if(stopService(i)==true){
soundOption.setChecked(false);
stopService(i);
Toast.makeText(OptionsActivity.this, "Music off.", Toast.LENGTH_SHORT).show();
}
}
}});
joinOption.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if(joinOption.isChecked()){
Toast.makeText(OptionsActivity.this, "Auto", Toast.LENGTH_SHORT).show();
}
else{
Toast.makeText(OptionsActivity.this, "Manual", Toast.LENGTH_SHORT).show();
}
}
});
tblBtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent shmoo = new Intent(OptionsActivity.this, SQLView.class);
startActivity(shmoo);
}
});
saveBtn.setOnClickListener(new View.OnClickListener(){
public void onClick(View v) {
switch (v.getId()){
case R.id.optSaveBtn: //Determine what will happen when the user presses the "Submit button".
boolean optionsWork = true;
try{
String sound = tSound.getText().toString();
String join = tJoin.getText().toString();
optionsDB entry = new optionsDB(OptionsActivity.this); //Creating a new instance of MasterMind game
entry.open();
entry.createOptionEntry(join, sound); //Passing both strings
entry.close();
}catch (Exception e){ //Creating an error message if for some reason the app cannot transfer data to the Database.
Toast.makeText(OptionsActivity.this, "Error", Toast.LENGTH_SHORT).show();
}
finally { //Creating an AlertDialog box when the user presses the Submit button.
if (optionsWork){
Toast.makeText(OptionsActivity.this, "Settings Saved", Toast.LENGTH_SHORT).show();
}
}
break;
}
}
});
}
protected void onDestroy() {
if (this.isFinishing()){
super.onDestroy();
stopService(i);
}
}
}
SQLite doesn't handle a boolean type. I always just use smallint and put either a 1 or a 0 in the field. make sure you set it to not accept nulls, and set the default value to either 1 or 0, given your usecase.
here's an example:
CREATE TABLE "db"."boolean_example" ("boolean_example_field" smallint NOT NULL DEFAULT 0);
To store preferences better idea probably will be use Shared Preferences.
And here is example:
SharedPreferences settings = getSharedPreferences("GameSettings", 0);
SharedPreferences.Editor editor = settings.edit();
editor.putBoolean("EnableMusic", mSilentMode);
editor.commit();
...
boolean isOn = settings.getBoolean("EnableMusic",true);

Categories

Resources