Set SharedPreferences to save Switch Statement Case - java

I really confused to save my Switch statement so when the game reopen button that had been VISIBLE is Save, so I do some coding with SharedPreferences like this
f1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v){
// TODO Auto-generated method stub
Intent level1 = new Intent ();
level1.setClassName ("com.example.game", "com.example.game.levelone");
startActivityForResult (level1, 0);
}
});
}
public void onActivityResult (int requestCode, int resultCode, Intent level1){
super.onActivityResult (requestCode, resultCode, level1);
f2=(Button)findViewById(R.id.f2);
f2lock=(ImageView)findViewById(R.id.f2lock);
SharedPreferences resultcode = getSharedPreferences("preferences", MODE_PRIVATE);
SharedPreferences.Editor editor = resultCode.edit();
editor.putBoolean("IsFinished", true);
editor.commit();
boolean resultcode = preferences.getBoolean("IsFinished", true);
switch (resultCode) {
case 2: f2.setVisibility(View.VISIBLE);
f2lock.setVisibility(View.GONE);
}
There is the an error on different line
First in SharedPreferences.Editor editor = resultCode.edit();
I got this error Cannot invoke edit() on the primitive type int
Second, boolean resultcode = preferences.getBoolean("IsFinished", true);
I got two error like this
preferences cannot be resolved and Duplicate local variable
Can anyone help me to fix the code or giving another solution code to save the Switch Statement?

error no:1
There is a typo in your code. Notice the C in resultCode.edit()
Replace
SharedPreferences resultcode = getSharedPreferences("preferences", MODE_PRIVATE);
SharedPreferences.Editor editor = resultCode.edit();
with
SharedPreferences resultcode = getSharedPreferences("preferences", MODE_PRIVATE);
SharedPreferences.Editor editor = resultcode.edit();
Actually, in your code, it is resultcode which is the SharedPreference, but you was calling edit() on resultCode
error:2
I think you are trying to get a boolean value that is stored in the SharedPreference. For that, what you are doing is wrong.
It should be done as follows
boolean result = resultcode.getBoolean("IsFinished", true);
Actually, it is resultcode which refers to your SharedPreference in your Java class and not preferences. preferences is just a name given to the xml file that is saved in your local device.
Please take a look in the docs for more details about SharedPreferences.

As Lal said, you have a typo. Personally, I prefer one-liner SharedPreferences with the key String as a private static String at the top of the class.
The code below is derived from one of my projects.
private static final String KEY_ISFINISHED = "prefs_isfinished";
PreferenceManager.getDefaultSharedPreferences(context)
.edit().putBoolean(KEY_ISFINISHED, myboolean).commit();
Using this code, you minimize typos. Aside from code typos, a typo in the key will make sure your preference is never saved/retrieved correctly which is why I 'advocate' for the use of the static String. You will also notice from my link that all of my preferences are managed by a single class which means I do not have to repeat code in other classes to retrieve/store a particular preference. Generally speaking, less code == less chance of errors.

Related

not able to make a button visible from another activity

I created an image gallery app.
My requirment:When I click on buttoncut in a activity(PhotosActivity.java), buttonpaste should become visible and it should remain visible when I go back to another activity(ImageGallery.java) so that I can use it for moving pictures to another folder.
What is happening: When I click on buttoncut(PhotosActivity.java), buttonpaste becomes visible but when I go back to any other activity(ImageGallery.java), it disappears.
I tried some code but its not working. How can I fix it ?
PhotosActivity.java
Intent intent = new Intent(PhotosActivity.this, ImageGallery.class);
intent.putExtra(EXTRA_IS_CORRECT, true);
startActivity(intent);
ImageGallery.java
Intent startingIntent = getIntent();
boolean isCorrect = startingIntent.getBooleanExtra(PhotosActivity.EXTRA_IS_CORRECT, false);
if(isCorrect) {
final ImageButton buttonpaste = (ImageButton) findViewById(R.id.buttonpaste);
buttonpaste.setVisibility(View.VISIBLE);
}
but when I go back to any other activity(ImageGallery.java), it disappears
Because you have a different Intent when you "go back". If you want to persist the visibility, you should probably be using SharedPreferences.
For example
ImageButton buttonpaste = (ImageButton) findViewById(R.id.buttonpaste);
SharedPreferences prefs = getSharedPreferences("prefs" Context.MODE_PRIVATE);
boolean isCorrect = getIntent().getBooleanExtra(PhotosActivity.EXTRA_IS_CORRECT, false);
SharedPreferences.Editor e = prefs.edit();
if(isCorrect || prefs.getBoolean(PhotosActivity.EXTRA_IS_CORRECT,false)) {
buttonpaste.setVisibility(View.VISIBLE);
e.putBoolean(PhotosActivity.EXTRA_IS_CORRECT, true);
e.apply();
}
In your main Activity use startActivityForResult instead of startActivity. This allows you to return a value from the new Activity to the Main Activity. For example:
In PhotosActivity
startActivityForResult(new Intent(PhotosActivity.this, ImageGallery.class), 3);
Here, number 3 is a number you define that allows you to identify the result later.
setResult(RESULT_OK); // or any result you want
The result is sent to the MainActivity, and you must override onActivityResult() to get the result.
protected void onActivityResult (int requestCode, int resultCode, Intent data)
{
if (requestCode == 3) // here you match the number you sent in startActivityForResult
if (resultcode == RESULT_OK)
// do something
}

Load SharePrefs Value into textview

So i made a game with a simple score keeping system, It seems that the highscore gets put into the shared prefs correctly, but when trying to load the high score into the activity oncreate the application crashes. this is my code.
SharedPreferences sharedPref = getPreferences(Context.MODE_PRIVATE);
int score = sharedPref.getInt("SCORE", 0);
String score2 = Integer.toString(score);
text10.setText(score2);
Not sure what i'm doing wrong so any advice will be great!
Here is my save score code
private void savePref(String key, int value) {
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor edit = sp.edit();
edit.putInt(key, value);
edit.apply();
}
From the log you have shared, it is clear that you have not get the TextView properly. Assuming that you have set the layout, do something like this:
text10 = (TextView) findViewById(R.id.your_textview_id);
SharedPreferences sharedPref = getPreferences(Context.MODE_PRIVATE);
int score = sharedPref.getInt("SCORE", 0);
String score2 = Integer.toString(score);
text10.setText(score2);
Save SharedPreferences properly, using both name and mode
SharedPreferences sharedPreferences = context.getSharedPreferences("DATA",Context.MODE_PRIVATE);
I think this is happening beacuse, the method that you're using getPreferences(PREFERENCE_MODE_PRIVATE)
returns the preferences saved by Activity's class name as described here :
Retrieve a SharedPreferences object for accessing preferences that are private to this activity. This simply calls the underlying getSharedPreferences(String, int) method by passing in this activity's class name as the preferences name.
So, when you're saving the prefs in SomeActivity it's being saved under the name "SomeActivity"
but when you're getting the prefs in this activity it's returning you the prefs saved under this activity's class name.
So, you should use getSharedPreferences (String name, int mode) method with the same name instead.
source
UPDATE
After looking at the stacktrace looks like your TextView object text10 is null, initialize it and the problem will be solved.

Using Shared preferences to save a string on a button click

So currently I have:
public void SaveText(View view) {
String saved = text.getText().toString();
// TODO
Toast.makeText(getApplicationContext(), R.string.addedfavs, Toast.LENGTH_SHORT).show();
}
How do you save the 'Text' string and save it into shared preferences, without overwriting previous saved strings.
(Note: I've tried using arrays and array lists but I just end up with one result and overwriting it rather than adding to the previously saved strings)
I'm pretty new to this so please don't skip any steps regardless of how insignificant they may seem.
SharedPreferences prefs = this.getSharedPreferences(
"com.example.app", Context.MODE_PRIVATE);
while saving
public void SaveText(View view) {
String saved = text.getText().toString();
SharedPreferences.Editor editor=prefs.edit();
editor.put("value",saved);
editor.commit();
Toast.makeText(getApplicationContext(), R.string.addedfavs, Toast.LENGTH_SHORT).show();
}
while retriving
String value=prefs.getString("value");
Read the content which is already stored in your SharedPreferences, append the new value and finally write back to SharedPreferences.

Android getPrefernces(int) is undefined

**after doing research and trying too look at stackoverflow solutions and try to applay them and failed in all, this error is still appers.
Iam trying to save data by using SharedPreferences and getPrefernces.
**how can i use it as an array for 10 cells only?(so it will save last ten values ive enterd and i could do sorting by max value)
Code:
public void onClick(View v) {
// TODO Auto-generated method stub
SharedPreferences sharedPref = this.getPrefernces(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
EditText name = (EditText)findViewById(R.id.namep);
editor.putString(name.getText().toString(), score);
editor.commit();
}
In the first line (the defind of sharedPref) ive got this error:
The method getPrefernces(int) is undefined for the type new View.OnClickListener(){}
Ive tried to switch it in few ways no ones works, i cant even call getActivity()function after this. i dont know why my code extends Activity.
Ive tried this soultions:
How to resolve an error: getSharedPreferences(String, int) is undefined for the type new View.OnClickListener(){}
The method setOnClickListener(new View.OnClickListener(){}) is undefined for the type imageButton1
Try this:
SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
or
SharedPreferences sharedPref = getPreferences(Context.MODE_PRIVATE);
this inside the OnClickListner will be pointing to that anonymous class, not the Activity. So you have to use your Activity reference over there instead.
Change
SharedPreferences sharedPref = this.getPrefernces(Context.MODE_PRIVATE);
to
SharedPreferences sharedPref = Your_Activity_Name.this.getPrefernces(Context.MODE_PRIVATE);
You do it in anonymous class OnClickListener and your "this" points to it. You need to call the method like this
OuterActivity.this.getPreferences(Context.MODE_PRIVATE);
or
OuterFragment.this.getActivity().getPreferences(Context.MODE_PRIVATE);
You have to call the method with the Context object. What is "this" in the above code? Then try #Piotr code.
You can't use
this.getPrefernces(Context.MODE_PRIVATE);
in View.onClickListener because that is not the same instance.
Instead of this you have to use something like that:
public void click(View v) {
SharedPreferences pref = PreferenceManager
.getDefaultSharedPreferences(MainActivity.this);
//Your other code
}
Point is that you have to get sharedPreferrences from activity, not from onClickListener.

Android SharedPreferences issue

I need a little help with Android Shared Preferences. I'm trying to put a boolean type in SP and make it visible from every other activity in my application.And I want to be able to change the state of boolean type to true/false from another activity so I can make some changes in the UI depending on that boolean value.
For now I'm using this piece of code,which I understand but it's not correct.
Here it is :
Activity 1:
boolean isLoggedIn = false;
SharedPreferences isLogged = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
SharedPreferences.Editor editor = isLogged.edit();
editor.putBoolean("isLoggedIn", isLoggedIn);
editor.commit();
Activity 2 :
boolean isLogged=true;
int mode = Activity.MODE_PRIVATE;
SharedPreferences mySharedPreferences;
mySharedPreferences=getSharedPreferences("isLoggedIn",mode);
mySharedPreferences.edit().putBoolean("isLoggedIn", isLogged);
boolean bool = mySharedPreferences.getBoolean("isLoggedIn",false);
Log.w("Boolean","Boolean state : "+bool);
In Activity 2 try using like this and it will work
mySharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
and remove below line
mySharedPreferences.edit().putBoolean("isLoggedIn", isLogged);
Put edit.commit(); after mySharedPreferences.edit().putBoolean("isLoggedIn", isLogged);
This will help you to get correct value.

Categories