Am trying to get shared preferences working from here
I added the code from that thread, adapting it to my needs, it is showing no errors in the android studio until I compile it.
public class ChrStats extends Activity
{
private SharedPreferences savedFields
private Button saveButton;
private EditText editText;
private EditText editText2;
private EditText editText3;
private EditText editText4;
private EditText editText5;
private EditText editText6;
private EditText editText7;
// Add all your EditTexts...
// Upon creating your Activity, reload all the saved values.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.your_layout);
saveButton = (Button) findViewById (R.id.your_save_button_id);
editText = (EditText) findViewById (R.id.your_edit_text_1_id);
editText2 = (EditText) findViewById(R.id.your_edit_text_2_id);
editText3 = (EditText) findViewById(R.id.your_edit_text_3_id);
editText4 = (EditText) findViewById(R.id.your_edit_text_4_id);
editText5 = (EditText) findViewById(R.id.your_edit_text_5_id);
editText6 = (EditText) findViewById(R.id.your_edit_text_6_id);
editText7 = (EditText) findViewById(R.id.your_edit_text_7_id);
// Keep adding all your EditTexts the same way...
// "info" is just a tag name, use anything you like
savedFields = getSharedPreferences("info", MODE_PRIVATE);
// In case no value is already saved, use a Default Value
editText.setText(savednotes.getString("editText1", "Default Value 1"));
editText2.setText(savednotes.getString("editText2", "Default Value 2"));
editText3.setText(savednotes.getString("editText3", "Default Value 3"));
editText4.setText(savednotes.getString("editText4", "Default Value 4"));
editText5.setText(savednotes.getString("editText5", "Default Value 5"));
editText6.setText(savednotes.getString("editText6", "Default Value 6"));
editText7.setText(savednotes.getString("editText7", "Default Value 7"));
// Save the changes upon button click
saveButton.setOnClickListener(saveButtonListener);
}
public OnClickListener saveButtonListener = new OnClickListener () {
#Override
public void onClick(View v) {
SharedPreferences.Editor preferencesEditor = savedFields . edit ();
if (editText.getText().length() > 0) // Not empty
preferencesEditor.putString("editText", editText.getText());
if (editText2.getText().length() > 0) // Not empty
preferencesEditor.putString("editText2", editText2.getText());
if (editText3.getText().length() > 0) // Not empty
preferencesEditor.putString("editText3", editText3.getText());
if (editText4.getText().length() > 0) // Not empty
preferencesEditor.putString("editText4", editText4.getText());
if (editText5.getText().length() > 0) // Not empty
preferencesEditor.putString("editText5", editText5.getText());
if (editText6.getText().length() > 0) // Not empty
preferencesEditor.putString("editText6", editText6.getText());
if (editText7.getText().length() > 0) // Not empty
preferencesEditor.putString("editText7", editText7.getText());
// You can make a function so you woudn't have to repeat the same code for each EditText
// At the end, save (commit) all the changes
preferencesEditor.commit();
}
}
}
I expected it to throw up no errors, but I looked up the relevant references, and can't see many faults in it. Here is the screenshot of errors from the android studio.
So, i see 3 critical problems here:
no semicolon after private SharedPreferences savedFields
you have no declaration of savednotes. Maybe it should be savedFields instead?
Your java code placed in .kt file. idk how could this happend
Related
I have an activity with two TextViews which show int values. These values change incrementally (1, 2, 3, and so...) when the user clicks a button. I use SharedPreferences to store that values via button click. When I close the app and open it again, the values are correctly displayed in the TextViews, but if they change, they should be added from the previous stored value. Problem is that they start to count from zero.
Here is my code:
public class Roulette1 extends ActionBarActivity {
Button button0, button1;
int click_button0, click_button1;
public static final String button0Str = "button0Key";
public static final String button1Str = "button1Key";
public static final String MyPREFERENCES = "MyPrefsRoulette1";
SharedPreferences sharedpreferences;
TextView times_0_tv;
TextView times_1_tv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout1);
times_0_tv = (TextView) findViewById(R.id.times_0);
times_1_tv = (TextView) findViewById(R.id.times_1);
button0 = (Button) findViewById(R.id.button0);
button1 = (Button) findViewById(R.id.button1);
final TextView total_clicks_tv = (TextView) findViewById(R.id.total_clicks);
button1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
click_button1 = click_button1 + 1;
int total_clicks = click_button0 + click_button1;
total_clicks_tv.setText(String.valueOf(total_clicks));
times_0_tv.setText(click_button0);
times_1_tv.setText(click_button1);
button0.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
click_button0 = click_button0 + 1;
int total_clicks = click_button0 + click_button1;
total_clicks_tv.setText(String.valueOf(total_clicks));
times_0_tv.setText(click_button0);
times_1_tv.setText(click_button1);
}
});
sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
if (sharedpreferences.contains(button0Str))
{
times_0_tv.setText(sharedpreferences.getString(button0Str, ""));
}
if (sharedpreferences.contains(button1Str))
{
times_1_tv.setText(sharedpreferences.getString(button1Str, ""));
}
}
public void run1(View view) {
SharedPreferences.Editor editor = sharedpreferences.edit();
String times0string = times_0_tv.getText().toString();
String times1string = times_1_tv.getText().toString();
editor.putString(button0Str, times0string);
editor.putString(button1Str, times1string);
editor.commit();
}
Hope you have any idea. Thanks!
When you read from sharedPrefs, remember to update the field counters and not just the value of the textViews.
As suggested in the comments, a possible solution would be to use the textView value as the state, updating that directly. Otherwise you have to keep the counters updated manually, for example by updating the fields value at the same time you update the textView value. Personally, I prefer to keep the state separated from the presentation, so that it is easier to compute something with that value later (the downside is that you have to keep the view synchronized. This might change with the new data binding library).
PS I purposely did not put any code, because the solution is trivial and there are other answers with code, but more importantly because I think that the data binding library is a much cleaner way to deal with this kind of problems, even though it's still in beta stage.
Sharedpreferences stored int data also. Check this link:
http://androidexample.com/Android_SharedPreferences_Basics/index.php?view=article_discription&aid=126&aaid=146
SharedPreferences pref = getApplicationContext().getSharedPreferences("MyPref", MODE_PRIVATE);
Editor editor = pref.edit();
/**************** Storing data as KEY/VALUE pair *******************/
editor.putBoolean("key_name1", true); // Saving boolean - true/false
editor.putInt("key_name2", "int value"); // Saving integer
editor.putFloat("key_name3", "float value"); // Saving float
editor.putLong("key_name4", "long value"); // Saving long
editor.putString("key_name5", "string value"); // Saving string
// Save the changes in SharedPreferences
editor.commit(); // commit changes
I think there is some logical mistake in your code. Please check.
Add this code to the very beginning of your oncreate:
SharedPreferences sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
times0string = String.valueOf(sharedPreferences.getString(button0Str, 0));
times1string = String.valueOf(sharedPreferences.getString(button1Str, 0));
To solve your problem, Try below code:
Replace first two line inside button1 onClick()
click_button1 = Integer.parseInt(sharedpreferences.getString(button1Str, "")) + 1;
int total_clicks = Integer.parseInt(sharedpreferences.getString(button0Str, "")) + click_button1;
Replace first two line inside button0 onClick()
click_button0 = Integer.parseInt(sharedpreferences.getString(button0Str, "")) + 1;
int total_clicks = click_button0 + Integer.parseInt(sharedpreferences.getString(button1Str, ""));
public class MainActivity extends Activity {
EditText number1, number2;
String number_1, number_2;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
number1 = (EditText) findViewById(R.id.number1);
number2 = (EditText) findViewById(R.id.number2);
number_1 = number1.getText().toString();
number_2 = number2.getText().toString();
After running the application, why does number_1 have an empty value.
onCreate method is create view.
So EditText number1, nubmer2 is not create yet.
If you want get number1 or number2's value, try in onPause().
Try this..
You have to get the text in like OnClick while starting application both EditText is empty. So that it returns empty.
number_1 = number1.getText().toString();
number_2 = number2.getText().toString();
Make sure you have predefined the value in the edittext and that should work
i need to see your xml.... if your trying to get numbers you have to parse the string to an int anyway... what are you trying to achieve? you simply want the text, from each of the textviews? is there text set in the xml?
Make sure you have predefined the value in the edittext in xml file.
like in your layout file android:text="your string" or else you have to set string after binding
oncreate method like.
number1 = (EditText) findViewById(R.id.number1);
number2 = (EditText) findViewById(R.id.number2);
number1.setText("your string");
then you have to get string from below code.
number_1 = number1.getText().toString();
number_2 = number2.getText().toString();
You need to fill the EditTexts with something before you can get their value. So create a button, and after filling the EditTexts, then get their values by clicking the button.
Perhaps like this:
public class MainActivity extends Activity {
EditText number1, number2;
String number_1, number_2;
Button submit;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
number1 = (EditText) findViewById(R.id.number1);
number2 = (EditText) findViewById(R.id.number2);
submit = (Button)findViewById(R.id.btn1); //Define a button in your layout xml file with the ID field set as "btn1"
submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
number_1 = number1.getText().toString();
number_2 = number2.getText().toString();
}
});
I have entered values in my text field, But the debugger shows null value.
The text id's are correct yet no value is being printed.
The log cat is showing null pointer exception. I have declared all the variables in the class.
The edit text string functions are declared in the method itself.
et1 = (EditText)findViewById(R.id.editText1);
et2 = (EditText)findViewById(R.id.editText2);
et3 = (EditText)findViewById(R.id.editText3);
et4 = (EditText)findViewById(R.id.editText4);
et5 = (EditText)findViewById(R.id.editText5);
set1 = et1.getText().toString();
set2 = et2.getText().toString();
set3 = et3.getText().toString();
set4 = et4.getText().toString();
set5 = et5.getText().toString();
System.out.println("set1 ="+set1);
System.out.println("set2 ="+set2);
All values given input are showing null and these are the few values that are being declared in the xml.
I need to know what mistake i am doing and how to rectify it.
i have initialized the values after setContent the data access happens in button on click listener... i didnt want to post the entire code.. –
I think your problem is same as this question.
You are directly accesssing the EditText's value after initializtion of EditText. You should accept the value on some event like onClick.
Let me Explain,
public class MainActivity extends Activity
{
EditText editText;
#Override
public void onCreate ( Bundle savedInstanceState )
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editText = (EditText) findViewById ( R.id.firstEditText );
String str = editText().getText().toString();
// Here Str will be null blank all the time because EditText it self is blank.
}
}
Now see this
public class MainActivity extends Activity implements OnClickListener
{
EditText editText;
#Override
public void onCreate ( Bundle savedInstanceState )
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editText = (EditText) findViewById ( R.id.firstEditText );
String str = editText().getText().toString();
// Here Str will be null blank all the time, since you haven't input anything in your EditText
}
#Override
public void onClick ( View view )
{
// Assuming you have already put some text in edittext.
String newStr = editText().getText().toString();
}
}
I would suggest you to follow some steps to find out your actual problem
check that you have set right layout in the setContentView.
before getting text from edit text set some text in it and then get text form the EditText view. Check that it still printing null.
I think you have done some silly mistake because EditText.getText() never returns null.
NullPoint exception is thrown because you are converting a NULL value to a string
et1.getText() is null and you are doing
et1.getText().toString();
which is wrong.
Every EditText is initially NULL because it does not contain any value.
According to Android Docs
public Editable getText ()
Added in API level 1
Return the text the TextView is displaying.
Since the EditText has not been set any text hence its current value is null.
I am very new to java and android but doing my best to make an app, basicaly I want a page with 6 text boxes on it, and each allows the user to type a 3 digit unique value into each, check a confirm box and then a button to save, then when the user revisits this part of the app the data will still be there, I managed to get it working for 1 box but if i add another it just duplicated box 1s value, here is my code for the class
public class Settings extends Activity implements OnClickListener {
CheckBox cb;
EditText et, et1;
Button b;
String test;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.settings);
cb = (CheckBox) findViewById(R.id.checkBox1);
et = (EditText) findViewById(R.id.editText1);
b = (Button) findViewById(R.id.button1);
b.setOnClickListener(this);
loadPrefs();
cb.setChecked(false);
}
private void loadPrefs() {
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
boolean cbValue = sp.getBoolean("CHECKBOX", false);
String name = sp.getString("NAME", "Kg");
if(cbValue){
cb.setChecked(true);
}else{
cb.setChecked(false);
}
et.setText(name + (" kg"));
}
private void savePrefs(String key, boolean value) {
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
Editor edit = sp.edit();
edit.putBoolean(key, value);
edit.commit();
}
private void savePrefs(String key, String value) {
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
Editor edit = sp.edit();
edit.putString(key, value);
edit.commit();
}
public void onClick(View v) {
// TODO Auto-generated method stub
savePrefs("CHECKBOX", cb.isChecked());
if (cb.isChecked())
savePrefs("NAME", et.getText().toString());
finish();
}
}
any help would be greatly appreciated as time is short :(
Read this.
What you're not coding is saving the data.
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
boolean cbValue = sp.getBoolean("CHECKBOX", false);
What the second line does is says, is "CHECKBOX" a saved sharedpreference? No, it isn't. Okay let's get the default value of false then.
What you need to do is save it using this:
SharedPreferences.editor Editor = sp.edit();
Editor.putBoolean("CHECKBOX",true);
Editor.commit();
The first line defines the sharedpreference editor. The next line saves the boolean value true under the in effect filename (key) of CHECKBOX and then the commit line says, okay do the above and finalise it so that now whenever I call:
sp.getBoolean("CHECKBOX",false);
I will get true because I won't have to use the default value of false.
Try to make this easy for you...
First, in your proferences xml, each text box and check box needs it's own key.
Secondly, to make it easy for you to read/understand you should assign a different name for the pref save method void savePrefs(String key, String value).
For example String: void savePrefsString(String key, String value)
For example boolean: void savePrefsBoolean(String key, boolean value)
Be sure each one is called appropriately (savePrefsBoolean for boolean and savePrefsString for edittext).
Then for each edit text you will want to retrieve the key from preferences for that edittext.
Example:
String name1 = sp.getString("NAME1", "Kg");
String name2 = sp.getString("NAME2", "Kg");
String name3 = sp.getString("NAME3", "Kg");
Then:
et1.setText(name1 + (" kg"));
et2.setText(name2 + (" kg"));
et3.setText(name1 + (" kg"));
Do the same for your checkboxes (they are actually true/false booleans).
Example:
boolean cb1 = sp.getBoolean("CHECKBOX1", false); //false is default value
boolean cb2 = sp.getBoolean("CHECKBOX1", false);
boolean cb3 = sp.getBoolean("CHECKBOX1", false);
Then to set value from prefs:
if(cb1){
cb1.setChecked(true);
}else{
cb1.setChecked(false);
}
and to save what the user has pressed:
savePrefsBoolean("CHECKBOX1", cb1.isChecked()); // get check value of checkbox
savePrefsBoolean("CHECKBOX2", cb2.isChecked());
savePrefsBoolean("CHECKBOX3", cb3.isChecked());
I have a SharedPreferences that saves EditText input from one activity and displays the String value in another activity.
When I enter an input into the EditText fields and press (a button I created) "Save" (which commits the EditText to editor), the file is stored successfully. However, the display activity (which displays the stored String values in SharedPreferences) doesn't display the values. I am guessing it is because it is the onCreate, so the screen is "created" when it runs. How can I get it to update the EditText values when the user commits (presses save) immediately?
CustomStoreEditActivity - Just storing the user inputs (EditText entries):
final Button saveButton = (Button) findViewById(R.id.saveButton);
saveButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
if (saveButton.isClickable()) {
SharedPreferences prefs = getSharedPreferences(
"customtime", 0);
// prefs.registerOnSharedPreferenceChangeListener(this);
final SharedPreferences.Editor edit = prefs.edit();
EditText shopName = (EditText) findViewById(R.id.shopName);
EditText open1 = (EditText) findViewById(R.id.open1);
EditText close1 = (EditText) findViewById(R.id.close1);
EditText open2 = (EditText) findViewById(R.id.open2);
EditText close2 = (EditText) findViewById(R.id.close2);
EditText open3 = (EditText) findViewById(R.id.open3);
EditText close3 = (EditText) findViewById(R.id.close3);
EditText open4 = (EditText) findViewById(R.id.open4);
EditText close4 = (EditText) findViewById(R.id.close4);
EditText open5 = (EditText) findViewById(R.id.open5);
EditText close5 = (EditText) findViewById(R.id.close5);
EditText open6 = (EditText) findViewById(R.id.open6);
EditText close6 = (EditText) findViewById(R.id.close6);
EditText open7 = (EditText) findViewById(R.id.open7);
EditText close7 = (EditText) findViewById(R.id.close7);
EditText comments = (EditText) findViewById(R.id.comments);
edit.putString("shopName", shopName.getText().toString());
edit.putString("Monday1", open1.getText().toString());
edit.putString("Monday2", close1.getText().toString());
edit.putString("Tuesday1", open2.getText().toString());
edit.putString("Tuesday2", close2.getText().toString());
edit.putString("Wednesday1", open3.getText().toString());
edit.putString("Wednesday2", close3.getText().toString());
edit.putString("Thursday1", open4.getText().toString());
edit.putString("Thursday2", close4.getText().toString());
edit.putString("Friday1", open5.getText().toString());
edit.putString("Friday2", close5.getText().toString());
edit.putString("Saturday1", open6.getText().toString());
edit.putString("Saturday2", close6.getText().toString());
edit.putString("Sunday1", open7.getText().toString());
edit.putString("Sunday2", close7.getText().toString());
edit.putString("comments", comments.getText().toString());
edit.commit();
Intent myIntent = new Intent(getBaseContext(),
CustomStoreActivity.class);
myIntent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
startActivity(myIntent);
Toast.makeText(getBaseContext(), "Opening Hours Saved!",
Toast.LENGTH_SHORT).show();
}
}
});
}
CustomStoreActivity - where I believe the problem lies:
private void displayPreferences(){
SharedPreferences prefs = getSharedPreferences("customtime", 0);
String shopName = prefs.getString("shopName", "Empty");
String shopTime1 = prefs.getString("Monday1", " ");
String shopTime2 = prefs.getString("Monday2", " ");
String shopComments = prefs.getString("comments", "");
TextView displayPrefs = (TextView) findViewById(R.id.displayPrefs);
displayPrefs.setText(shopName + shopTime1 + shopTime2 + shopComments);
}
Thank you for your ample time.
I think part of what you're looking for is to put your CustomStoreActivity code in onResume instead of onCreate. Whatever code you move into onResume will occur whenever the CustomStoreActivity is brought to the front (including when it is first created).
Another alternative, assuming that CustomStoreActivity is used to launch the Activity that contains the EditTexts, is to use startActivityForResult and pass the data back in the result Intent instead of using the SharedPreferences. Here is a simple example (though note that the setResult call in this example is passed null where you would want to pass in an Intent, as documented here in the Android docs).
It also seems like you're trying to use your second Activity like a dialog box with editable fields. If that's the case, yet another alternative is to actually use a variant of the Dialog class within your CustomStoreActivity class instead of creating another Activity to act like one. See the Android doc for dialogs.
I'm not sure I really understand your question but are you trying to update the TextView of a different Activity from the one you are in? In which case I don't think this can be done and you should use Intents to pass the data to the activity