if application re-open SharedPreferences not saving boolean - android

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.

Related

Getting audio from the folder

I have an alarm and want to give the choice to user choose the music.
I have an activity with some code, include this fragment:
Button ring_button = (Button) findViewById(R.id.button2);
ring_button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent_for_ring_button = new Intent();
intent_for_ring_button.setAction(Intent.ACTION_GET_CONTENT);
File file = new File(REPORTS_DIRECTORY);
intent_for_ring_button.setDataAndType(Uri.fromFile(file),"audio/*");
startActivityForResult(Intent.createChooser(intent_for_ring_button,"Open folder"), 0);
}
});
and one more activity with alarm that extends BroadcastReceiver, where i`m starting next activity with dialog window with some music.
Here is it:
public class Dialog_window extends ActionBarActivity{
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.dialog_window_bckg);
getSupportActionBar().hide();
this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
final MediaPlayer Alarm_mp3 = MediaPlayer.create(Dialog_window.this, R.raw.data_don_t_sing);
Alarm_mp3.start();
Alarm_mp3.setLooping(true);
AlertDialog.Builder builder = new AlertDialog.Builder(Dialog_window.this);
builder.setTitle("Важное сообщение!")
.setMessage("Вставай!")
.setIcon(R.drawable.uncle_sam)
.setCancelable(false)
.setNegativeButton("ОК, встаю, встаю.",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
Alarm_mp3.stop();
System.exit(0);
}
});
AlertDialog alert = builder.create();
alert.show();
}
}
How i can realize this? I must get some extras from the first activity or smth else?
After you called startActivityForResult with ACTION_GET_CONTENT intent, you should overwrite onActivityResult in the same class, and get the chosen file's path. After you have the path, you can save to shared preferences, and easily retrieve from another activity (ex. in your Dialog_window) and play with MediaPlayer.
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(requestCode == 0){ // you've set to 0 at startActivityForResult
if(resultCode==RESULT_OK){
String filePath = data.getData().getPath();
// save filePath to shared preferences
}
}
}
After you retrieved inside another activity, just simply play it.
String savedPath = ..... ; // retrieve from shared preferences
//check your saved path, it could be a full path already..
//if it is, you don't need to concatenate anything to it
String fullPath = Environment.getExternalStorageDirectory()+savedPath;
mediaPlayer = new MediaPlayer();
mediaPlayer.setDataSource(fullPath);
mediaPlayer.prepare();
mediaPlayer.start()
Saving file path to shared preferences:
SharedPreferences.Editor editor = getSharedPreferences("mypref", MODE_PRIVATE).edit();
editor.putString("audioFilePath", filePath);
editor.commit();
Restoring file path from shared preferences:
SharedPreferences prefs = getSharedPreferences("mypref", MODE_PRIVATE);
String restoredFilePath = prefs.getString("audioFilePath", null);
if (restoredFilePath != null) {
// here you have the restored file path
}

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

Remember click in Android

I have created an activity that should be displayed only once. In this Activity, I added a button, and click its close and will not reopen anymore when the application is started again. I thought of using SharedPreferences, but I do not get the desired result.
I memorize a data in Shared:
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.button1:
SharedPreferences userDetails = getSharedPreferences("entrato", MODE_PRIVATE);
Editor edit = userDetails.edit();
edit.clear();
edit.putString( "entrato", "entra" );
edit.commit();
this.finish();
break;
}
}
then, in OnCreate() of the previous activity call the Shared and if the data is present do not open the activity:
//remember click
SharedPreferences userDetails = getSharedPreferences("entrato", MODE_PRIVATE);
String valore = userDetails.getString("entrato", "");
if (valore.equals("entra")){
return;
}else{
Intent intent = null;
intent = new Intent(this, Benvenuto.class);
startActivity(intent);
create share preference class like this:
public class MyPreference {
private static final String APP_SHARED_PREFS = "myPref";
private SharedPreferences appSharedPrefs;
private Editor prefsEditor;
public MyPreference(Context context) {
this.appSharedPrefs = context.getSharedPreferences(APP_SHARED_PREFS, Activity.MODE_PRIVATE);
this.prefsEditor = appSharedPrefs.edit();
}
public boolean loadServices(String servicName) {
return appSharedPrefs.getBoolean(servicName, false);
}
public void saveServices(String servicName, boolean isActivated) {
prefsEditor.putBoolean(servicName, isActivated);
prefsEditor.commit();
}
}
then On Oncreate activity check if service exist so wont show and exit.
public static MyPreference myPref = new MyPreference(this);
if(myPref.loadService("this is not first time")){
thisActivity.finish();
}else {
// so it's first time and you can do what ever you want to do
}
and go on you click events and save service like this.
public static MyPreference myPref = new MyPreference(this);
myPref.saveService("this is not first time");
Try this code instead
// save string
static public boolean setPreference(Context c, String value, String key) {
SharedPreferences settings = c.getSharedPreferences(PREFS_NAME, 0);
settings = c.getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putString(key, value);
return editor.commit();
}
// retrieve String
static public String getPreference(Context c, String key) {
SharedPreferences settings = c.getSharedPreferences(PREFS_NAME, 0);
settings = c.getSharedPreferences(PREFS_NAME, 0);
String value = settings.getString(key, "");
return value;
}
I have Four activities
Splash
Have 2 Buttons And 1 CheckBox ( Remember Me)
3 & 4. Another Activity
If I check the remember me option using checkbox, then I have to remember the button I have clicked and then start the 3rd or 4th activity directly whenever next start.

android getsharedPreferences not sure how to show hide other activities

I decided to use sharedPreferences so I could store the value of a togglebutton on my activity Preferences. On my main activity I want to hide a twitter button when the user clicks the twitter button in the Preferences activity.
private SharedPreferences prefs;
private String prefName = "MyPref";
private ToggleButton timer, twitter;
// this is the key used to set the timer to visible or hidden
private static final String TIMER_KEY = "timekey";
private static final String TWITTER_KEY= "tweet";
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.preferences);
timer = (ToggleButton)findViewById(R.id.timer_pref);
twitter =(ToggleButton)findViewById(R.id.twitter_pref);
timer.setChecked(true);
twitter.setChecked(true);
// Toast.makeText(Preferences.this, timer, Toast.LENGTH_SHORT).show();
Button b = (Button) findViewById(R.id.home_btn);
b.setOnClickListener(new View.OnClickListener()
{
// now add the new screen
public void onClick(View arg0) {
// TODO Auto-generated method stub
// get the shared perference data
Intent i = new Intent(Preferences.this, AndroidGUIActivity.class);
startActivity(i);
}
});
twitter.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
prefs = getSharedPreferences("MyPref", 0 );
SharedPreferences.Editor editor = prefs.edit();
if (timer.isChecked() == true)
{
editor.putBoolean("twitterButtonStatus", true);
}
else if(timer.isChecked() == false)
{
editor.putBoolean("twitterButtonStatus", false);
}
// now save the value that is passed to the editor.putBoolean function
// the twitter data hase been saved
editor.commit();
// now store the variable so that it can be copied to another activity
Bundle b = new Bundle();
}
});
There is no need to transfer Preferences through activities using intent.
You can access your "shared"Preferences from any activity.
You just put the button status with a string key inside:
SharedPreferences settings = getSharedPreferences("MyPrefs", 0);
SharedPreferences.Editor editor = settings.edit();
editor.putBoolean("twitterButtonStatus", buttonStatus);
And in another activity you retrieve these preferences using string key ("twitterButtonStatus"):
SharedPreferences settings = getSharedPreferences("MyPrefs", 0);
boolean buttonStatus = settings.getBoolean("twitterButtonStatus", false); // second param is default!
See: http://developer.android.com/guide/topics/data/data-storage.html
Edit:
Youre saving SharedPrefs now, to get them back and set your Button Gone do something like this:
SharedPreferences settings = getSharedPreferences(prefName, 0);
boolean buttonStatus = settings.getBoolean(TWITTER_KEY, true); //2nd is default
if(buttonstatus==false) twitter.setVisibility(View.GONE);

Activity that is only launched once after a new install?

I want my app to have an activity that shows instruction on how to use the app. However, this "instruction" screen shall only be showed once after an install, how do you do this?
You can test wether a special flag (let's call it firstRun) is set in your application SharedPreferences. If not, it's the first run, so show your activity/popup/whatever with the instructions and then set the firstRun in the preference.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
SharedPreferences settings = getSharedPreferences("prefs", 0);
boolean firstRun = settings.getBoolean("firstRun", true);
if ( firstRun )
{
// here run your first-time instructions, for example :
startActivityForResult(
new Intent(context, InstructionsActivity.class),
INSTRUCTIONS_CODE);
}
}
// when your InstructionsActivity ends, do not forget to set the firstRun boolean
protected void onActivityResult(int requestCode, int resultCode,
Intent data) {
if (requestCode == INSTRUCTIONS_CODE) {
SharedPreferences settings = getSharedPreferences("prefs", 0);
SharedPreferences.Editor editor = settings.edit();
editor.putBoolean("firstRun", false);
editor.commit();
}
}
yes, you can fix this problem with SharedPreferences
SharedPreferences pref;
SharedPreferences.Editor editor;
pref = getSharedPreferences("firstrun", MODE_PRIVATE);
editor = pref.edit();
editor.putString("chkRegi","true");
editor.commit();
Then check String chkRegi ture or false

Categories

Resources