I've been getting null returns from getting strings from my saved preferences. I'm not sure how savedpreferences worked but my understanding was that when call a sharedpreferences, it creates the keypair file on the phone so you can come back to it later.
My program is essentially a string creation application. When you press a button, it creates a string to send as an sms. My settings activity page has four edittexts that save whatever is inside them with a buttonclick and returns to the main activity. The final button creates a String by getting the value from the keyvalue pair and constructs the message. However, I've always gotten null for each of the values.
Heres the code for the settings page and then the main page. Please ask if I could add more, I didn't add ALL of the code, just the sharedpreferences portions.
public SharedPreferences sp;
public Editor e;
public void savethethings(){ //run this when enter is pressed/savew
EditText smsintro_hint = (EditText) findViewById(R.id.settings_smsintro_hint);
EditText smsbody_hint = (EditText) findViewById(R.id.settings_smsbody_hint);
EditText checkboxbody_hint = (EditText) findViewById(R.id.settings_checkboxbody_hint);
EditText checkboxbody_description_hint = (EditText) findViewById(R.id.settings_checkboxbody_description_hint);
String introstring = smsintro_hint.getText().toString();
String bodystring = smsbody_hint.getText().toString();
String checkboxbodystring = checkboxbody_hint.getText().toString();
String checkboxdescriptionstring = checkboxbody_description_hint.getText().toString();
e.putString("intro", introstring);
e.commit(); // you forgot to commit
if(!bodystring.isEmpty())
{
e.putString("body", bodystring);
e.commit();
}
if(!checkboxbodystring.isEmpty())
{
e.putString("checkbody", checkboxbodystring);
e.commit();
}
if(!checkboxdescriptionstring.isEmpty())
{
e.putString("checkboxdescr", checkboxdescriptionstring);
e.commit();
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.settingmenu);
//SP
sp = PreferenceManager.getDefaultSharedPreferences(getApplicationContext()); // forget about
// named preferences - get the default ones and finish with it
e = sp.edit();
Button tt = (Button)findViewById(R.id.savebutton);
tt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
finish();
}
});
public void save(View view)
{
//THINGS HAPPEN HERE WITH SHARED PREFERENCES :(
savethethings();
this.finish();
return;
}
public String finishedtext(String userstring)
{
smsintroduction = (sp.getString("intro", ""));
smsbody = (sp.getString("body", ""));
checkboxtext = (sp.getString("checkbody", ""));
checkboxmessage = (sp.getString("checkboxdescr", ""));
if(smsintroduction.isEmpty())
{
if(smsbody.isEmpty())
{
if(checkboxtext.isEmpty())
{
if(checkboxmessage.isEmpty()) //topkek for most AND statements Ive ever put in in if/then form
{
//Essentially the DEFAULT if they're ALL null
smsbody = "Hi "+ userstring +"! This is coming from jake's phone and it wants to send a text so we can talk or whatever. ";
}
}
}
}
Toast.makeText( this, "Creating text, then press send!", Toast.LENGTH_LONG).show();
String thetext = "";
thetext = smsintroduction + " " + smsbody + " " + checkboxtext;
return thetext;
}
public void savethethings(){ //run this when enter is pressed/savew
EditText smsintro_hint = (EditText) findViewById(R.id.settings_smsintro_hint);
EditText smsbody_hint = (EditText) findViewById(R.id.settings_smsbody_hint);
EditText checkboxbody_hint = (EditText) findViewById(R.id.settings_checkboxbody_hint);
EditText checkboxbody_description_hint = (EditText) findViewById(R.id.settings_checkboxbody_description_hint);
String introstring = smsintro_hint.getText().toString();
String bodystring = smsbody_hint.getText().toString();
String checkboxbodystring = checkboxbody_hint.getText().toString();
String checkboxdescriptionstring = checkboxbody_description_hint.getText().toString();
// if(!introstring.isEmpty()) //if the fields are NOT empty, they should get saved.
// {
e.putString("intro", introstring);
e.commit(); // you forgot to commit
if(!bodystring.isEmpty())
{
e.putString("body", bodystring);
e.commit();
}
if(!checkboxbodystring.isEmpty())
{
e.putString("checkbody", checkboxbodystring);
e.commit();
}
if(!checkboxdescriptionstring.isEmpty())
{
e.putString("checkboxdescr", checkboxdescriptionstring);
e.commit();
}
}
Create java class named SessionManger and put all your methods for setting and getting SharedPreferences values. When you want to save value use the object of this class and set and get the values.
Sample code given below.
public class SessionManager {
SharedPreferences pref;
SharedPreferences.Editor editor;
Context _context;
int PRIVATE_MODE = 0;
public SessionManager(Context context) {
this._context = context;
pref = _context.getSharedPreferences("name_that_you_use", PRIVATE_MODE);
editor = pref.edit();
editor.apply();
}
public void setIntroMessage(String data) {
editor.putString("intro", data);
editor.commit();
}
public String getIntroMessage() {
return pref.getString("intro", null);
}
}
Related
I've made registration and login activity in an android using shared preferences. User is able to registered and logged in successfully. But my problem is when new user is registered, it delete the previous user's registration details.
Here is my registration page:
public class Registration extends Activity implements
View.OnClickListener
{
SharedPreferences pref;
Editor editor;
TextView btn_registration , btn_formlogin;
EditText et_name, et_pass, et_email , et_phone ;
ImageView btn_upload ;
private static final int PICK_IMAGE_REQUEST = 0;
private Uri mImageUri;
SessionManager session;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_registration);
et_name = (EditText) findViewById(R.id.edt_Name);
et_pass = (EditText) findViewById(R.id.edt_userPassword);
et_email = (EditText) findViewById(R.id.edt_userEmail);
et_phone = (EditText) findViewById(R.id.edt_Phone);
btn_registration = (TextView) findViewById(R.id.btn_registration);
btn_formlogin = (TextView) findViewById(R.id.btn_formlogin);
btn_upload = (ImageView)findViewById(R.id.img_upload);
Map<String,String> values = new HashMap<String,String>();
AppCompatDelegate.setCompatVectorFromResourcesEnabled(true);
btn_upload.setOnClickListener(this);
SharedPreferences preference =
PreferenceManager.getDefaultSharedPreferences(this);
final String mImageUri = preference.getString("image", null);
btn_upload.setImageResource(R.drawable.adduser);
// creating an shared Preference file for the information to be stored
// first argument is the name of file and second is the mode, 0 is
private mode
pref = getSharedPreferences("USER_CREDENTIALS", 0);
// get editor to edit in file
editor = pref.edit();
// the tap of button we will fetch the information from four edittext
btn_registration.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick (View v) {
boolean validName = true;
boolean validPass = true;
boolean validPhone = true;
boolean validEmail = true;
String name = et_name.getText().toString();
String email = et_email.getText().toString();
String pass = et_pass.getText().toString();
String phone = et_phone.getText().toString();
if (isEmpty(et_name)) {
et_name.setError("Enter the Name");
validName = false;
}
if (isEmpty(et_pass)) {
et_pass.setError("Password can't be null");
validPass = false;
}
if (isEmail(et_email) == false) {
et_email.setError("Enter valid email");
validEmail = false;
}
if (isValidMobile(et_phone) == false) {
validPhone = false;
}
final String required_email= pref.getString("Email",null);
final String required_phone=pref.getString("Phone",null);
if(et_email.equals(required_email)){
validEmail = true;
}
else if(et_phone.equals(required_phone)){
validPhone = true;
}
if (validName && validPass && validPhone && validEmail){
// as now we have information in string. Lets stored them
with the help of editor
editor.putString("Name" , name );
editor.putString("Email", email);
editor.putString("Password", pass);
editor.putString("Phone", phone);
editor.putString("image", String.valueOf(mImageUri));
editor.commit(); // commit the values
Toast.makeText(Registration.this, "Registration
Successful", Toast.LENGTH_LONG).show();
session = new SessionManager(getApplicationContext());
session.createLoginSession(name, email, mImageUri);
// after saving the value open next activity
Intent ob = new Intent(Registration.this,
DashBoard.class);
startActivity(ob);
}
else{
Toast.makeText(Registration.this, "Registration
unsuccessful! Please retry.", Toast.LENGTH_LONG).show();
}
}
});
I just want to know how to register multiple user using shared preferences file ?
If you will have multiple users, it is better to use a database(sqlite) than a shared preferences.
in shared preference you can save only single value in a object if you want to save multiple users in your device then you can use room database to store multiple user details in your device. Shared Preference can be used only for single information or if you want to store multiple values in shared preference then you can store arrayList in shared prefefrence.
save array list in shared preference:-
private static SharedPreferences mPrefs;
private static SharedPreferences.Editor mPrefsEditor;
public static Set<String> getCamEval(Context ctx) {
mPrefs = PreferenceManager.getDefaultSharedPreferences(ctx);
return mPrefs.getStringSet("sdk_camEval", null);
}
public static void setCamEval(Context ctx, ArrayList<String> value) {
mPrefs = PreferenceManager.getDefaultSharedPreferences(ctx);
mPrefsEditor = mPrefs.edit();
Set<String> set = new HashSet<>();
set.addAll(value);
mPrefsEditor.putStringSet("sdk_camEval", set);
mPrefsEditor.commit();
}
I am developing an app,in that i am maintaining Session using Shared Preferences.I that when user login,i am using their email id for further use.But when i tried to use that email in another activity, it is showing null.
Below in my code for mainActivity:
public class main extends AppCompatActivity {
public Button submit;
public static final String MyPREFERENCES = "MyPrefs" ;
public static final String email = "emailkey";
SharedPreferences sharedpreferences;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity1);
submit = (Button) findViewById(R.id.btn_login);
ImageView i1 = (ImageView) findViewById(R.id.imgLogo);
String checkBoxText = "I agree to all the";
final CheckBox checkBox = (CheckBox) findViewById(R.id.checkBox);
sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
checkBox.setText(Html.fromHtml(checkBoxText));
checkBox.setMovementMethod(LinkMovementMethod.getInstance());
submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
EditText e1 = (EditText) findViewById(R.id.input_email);
EditText p1 = (EditText) findViewById(R.id.input_password);
String e = e1.getText().toString();
final String password = p1.getText().toString();
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putString(email, e);
editor.commit();
Here is my code for another activity:
String e,email;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.internshipsdetails);
SharedPreferences sharedpreferences = getSharedPreferences(main.MyPREFERENCES, Context.MODE_PRIVATE);
sharedpreferences.getString(email,e);
String url = "url?COMP_REQ_ID=" + title + "&StuEmail=" + e;
AQuery mAQuery = new AQuery(InternShipsDetails.this);
mAQuery.ajax(url, String.class, new AjaxCallback<String>() {
#Override
public void callback(String url, String data, AjaxStatus status) {
super.callback(url, data, status);
if (BuildConfig.DEBUG) {
Log.d("###$Request URL", url + "");
Log.d("###$Response ", data + "");
Log.d("###$Status Message : ", status.getMessage() + "");
Log.d("###$Status Code : ", status.getCode() + "");
}
You can manage session by changing shared preference values after doing logout action and check preference again at the time of login also. You can save current time also in a string at login and logout action. Make sure to use private shared preferences.
You are passing the wrong key to shared Pref because of that you are getting null.
Following is the updated code of yours which will give you the stored email address:
SharedPreferences sharedpreferences = getSharedPreferences(main.MyPREFERENCES, Context.MODE_PRIVATE);
e = sharedpreferences.getString(main.email,"");
String url = "url?COMP_REQ_ID=" + title + "&StuEmail=" + e;
Happy coding !!!
getString (String key, String defValue) method returns a String. So, you need to catch the output in a string variable.
Also, you are passing a nullkey. You need to pass the same key using which you saved the value.
So, in your case it would be
e = sharedpreferences.getString("emailkey","nodata");
public class ActivityEditParent extends AppCompatActivity {
private static final String TAG="ActivityEditParent";
CustomEditText etFirstName,etLastName,etEmail,etPhone;
public static ConnectionDetector detector;
private static final String URL = "http://hooshi.me.bh-in-13.webhostbox.net/index.php/parents/editprofile";
private SharedPreferences sharedPreferences;
private SharedPreferences.Editor editor;
private CustomButton btnSave;
private String parentFirstName,parentLastName,parentPhone;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_edit_parent);
getSupportActionBar().hide();
detector = new ConnectionDetector(ActivityEditParent.this);
getUIComponents();
}
private void getUIComponents(){
etFirstName = (CustomEditText) findViewById(R.id.edit_first_name);
etLastName = (CustomEditText) findViewById(R.id.edit_last_name);
etEmail = (CustomEditText) findViewById(R.id.edit_email_address);
etPhone = (CustomEditText) findViewById(R.id.edit_phone_number);
btnSave = (CustomButton) findViewById(R.id.btn_save_parent);
btnSave.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
editParent();
}
});
TextView title = (TextView) findViewById(R.id.toolbar_title);
ImageButton back = (ImageButton) findViewById(R.id.toolbar_back);
title.setText("Edit parent");
back.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
goBack();
}
});
sharedPreferences = getSharedPreferences(AppConstants.OOSH_PREFERENCES, Context.MODE_PRIVATE);
editor = sharedPreferences.edit();
String fName = sharedPreferences.getString(AppConstants.PARENT_FNAME,AppConstants.fName);
String lName = sharedPreferences.getString(AppConstants.PARENT_LNAME,AppConstants.lName);
String email = sharedPreferences.getString(AppConstants.PARENT_EMAIL,AppConstants.email);
String phone = sharedPreferences.getString(AppConstants.PARENT_MOBILE,AppConstants.mobile);
etFirstName.setText(fName);
etLastName.setText(lName);
etPhone.setText(phone);
etEmail.setText(email);
}
private void goBack() {
startActivity(new Intent(getApplicationContext(), ActivityEditDetails.class));
finish();
}
private void editParent(){
SharedPreferences preferences = getSharedPreferences(AppConstants.OOSH_PREFERENCES, Context.MODE_PRIVATE);
final SharedPreferences.Editor editor = preferences.edit();
JSONObject jsonParam = null;
parentFirstName = etFirstName.getText().toString().trim();
parentLastName = etLastName.getText().toString().trim();
parentPhone = etPhone.getText().toString().trim();
if (detector.checkInternet()){
jsonParam = new JSONObject();
JSONObject header = new JSONObject();
try {
jsonParam.put("parentId",preferences.getString(AppConstants.PARENT_ID,""));
jsonParam.put("parentFN",parentFirstName);
jsonParam.put("parentLN",parentLastName);
jsonParam.put("parentPhone",parentPhone);
jsonParam.put("apiAccessKey",preferences.getString(AppConstants.API_ACCESS_KEY,""));
header.put("parent",jsonParam);
Log.d("POST PARAMETERS:",""+header);
} catch (JSONException e) {
e.printStackTrace();
}
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, URL, header, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d("Response:",""+response);
String json_status = null;
try {
json_status = response.getString("status");
if (json_status.equalsIgnoreCase("Success")){
Toast.makeText(getApplicationContext(), "changed parent details successfully", Toast.LENGTH_SHORT).show();
startActivity(new Intent(getApplicationContext(),ActivityHome.class));
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
VolleySingleton.getInstance(getApplicationContext()).addToRequestQueue(jsonObjectRequest);
}
}
}
In the response After getting success message I want save the edited details in in respective edit text fields please help.After success message I am moving to home screen through intent and again I get back to this screen it is showing the previous details only.
all happens here :
...
if (json_status.equalsIgnoreCase("Success")){
Toast.makeText(getApplicationContext(), "changed parent details successfully", Toast.LENGTH_SHORT).show();
startActivity(new Intent(getApplicationContext(),ActivityHome.class));
}
...
once you have a success response save the edited values on the preferences, for example etFirstName, save it is new value to the corresponding preference :
...
if (json_status.equalsIgnoreCase("Success")){
Toast.makeText(getApplicationContext(), "changed parent details successfully", Toast.LENGTH_SHORT).show();
editor.putString(AppConstants.PARENT_FNAME, parentFirstName);
editor.apply(); //don't forget this
startActivity(new Intent(getApplicationContext(),ActivityHome.class));
}
...
any way you're creating the editor but not using it.
you want to save data after download from network or after an edit in edit text fields was made??
if from network add some save method execution statement in code where you download data was successful
if (json_status.equalsIgnoreCase("Success")){
Toast.makeText(getApplicationContext(), "changed parent details successfully", Toast.LENGTH_SHORT).show();
// here you have successful received data so u can map them to edit text or save in shared prefs
// add method to save data here
saveData(response);
startActivity(new Intent(getApplicationContext(),ActivityHome.class));
}
private void saveData(JSONObject response) {
// use JSon response object save here to shared preferences
// see how to load data from json object
// https://processing.org/reference/JSONObject_getString_.html
SharedPreferences sharedPreferences = getSharedPreferences(AppConstants.OOSH_PREFERENCES, Context.MODE_PRIVATE);
sharedPreferences.putString(....).apply;
// or set edit text controls with JSon data
}
to save edit text changes you have two choices :
add to layout save button (you have one) button and set on click listener with method to save data:
btnSave = (CustomButton) findViewById(R.id.btn_save_parent);
btnSave.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
saveData(v);
}
});
private void saveData(View view) {
// get root view
View rootView = view.getRootView();
// find edit text widget on root view
EditText etFirstName = (EditText) rootView.findViewById(R.id.edit_first_name);
// get string from edit text widget
String firstName = etFirstName.getString.toString();
// get shared preferences
SharedPreferences sharedPreferences = getSharedPreferences(AppConstants.OOSH_PREFERENCES, Context.MODE_PRIVATE);
// save to shared prefs firstName wher NAME_KEY is string to identified your saved data for later use - to load
sharedPreferences.putString(NAME_KEY,firstName).apply;
}
private void loadDataFromSharedPredferences(View view) {
// get shared preferences
SharedPreferences sharedPreferences = getSharedPreferences(AppConstants.OOSH_PREFERENCES, Context.MODE_PRIVATE);
// load data from shared prefs firstName wher NAME_KEY is string to identified data to load
String firstName = sharedPreferences.getString(NAME_KEY,firstName);
// get root view
View rootView = view.getRootView();
// find edit text widget on root view
EditText etFirstName = (EditText) rootView.findViewById(R.id.edit_first_name);
// set string to edit text widget
etFirstName.setText(firstName);
}
add on text change listener for edittext widgets
ps. you need to clarify - write a exactly steps of what you want to do achieve
load data from network ? then save ?
or save request date ?
or save result data ?
I have two strings that I want to save them I wrote the code as shown below
public class MainActivity extends Activity {
Button result;
EditText b951, b9511, sum95, t95, p95
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
LoadPreferences();
result = (Button)findViewById(R.id.btn1);
b951 = (EditText)findViewById(R.id.b951);
b9511 = (EditText)findViewById(R.id.b9511);
sum95 = (EditText)findViewById(R.id.sum95);
p95 = (EditText)findViewById(R.id.p95);
t95 = (EditText)findViewById(R.id.t95);
}
public void close (View v){
SavePreferences("p2b951", b951.getText().toString());
SavePreferences("p2b9511", b9511.getText().toString());
finish();
}
private void SavePreferences(String key, String value){
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(key, value);
editor.commit();
}
private void LoadPreferences(){
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
String p1b951 = sharedPreferences.getString("p2b951", "1");
String p1b9511 = sharedPreferences.getString("p2b9511", "1");
b951.setText(p1b951);
b9511.setText(p1b9511);
}
public void result (View v) {
try {
int ib951 = Integer.parseInt(b951.getText().toString());
int ib9511 = Integer.parseInt(b9511.getText().toString());
int iisum95 = (ib9511-ib951);
sum95.setText(String.valueOf(iisum95));
int isum95 = Integer.parseInt(sum95.getText().toString());
int ip95 = Integer.parseInt(p95.getText().toString());
int pp95 = (isum95*ip95);
t95.setText(String.valueOf(pp95));
}
catch (Exception e) {
e.printStackTrace();
}
}
}
But it seems there is a problem with this two lines:
b951.setText(p1b951);
b9511.setText(p1b9511);
I tried this
b951.setText(String.valueOf.p1b951);
b9511.setText(String.valueOf.p1b9511);
Also the problems still exist
When I open the application and when the loadpreferences is called the app will force close
The logcat show me that the error is with this two lines for sure it's just with the first line coz he didn't get the second but they are the same so they are wrong wroted
Any help??
Change onCreate() as follows:
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
result = (Button)findViewById(R.id.btn1);
b951 = (EditText)findViewById(R.id.b951);
b9511 = (EditText)findViewById(R.id.b9511);
sum95 = (EditText)findViewById(R.id.sum95);
p95 = (EditText)findViewById(R.id.p95);
t95 = (EditText)findViewById(R.id.t95);
LoadPreferences();
}
This is because you are using the EditTexts in the LoadPreferences() without calling findViewById() on the EditTexts.
You can follow and help from like codes. such as
Setting values in Preference:
SharedPreferences.Editor editor = getSharedPreferences(MODE_PRIVATE).edit();
editor.putString("name", "Elena");
editor.putInt("idName", 12);
editor.commit();
Retrieve data from preference:
SharedPreferences prefs = getSharedPreferences(MODE_PRIVATE);
String restoredText = prefs.getString("text", null);
if (restoredText != null) {
String name = prefs.getString("name", "No name defined");//"No name defined" is the default value.
int idName = prefs.getInt("idName", 0); //0 is the default value.
}
it any confused about this then follow this link
I have a login activity on app start and I need to check if use has used this app before and then I need to place the username and his password entered recently.
For this I have used shared preferences and used as shown below:
b.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
username= usernameET.getText().toString();
password= passwordET.getText().toString();
SharedPreferences data = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
data.edit().putString("username", username).commit();
data.edit().putString("password", password).commit();
}
});
Now I'm getting these values on app restart as shown below:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
SharedPreferences data = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
String storedUsername = data.getString("username", "");
String storedPassword = data.getString("password", "");
if (storedUsername != null && storedPassword != null) {
usernameET.setText(storedUsername);
passwordET.setText(storedPassword);
} else {
}
}
Coder, what is your issue? This is not working?
Please, tell us what is happening.
The implementation with SharedPreference would be my suggestion for you, is it not working?
I made a very simple implemention here and it works as usual...
On the onCreate:
SharedPreferences data = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
String storedUsername = data.getString("username", "");
String storedPassword = data.getString("password", "");
Toast.makeText(this, "saved Strings, user = " + storedUsername + " pass = " + storedPassword, Toast.LENGTH_LONG).show();
On the click of an ImageButton
#Override
public void onClick(View v) {
SharedPreferences data = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
data.edit().putString("username", "carlos").commit();
data.edit().putString("password", "password").commit();
}
Sounds like you are not setting the content on the SharedPreferences. Could you please make sure the action is executed?
Didn't really see a question asked but...
data.getString is going to return the default value if it is not set, which you're setting as a blank string(""). Either change your if:
if (!storedUsername.equals("") && !storedPassword.equals(""))
or change your default value to null
String storedUsername = data.getString("username", null);
String storedPassword = data.getString("password", null);