samedi 4 avril 2015

Android - How to save String from EditText to Sharedpreferences - not working

I have an XML file which gets some text with an input type numberDecimal. I then get this text using getText.toString.


I would like to save this data persistently using Sharedpreferences. Then I would like to retrieve this data in another Activity. Everything is working when I hard code the putString in Sharedpreferences. It is when I try to pass a String variable to Shared preferences that this fails.


This is what I would like to have working...



SharedPreferences user_data = getSharedPreferences(STORAGE, Context.MODE_PRIVATE);

final EditText user_wage = (EditText)findViewById(R.id.wage);

finalwage = user_wage.getText().toString();

SharedPreferences.Editor editor = user_data.edit();
editor.putString("wageKEY",finalwage);
editor.commit();


Sharedpreferences works when I do this.... I mean I can save the data and retrieve it later.



SharedPreferences user_data = getSharedPreferences(STORAGE, Context.MODE_PRIVATE);

final EditText user_wage = (EditText)findViewById(R.id.wage);

finalwage = user_wage.getText().toString();

SharedPreferences.Editor editor = user_data.edit();
editor.putString("wageKEY","123");
editor.commit();


Also I can get this to work....



SharedPreferences user_data = getSharedPreferences(STORAGE, Context.MODE_PRIVATE);

final EditText user_wage = (EditText)findViewById(R.id.wage);

finalwage = user_wage.getText().toString();
testvar = "123";

SharedPreferences.Editor editor = user_data.edit();
editor.putString("wageKEY",testvar);
editor.commit();


In summary I can get everything working fine when the String is hard coded in my program. It is when I get the user's input and try to save it that I always get a number exception error on the retrieving side. How should I go about saving a String variable from an EditText?


I think the problem may be because I am using the numberDecimal type in the XML file, but I have also tried regular text input with no luck.


Thank you!


Aucun commentaire:

Enregistrer un commentaire