2

For the code below I am trying to retrieve the shared preference, I think it saved correctly but when I go back to the login screen all the data is gone. I need it to remain when I go back to this screen. So i enter name, age and id into three separate lines on the profile page. Then i press the save button Then go to the page before by pressing back on the action bar. And when i go back to the profile page my info should still be there but its not Any help?

 package com.example.myprofile;

import android.content.Context;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import java.sql.Savepoint;

public class Profile extends AppCompatActivity {

             protected EditText NameEditText;
             protected EditText AgeEditText;
             protected EditText IDEditText;
             protected Button saveButton;
             protected Button settings_id;
             String name;
             String age;
             String id;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_profile);

        EditText mEdit = (EditText) findViewById(R.id.NameEditText);
        mEdit.setEnabled(false);
        EditText mEdit1 = (EditText) findViewById(R.id.AgeEditText);
        mEdit1.setEnabled(false);
        EditText mEdit2 = (EditText) findViewById(R.id.IDEditText);
        mEdit2.setEnabled(false);

        NameEditText = (EditText) findViewById(R.id.NameEditText);
        AgeEditText = (EditText) findViewById(R.id.AgeEditText);
        IDEditText = (EditText) findViewById(R.id.IDEditText);
        settings_id = (Button) findViewById(R.id.settings_id);
        saveButton = (Button) findViewById(R.id.SaveButton);



         SharedPreferences prefs = getSharedPreferences(getString(R.string.ProfileName), Context.MODE_PRIVATE);
         name = prefs.getString("userName", "");
         age = prefs.getString("userAge", "");
         id = prefs.getString("userID", "");


        saveButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {


                String name = NameEditText.getText().toString();
                String age = AgeEditText.getText().toString();
                String id = IDEditText.getText().toString();
                SharedPreferences sharedPreferences = getSharedPreferences(getString(R.string.ProfileName), Context.MODE_PRIVATE);
                SharedPreferences.Editor editor = sharedPreferences.edit();
                editor.putString(getString(R.string.ProfileName), name);
                editor.putString(getString(R.string.ProfileAge), age);
                editor.putString(getString(R.string.ProfileID), id);
                editor.apply();


                  if (Integer.parseInt(age) < 18)
                {
                    Toast toast1 = Toast.makeText(getApplicationContext(), "Invalid Age", Toast.LENGTH_LONG);
                    toast1.show();
                }
                  else if (!name.isEmpty() && !age.isEmpty() && !id.isEmpty())
                  {
                      getSupportActionBar().setDisplayHomeAsUpEnabled(true);
                      Toast toast = Toast.makeText(getApplicationContext(), "Name Saved!", Toast.LENGTH_LONG);
                      toast.show();
                  }
                  else
                {
                    Toast toast2 = Toast.makeText(getApplicationContext(), "Incomplete Info", Toast.LENGTH_LONG);
                    toast2.show();
                }


            }
        });

        getSupportActionBar().setDisplayHomeAsUpEnabled(false);

    }


    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.settings_id:
            {
                EditText mEdit = (EditText) findViewById(R.id.NameEditText);
                mEdit.setEnabled(true);
                EditText mEdit1 = (EditText) findViewById(R.id.AgeEditText);
                mEdit1.setEnabled(true);
                EditText mEdit2 = (EditText) findViewById(R.id.IDEditText);
                mEdit2.setEnabled(true);
                saveButton.setEnabled(Boolean.parseBoolean("True"));
            }
            default:
                return super.onOptionsItemSelected(item);

        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu, menu);
        return true;

    }
}
  • Have you passed correct key while retrieving data? for more info https://developer.android.com/training/data-storage/shared-preferences#java and https://stackoverflow.com/questions/23024831/android-shared-preferences-example – user3678528 Jan 28 '19 at 02:02
  • I think there is no need for multiple SharedPreferences and SharedPreferences.Editor objects as a single object will do the job just use different keys distinguish. And I thing you should read from the same SharedPreferences object with same key(* when initializing to read shared pass the same key what you used when saving) and I presume will solve your problem. – Ashutosh Sagar Jan 28 '19 at 04:39
  • In year 2020, Google has been released new data storage that is repleced of Shared Preference... It' is developed with "Kotlin" https://stackoverflow.com/questions/48001014/how-to-get-value-of-sharedpreferences-android/64301737#64301737 – Ucdemir Oct 11 '20 at 07:48

5 Answers5

1

To save data use the following code sample

name = NameEditText.getText().toString();
age = AgeEditText.getText().toString();
id = IDEditText.getText().toString();

SharedPreferences prefs = getSharedPreferences(
      "com.example.myprofile", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.putString("userName", name);
editor.putString("userAge", age);
editor.putString("userID", id);
editor.apply();

To retrieve the data use the following code sample

SharedPreferences prefs = getSharedPreferences(
    "com.example.myprofile", Context.MODE_PRIVATE);
name = prefs.getString("userName", "");
age = prefs.getString("userAge", "");
id = prefs.getString("userID", "");

Before onCreate method

String name;
String age;
String id;

Explanation:

  • The first parameter of getSharedPreferences is your package name, basically the first line in your code.
  • You don't need to create multiple SharedPreferences instances, one is enough
  • You don't need to create multiple SharedPreferences.Editor instances, one is also enough.
  • You might not want to use a random key, such as the user's username for saving data, since you would then need to pass the key to other activities through intents, and if you are going to do that, why not send the username instead of the key?
  • Use editor.apply() instead of editor.commit()
  • It is common to save data in onPause() and retrieve it in onResume(), so it can be useful to declare them global, to avoid writing extra lines of code.
S. Czop
  • 414
  • 5
  • 16
0

try (apply() at the end of the line):

editor.putString(getString(R.string.ProfileName), name).apply();
editor1.putString(getString(R.string.ProfileAge), age).apply();
editor2.putString(getString(R.string.ProfileID), id).apply();
0

You are using particular strings ( getString(R.string.ProfileAge) ....)to save data in shared preferences in private mode by using commit() or apply():-

SharedPreferences sharedPreferences1 = getSharedPreferences(getString(R.string.ProfileAge), Context.MODE_PRIVATE);
                SharedPreferences sharedPreferences2 = getSharedPreferences(getString(R.string.ProfileID), Context.MODE_PRIVATE);

But you are not trying to get that data using these strings in private mode you have to use :-

SharedPreferences sharedPref = getSharedPreferences(getString(R.string.ProfileAge), Context.MODE_PRIVATE);
String name = sharedPref.getString("key", "defaultValue");
DeePanShu
  • 378
  • 3
  • 9
0

For save

SharedPreferences pref = getSharedPreferences("Name", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putBoolean("keyname",true);
editor.putString("keyname","string value");
editor.putInt("keyname","int value");
editor.putFloat("keyname","float value");
editor.putLong("keyname","long value");
editor.commit();

For get

SharedPreferences pref = getSharedPreferences("Name", Context.MODE_PRIVATE);
pref.getString("keyname",null);
pref.getInt("keyname",0);
pref.getFloat("keyname",0);
pref.getBoolean("keyname",true);
pref.getLong("keyname",0);

For single delete

SharedPreferences pref = getSharedPreferences("Name", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = pref.edit();
editor.remove("keyname");
editor.commit();

For all delete

SharedPreferences pref = getSharedPreferences("Name", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = pref.edit();
editor.clear();
editor.commit();
Aftab Alam
  • 1,193
  • 9
  • 12
0

You can use share preference like this

To save data in preference

SharedPreferences share = getSharedPreferences("Data", Context.MODE_PRIVATE);
SharedPreferences.Editor edit = share.edit();
edit.putLong("user_id", 1);
edit.putString("token","1243434sfdfsf");
edit.commit();

To get data from preference

SharedPreferences share = getSharedPreferences("Data", Context.MODE_PRIVATE);
share.getLong("user_id", 0);
share.getString("token", "");

You can try this link for more details: Shared preference in android

Aneh Thakur
  • 968
  • 10
  • 18