I may be going about this the wrong way - applying what I know from other API's - so, if so, perhaps you can point me in a different direction. The fact is, I can't seem to find any examples for exactly what I am doing. I'm trying to call a method from the xml layout. I want to call the same method from various checkboxes, basically on a click of any checkbox, I want to store the isChecked state in the SharedPreferences file. This is my xml and java:
<CheckBox
android:layout_width="194dp"
android:layout_height="wrap_content"
android:text="#string/Chri"
android:id="#+id/chkbxChristmas"
android:checked="false"
android:onClick="savePreferencesData(#string/Chri,#+id/chkbxChristmas)"/>
public void savePreferencesData(String preference,int id) {
SharedPreferences prefs = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = prefs.edit();
CheckBox cb1 = (CheckBox) findViewById(id);
editor.putBoolean(preference, cb1.isChecked());
// Commit the edits!
editor.commit();
};
As you can see, I'm trying to pass the checkbox ID and the #string/Chri string value (I use this value as the tag in the SharedPreferences file) so the method knows which preference to update.
Is it even possible to pass the variables, and is there a better way to identify which checkbox is calling the method?
I appreciate the help!
Just a quick update: For some reason I could not get the Lister to function... here is my code:
public void saveHanuPref(View view) {
final CheckBox checkBox = ( CheckBox ) findViewById( R.id.chkbxHanukkah );
checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener()
{
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked)
{
if ( isChecked )
{
SharedPreferences prefs = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = prefs.edit();
editor.putBoolean(getString(R.string.Hanu), checkBox.isChecked());
editor.commit();
}
}
});
}
Calling this simple method from the activity xml (using onClick) did work:
public void saveChriPref(View view) {
CheckBox checkBox = ( CheckBox ) findViewById( R.id.chkbxChristmas );
SharedPreferences prefs = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = prefs.edit();
editor.putBoolean(getString(R.string.Chri), checkBox.isChecked());
editor.commit();
};
Thanks again for the help.
The right way would be to set an OnCheckedChangeListener
CheckBox checkBox = ( CheckBox ) findViewById( R.id.chkbxChristmas );
checkBox.setOnCheckedChangeListener(new OnCheckedChangeListener()
{
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked)
{
if ( isChecked )
{
// perform logic
}
}
});
The method you declare in your onClick() method of the button can take only one input type - it is the View which holds that button. No other data can be specified.
Said that, the method in onCLick should be only the name of the method, no parameters etc.
android:onClick = "savePreferencesData()"
Assuming, you are using the Activity class, this is how the method should be created.
public void savePreferencesData(View v) {
// do what you want
}
The method you declared in the xml file should be present in the same Activity class only. Said that, other buttons in other XML files cannot re-use this method.
is there a better way to identify which checkbox is calling the
method?
Try the below code sample:
YOUR_CHECKBOX_NAME.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if(YOUR_CHECKBOX_NAME.isChecked()) {
System.out.println("Checked");
} else {
System.out.println("Un-Checked");
}
}
});
Related
I have set up shared preferences to store the values of an ArrayList after a save data button is clicked within my app. This part is working fine.
The trouble I am having is that I have a recyclerview adapter which populates a recyclerview with rows. Each row contains a check box which turns the text in that row green when checked to indicate it has been completed.
My question is how can I add the checkbox state to my shared preferences and save that state so when I re-open the app the checkbox is saved.
Save button in oncreate in main activity
//Functionality for save button
final Button saveButton =findViewById(R.id.saveButtonGame);
saveButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
saveData();
}
});
Here is my code for my shared preferences in Main Activity (outside oncreate) to save arraylist. How can I implement my checkbox state into this?
//Save data when save button is clicked
private void saveData(){
SharedPreferences sharedPreferences = getSharedPreferences("shared preferences", MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
Gson gson = new Gson();
String json = gson.toJson(gameList);
editor.putString("game list", json);
editor.apply();
}
//Load data on app start up
private void loadData(){
SharedPreferences sharedPreferences = getSharedPreferences("shared preferences", MODE_PRIVATE);
Gson gson = new Gson();
String json = sharedPreferences.getString("game list", null);
Type type = new TypeToken<ArrayList<String>>() {}.getType();
gameList = gson.fromJson(json, type);
if(gameList == null){
gameList = new ArrayList<>();
}
}
You could create three integers for "On" and "Off" states and one to hold the switch value either on or off. This is how I did mine.
int reminderState;
int REMINDER_ON = 1;
int REMINDER_OFF = 0;
switch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked) {
if (isChecked) {
reminderState = REMINDER_ON;
} else {
reminderState = REMINDER_OFF;
}
}
});
So in your saveData() method, you store the reminderSate value in your shared preferences.
And in loadData() you check if the reminderState is on or off then set your switch according to the switch state.
I am just trying to store the users input from an editText in a Shared Preference, but it is not working:
editText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
#Override
public boolean onEditorAction(TextView v, int keycode, KeyEvent event) {
Log.v(TAG, keyword.getString("keyword", "mDefault")); //IT LOGS OUT THE DEFAULT STRING EVEN **AFTER** STORING THE PREFERENCES BEFORE
if (keycode == EditorInfo.IME_ACTION_SEND) {
editText.setText(editText.getText().toString());
keywordEditor.putString("keyword", editText.getText().toString());
keywordEditor.commit();
Log.v(TAG, keyword.getString("keyword", "default")); //CORRECT! THIS LINE WORKS
}
}
return true;
});
When I first edit the text, I will first get a log of "mDefault" which is normal, since nothing is stored in the shared preference.
Then, I store something in the shared preference, and to make sure it stored, I log and I get a log of what I typed. Which means the shared preference data WAS stored.
Heres the problem: After I have stored something in the shared preference, I go to a different activity, and I come back, and all the data stored in the shared preference is GONE!
The very first log still says mDefault after navigating through activities.
What could the problem be?
EDIT:
Here is my instantiation:
onCreate:
keyword = PreferenceManager.getDefaultSharedPreferences(this); //Making a shared preferences
keywordEditor = keyword.edit();
Maybe you don't save on setOnEditorActionListener. Save when you go to a different activity. Because when it goes to different activity the setOnEditorActionListener editText.getText().toString() it returns null.
STORING PREFERENCES:
SharedPreferences pref = getSharedPreferences("MyPrefs",Context.MODE_PRIVATE);
// We need an editor object to make changes
SharedPreferences.Editor edit = pref.edit();
// Set/Store data
edit.putString("username", "Rishabh");
edit.putString("password", "rishabh123");
// Commit the changes
edit.commit();
RETRIEVING PREFERENCES:
SharedPreferences pref = getSharedPreferences("MyPrefs", Context.MODE_PRIVATE);
String username = pref.getString("username", "");
String password= pref.getString("password", "");
Log.d(TAG, username);
Log.d(TAG, password);
Adding this as an example in case you missed a key components. This is currently working for me:
public class Main2Activity extends ActionBarActivity {
private SharedPreferences keyword;
private SharedPreferences.Editor keywordEditor;
private String TAG = "TAG";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
keyword = PreferenceManager.getDefaultSharedPreferences(this); //Making a shared preferences
keywordEditor = keyword.edit();
final EditText editText = (EditText) findViewById(R.id.et_text);
findViewById(R.id.btn_launch).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Main2Activity.this, Main22Activity.class);
startActivity(intent);
}
});
editText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
#Override
public boolean onEditorAction(TextView v, int keycode, KeyEvent event) {
Log.v(TAG, "Initial: " + keyword.getString("keyword", "mDefault")); //IT LOGS OUT THE DEFAULT STRING EVEN **AFTER** STORING THE PREFERENCES BEFORE
if (keycode == EditorInfo.IME_ACTION_SEND) {
editText.setText(editText.getText().toString());
keywordEditor.putString("keyword", editText.getText().toString());
keywordEditor.commit();
Log.v(TAG, "Saving in prefs: " + keyword.getString("keyword", "default")); //CORRECT! THIS LINE WORKS
}
return true;
}
});
}
}
From a fresh install:
I typed in "test" and hit the send button on keyboard therefore invoked the onEditorAction
Then clicked on launch new activity -> hit back button and typed in "test2" and hit send button.
The following is the log out put:
02-29 23:26:42.068 18105-18105/com.example.naveed.myapplication V/TAG: Initial: mDefault
02-29 23:26:42.136 18105-18105/com.example.naveed.myapplication V/TAG: Saving in prefs: test
02-29 23:26:53.281 18105-18105/com.example.naveed.myapplication V/TAG: Initial: test
02-29 23:26:53.338 18105-18105/com.example.naveed.myapplication V/TAG: Saving in prefs: test2
As you can see initially it was "mDefault" then "test" was saved. I launched a new activity and came back. Next time the initial was "test" since it was saved last time and "test2" was the new value saved.
Create SharedPreferences class
public class SharedPreferenceClass
{
// Shared Preferences
SharedPreferences pref;
// Editor for Shared preferences
SharedPreferences.Editor editor;
// Context
Context _context;
// Shared pref mode
int PRIVATE_MODE = 0;
// Sharedpref file name
private static final String PREF_NAME = "INTELLIJ_AMIYO";
public static final String KEY_SET_VALUE= "KEY_SET_VALUE";
public SharedPreferenceClass(Context context){
this._context = context;
pref = _context.getSharedPreferences(PREF_NAME, 0);
editor = pref.edit();
}
public void setUserDATA(String data)
{
editor.remove(KEY_SET_VALUE);
editor.putString(KEY_SET_VALUE, data);
editor.commit();
}
public String getUserDATA()
{
String getData= pref.getString(KEY_SET_VALUE, null);
return getData;
}
}
Now call this in your Activity section globally
SharedPreferenceClass sharedPrefClassObj;
& call onCreate(Bundle savedInstanceState) section
sharedPrefClassObj = new SharedPreferenceClass(getApplicationContext());
Now add this
editText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
#Override
public boolean onEditorAction(TextView v, int keycode, KeyEvent event) {
if (keycode == EditorInfo.IME_ACTION_SEND) {
editText.setText(editText.getText().toString());
sharedPrefClassObj.setUserDATA(editText.getText().toString()); // Set data
// Get data sharedPrefClassObj.getUserDATA();
}
}
return true;
});
Very important: you need a Preference name (for example: "MY_PREFS_NAME") to set and retrieve the values:
SharedPreferences.Editor keywordEditor = context.getSharedPreferences("MY_PREFS_NAME", MODE_PRIVATE).edit();
Use the same constant Preference name and it will give you the same preferences in any point of your app.
I have two different activity's. First one only showed to the user first time - to store phonenumber inside sharedprefs. I think the problem is my load from prefs method but just in case I will leave everything here to make it more relevant to future users. It looks like in both activitys the "mobilnummer" is saved - but I am having problem to display them.
The idea is it to be overwritten if user updates it - I think the method will do that?
OnStartUp.java
public static final String PREFS_NAME = "MobileNumberSaved";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mobilnummer = (EditText) findViewById(R.id.mobilnummer);
final Button button = (Button) findViewById(R.id.ntonboarding);}
public void SaveToMobile(View v) {
if (mobilnummer.getText().toString().length() >= 8) {
FragmentedUser.SaveMobile(mobilnummer.getText().toString()); // just saves to Parse.com (This works)
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putString("mobilnummer", mobilnummer.toString());
editor.commit();
}
}
Profile
EditText mobilnummer;
public static final String PREFS_NAME = "MobileNumberSaved";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mobilnummer = (EditText) findViewById(R.id.mobilnummer);
This is the issue/problem i think! (Code below)
SharedPreferences MobileNumberSaved = this.getSharedPreferences("mobilnummer", Context.MODE_PRIVATE);
String tempMobilnummer = mobilnummer.getText().toString();
mobilnummer.setText(tempMobilnummer);
// IF user wants to change mobilenumber
mobilnummer.setOnEditorActionListener(new TextView.OnEditorActionListener() {
#Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
boolean handled = false;
if (actionId == EditorInfo.IME_ACTION_SEND) {
if (mobilnummer.getText().toString().length() >= 8)
FragmentedUser.SaveMobile(mobilnummer.getText().toString());
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putString("mobilnummer", mobilnummer.toString());
editor.commit();
tlfstatus.setImageResource(R.drawable.ok);
handled = true;
}
return handled;
}
});
I think here is your error:
SharedPreferences MobileNumberSaved = this.getSharedPreferences("mobilnummer", Context.MODE_PRIVATE);
//here it should be MobileNumberSaved instead of mobilnummer, because tehre is no sense to set the same text to the textView again after you got it from there
String tempMobilnummer = MobileNumberSaved.getText().toString();
mobilnummer.setText(tempMobilnummer);
But the correct way to get a value from shared preferences is something like this:
SharedPreferences prefs = getSharedPreferences(PREFS_NAME, MODE_PRIVATE);
String savedMobileNumber = prefs.getString("mobilnummer", "");
mobilnummer.setText(savedMobileNumber);
Update: when you save the value in the shared preferences, you save only the editText, not it's value, so do something like this when saving:
SharedPreferences.Editor editor = settings.edit();
//mobilnumber is your EditText, so get it's text like this
editor.putString("mobilnummer", mobilnummer.getText().toString());
editor.commit();
And everything else is still the same that I wrote above
I have a configuration page which has a form on it. When the button is pressed, I want to save that value to a SharedPreference. This SharedPreference value then needs to be accessed from elsewhere in my app.
I am trying to save the value like the below. I want to save the collectionID so I can use it elsewhere
public class ConfigPage extends Activity {
public static final String PREFS_NAME = "MyPrefsFile";
Button mButton;
EditText mEdit;
String collectionID;
String key = "GregKey";
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.config);
getActionBar().hide();
mButton = (Button)findViewById(R.id.setCollection);
mEdit = (EditText)findViewById(R.id.collectionName);
mButton.setOnClickListener(
new View.OnClickListener()
{
public void onClick(View view)
{
collectionID = mEdit.getText().toString();
Log.d("EditText", collectionID);
SharedPreferences settings =
getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putString(key, collectionID);
editor.commit();
}
});
}
}
Once it has been saved, I then need to access it in another class, however I can't figure out how to do this. The example above crashes the application at the moment so something isn't quite right
I want to save the collectionID so I can use it elsewhere
Use mButton Button onClick event for saving EditText text in SharedPreferences as :
mButton.setOnClickListener( new View.OnClickListener()
{
public void onClick(View view)
{
collectionID = mEdit.getText().toString();
Log.d("EditText", collectionID);
// save value here in SharedPreferences
SharedPreferences settings =
ConfigPage.this.getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putString(collectionID, collectionID);
editor.commit();
}
});
Your crash occurs because your value is null:
String savedID;
You need to add a value to the variable:
String savedID = "somevalue";
Also, your key is null as long as the Button is not pressed which will also lead to a crash.
The putString(String key, String value) method enables you to store a specific value with a specific key, that can later be used to reaccess the stored value.
Example:
String key = "somekey";
String value = "yourvaluetostore";
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putString(key, value); // store the value
editor.commit();
In another Activity:
String key = "somekey";
SharedPreferences sharedPreferences = getSharedPreferences(PREFS_NAME, 0);
// get the value "" is default
String value = sharedPreferences.getString(key, "");
All you need in the other Activity is the key you stored the value with. With this key, you can pull the correct stored value out of the SharedPreferences. --> The key is needed to identify the value.
Since you are using the part of code :
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putString(collectionID, savedID);
editor.commit();
Log.d("Saved as", savedID);
in the onCreate method, that translates to
...
editor.putString(null, null);
Log.d("Saved as", null);
Correct your code so that you fill those elements before. I guess you wanted to make the save in the OnClick part
Yes something its not quite right here because as i see you are saving nothing. on shared pref you should have a "key" which will be use to identify the saved value in your example it should be something like this
public class ConfigPage extends Activity {
public static final String PREFS_NAME = "MyPrefsFile";
public static final String COLLECTIONID_KEY = "COLLECTIONID_KEY";
Button mButton;
EditText mEdit;
String collectionID;
String savedID;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.config);
getActionBar().hide();
mButton = (Button)findViewById(R.id.setCollection);
mEdit = (EditText)findViewById(R.id.collectionName);
mButton.setOnClickListener(
new View.OnClickListener()
{
public void onClick(View view)
{
collectionID = mEdit.getText().toString();
Log.d("EditText", collectionID);
}
});
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putString(COLLECTIONID_KEY, collectionID);
editor.commit();
Log.d("Saved as", COLLECTIONID_KEY);
}
}
then to retrieve it :
SharedPreferences sharedPreferences = getSharedPreferences(PREFS_NAME, 0);
String mySavedCollectionID = sharedPreferences.getString(COLLECTIONID_KEY);
and make sure that its done on the Onclick event otherwise you might end up with crash again because after the on-click event in your code the lines below will run anyway and save null!
I have multiple on click listeners implemented in the code. But, I want each click from seperate images to be saved in a "ticker" in shared preferences. So, if there are 2 clicks on image 1, 4 clicks on image 2, and 6 clicks on image 3, it totals up to be 12 "clicks" counted in shared prefs. The problem is, every onClickListener seems to overwrite the other, instead of stacking. Any ideas on how to accomplish this?
Image1.setOnClickListener(new View.OnClickListener() {
SharedPreferences pref = getSharedPreferences("ActivityPREF", Context.MODE_PRIVATE);
int numClicks = pref.getInt("Total_Clicks", 0);
#Override
public void onClick (View v) {
numClicks++;
}
SharedPreferences pref =
getSharedPreferences("ActivityPREF", Context.MODE_PRIVATE);
Editor ed = pref.edit();
ed.putInt("Total_Clicks", numClicks);
ed.apply();
}
});
Image2.setOnClickListener(new View.OnClickListener() {
SharedPreferences pref = getSharedPreferences("ActivityPREF", Context.MODE_PRIVATE);
int numClicks = pref.getInt("Total_Clicks", 0);
#Override
public void onClick (View w) {
numClicks++;
}
SharedPreferences pref =
getSharedPreferences("ActivityPREF", Context.MODE_PRIVATE);
Editor ed = pref.edit();
ed.putInt("Total_Clicks", numClicks);
ed.apply();
}
});
Image3.setOnClickListener(new View.OnClickListener() {
SharedPreferences pref = getSharedPreferences("ActivityPREF", Context.MODE_PRIVATE);
int numClicks = pref.getInt("Total_Clicks", 0);
#Override
public void onClick (View x) {
numClicks++;
}
SharedPreferences pref =
getSharedPreferences("ActivityPREF", Context.MODE_PRIVATE);
Editor ed = pref.edit();
ed.putInt("Total_Clicks", numClicks);
ed.apply();
}
});
You are keeping track of the numclicks 3 times (inside each OnClickListener), so it makes sense for them to override each other.
For starters you could create your OnClickListener only once, and assign it to each image. This should solve it:
View.OnClickListener imageClickedListener = new View.OnClickListener() {
SharedPreferences pref = getSharedPreferences("ActivityPREF", Context.MODE_PRIVATE);
int numClicks = pref.getInt("Total_Clicks", 0);
#Override
public void onClick (View v) {
numClicks++;
Editor ed = pref.edit();
ed.putInt("Total_Clicks", numClicks);
ed.apply();
}
}
Image1.setOnClickListener(imageClickedListener);
Image2.setOnClickListener(imageClickedListener);
Image3.setOnClickListener(imageClickedListener);
EDIT:
I've added a reply to your comment here cause I find it clearer.
The sharedPreferences instances were not the problem. They all talk to the same saved data ("ActivityPREF"). The problem was that you had 3 instances of OnClickListener, and all 3 of them were holding the integer numClicks. So they all started at 0 (or previously saved amount), and only increased the local numClicks. So if I tapped image1 twice, the numClicks inside that listener would be on 2. While the other ones would still be at 0.
It would have worked if you would have added the following to the onClick methods, before increasing the numClicks:
numClicks = pref.getInt("Total_Clicks", 0);
Since it would then reload it from the saved value. Only the code inside the onClick method is called each time a click is made, not the code you add when instantiating an OnClickListener.