**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.
Related
I have a variable who contains data that can change when user is using app.
My goal is to store those data in SharedPrefs just before user is closing app,
I was thinking about something like
OnStop() {
Preferences.edit()... }
but i don't know the correct syntax ...
thanks in advance guys
Save your data in SavedPrefs in onStop Method.
Syntex will be like
In onStop Method
#Override
protected void onStop() {
super.onStop();
SharedPreferences saved_values = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
SharedPreferences.Editor editor = saved_values.edit();
edit.putString("key", "stringToBeSaved")
editor.commit();
}
And then to retrive your data in onCreate method
#Override
protected void onCreate(Bundle savedInstanceState) {
SharedPreferences saved_values = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
String foo = saved_values.getString("key", "default_string");
}
Remember the key should be same.
For more info check out Android docs on
Shared Preferences: Save key-value data
Android Lifecycle: Understand the Activity Lifecycle
Activity.onStop() is called just before the app is completely closed (kicked from recents)
You should probably use Activity.onPause() to save your preferences as it will also be called when the user just switches to another app.
Further information:
https://developer.android.com/guide/components/activities/activity-lifecycle
You should save your persistent data in onPause() rather than in onStop().
Then you can retrieve your data in onResume().
For saving the data you can take a look at this example
SharedPreferences.Editor editor = getSharedPreferences("myPrefs", MODE_PRIVATE).edit();
editor.putString("username", "My name");
editor.apply();
And then retrience your data like this
SharedPreferences prefs = getSharedPreferences("myPrefs", MODE_PRIVATE);
String username = prefs.getString("username", "No username"); //No username is the default value
I was wondering if anyone could tell me how I could check a checkBox in an activity from another activity.
I'm making a homework app and I want to put a check next to the questions that have been completed.
So the first activity has a list of questions and next to them are unchecked boxes. When you click a question, the app takes you to the second activity. In the second activity, I want to check the box of the question that was completed.
You should use SharedPreferences for that. call this in the first activity:
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
prefs.putBoolean("KEY", <your value>).apply();
and something similar in another activity:
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
boolean isTicked = prefs.getBoolean("KEY", <default boolean value>);
where KEY can be anything, for example, your question's number
You should use intent and bundle logic for passing data between activities.(in most cases)
In the first activity, whenever you are creating the second activity, you pass your data.
Intent intent = new Intent(FirstActivity.this,SecondActivity.class);
intent.putExtra("checked",checkBox.isChecked());
startActivity(intent);
In the second activity you receive your data by using :
Intent receivedIntent = getIntent();
boolean finalChecked = receivedIntent.getExtras().getBoolean("checked");
//now you can apply your logic with finalChecked variable
You can save checked check question to a bundle and pass it as extra to your second activity through intent and read it from that intent inside your second activity
In your first activity do something like this
public class FirstActivity extends Activity {
public static final String EXTRA_CHECKED_QUESTION = "Checked Question";
// other codes here
private void startSecondActivity() {
String checkedQuestion = getCheckedQuestion(); // a method to get checked question
Intent intent = new Intent(this, SecondActivity.class);
intent.putExtra(FirstActivity.EXTRA_CHECKED_QUESTION, checkedQuestion);
startActivity(intent);
}
}
then in your second activity
public class SecondActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstance) {
// other codes
String checkedQuestion = getIntent().getStringExtra(FirstActivity.EXTRA_CHECKED_QUESTION);
// do whatever you want with checkQuestion
}
}
Please note that the string which you pass as first parameter to putExtra() method in FirstActivity, should be same as the string you are using with getStringExtra() to retrieve your extra in SecondActivity, otherwise you can not retrieve your passed extra in SecondActivity.
Also, I did not write these codes inside idea, so there might be syntax error
Read more about intent here
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.
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.
So I am trying to use SharedPreferences to pass a value from the Activity to a Class. The problem is the following:
On initial loading of the Activity, the value is stored in SharedPreferences but if I exit the Activity and return back, and try to update the value, the SharedPreferences does not seem to update and stays at the value of the initial load of the Activity.
Some class function
private void populatePlayerQueue(){
int category_index;
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this.getContext());
category_index = sharedPreferences.getInt("selected_category", 0);
}
Activity onResume
#Override
public void onResume() {
super.onResume();
int tmp = Integer.parseInt(getIntent().getStringExtra("CategoryIndex"));
//store the category in the shared preferences
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putInt("selected_category", tmp);
editor.commit();
}
What I am trying to do:
I have to send an integer from the activity to a specific class and if I come back to the activity then I need to store the update value and so the class will be able to access the newly updated value again. I only have access to the context and not the activity. This causes errors if I try to create an interface callback to communicate with the activity. So this option is eliminated, hence I am trying anything I can to do that.
For some better result remove the SharedPreference through its key at the time of exit application.
In your case when you exit your application just clear the SharedPreference like:
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.remove("selected_category"); //Just remove it by its specific key
editor.commit();
Then it will clearly load and save the new value again when you go back to your application on the same key or you can use new one.