2016-09-20 7 views
-3

Я сохраняю некоторые данные в SharedPreferences, но когда я нажимаю кнопку «Назад» и снова перехожу к профилю, данные очищаются.
Как хранить данные с помощью SharedPreferences?Извлечение данных из общих предварительных условий

package www.edukeen.in.eduaspire; 
    public class Profile extends AppCompatActivity { 
    EditText editTextName, editDOB, editphone, editcity, editclass, editboard, editschool, edithobbies, editachievements; 
    Button buttonSave; 

    public static final String MyPREFERENCES = "MyPrefs" ; 
    public static final String Name = "nameKey"; 
    public static final String DOB = "DOBKey"; 
    public static final String Phone = "phoneKey"; 
    public static final String City = "cityKey"; 
    public static final String Class = "classKey"; 
    public static final String Board = "boardKey"; 
    public static final String School = "schoolKey"; 
    public static final String Hobbies = "hobbiesKey"; 
    public static final String Achievements = "achievementsKey"; 
    SharedPreferences sharedpreferences; 

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

     editTextName = (EditText) findViewById(R.id.editTextName); 
     editDOB = (EditText) findViewById(R.id.editDOB); 
     editphone = (EditText) findViewById(R.id.editphone); 
     editcity = (EditText) findViewById(R.id.editcity); 
     editclass = (EditText) findViewById(R.id.editclass); 
     editboard = (EditText) findViewById(R.id.editboard); 
     editschool = (EditText) findViewById(R.id.editschool); 
     edithobbies = (EditText) findViewById(R.id.edithobbies); 
     editachievements = (EditText) findViewById(R.id.editachievements); 

     buttonSave=(Button)findViewById(R.id.buttonSave); 
     sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE); 


     buttonSave.setOnClickListener(new View.OnClickListener() { 
      @Override 
      public void onClick(View v) { 
       String Name = editTextName.getText().toString(); 
       String DOB = editDOB.getText().toString(); 
       String Phone = editphone.getText().toString(); 
       String City = editcity.getText().toString(); 
       String Class = editclass.getText().toString(); 
       String Board = editboard.getText().toString(); 
       String School = editschool.getText().toString(); 
       String Hobbies = edithobbies.getText().toString(); 
       String Achievements = editachievements.getText().toString(); 

       SharedPreferences.Editor editor = sharedpreferences.edit(); 

       editor.putString(Name, Name); 
       editor.putString(DOB, DOB); 
       editor.putString(Phone, Phone); 
       editor.putString(City, City); 
       editor.putString(Class, Class); 
       editor.putString(Board, Board); 
       editor.putString(School, School); 
       editor.putString(Hobbies, Hobbies); 
       editor.putString(Achievements, Achievements); 

       editor.commit(); 
       Toast.makeText(Profile.this,"Data saved",Toast.LENGTH_LONG).show(); 

      String name = sharedpreferences.getString("name", "No name"); 
      String dob = sharedpreferences.getString("DOB", ""); 
      String phone = sharedpreferences.getString("phone", ""); 
      String city = sharedpreferences.getString("city", ""); 
      String clas = sharedpreferences.getString("class", ""); 
      String board = sharedpreferences.getString("board", ""); 
      String school = sharedpreferences.getString("school", ""); 
      String hobbies = sharedpreferences.getString("hobbies", ""); 
      String achievements = sharedpreferences.getString("achievements", ""); 
      } 
     }); 
    } 
} 

И что делать, если я хочу получить эти данные в своей базе данных?
Я уже подписал пользователь, используя firebase.

+0

использование editor.apply(); Ошибка – DKV

+0

- вы используете одни и те же данные для ключа и значения при сохранении данных, а также используете зарезервированные ключевые слова. – Meenal

+1

см. Http://stackoverflow.com/a/29840449/2006803. И добавьте «это». в ключевой части метода putString –

ответ

0

Используйте это, возможно, это поможет вам.

public class SharedPreferenceManager { 

String APP_PREF = "APP_PREF"; 

public void setData(Context context, String key, int value) { 
    SharedPreferences.Editor editor = context.getSharedPreferences(APP_PREF, Context.MODE_PRIVATE).edit(); 
    editor.putInt(key, value); 
    editor.apply(); 
} 

public void setData(Context context, String key, long value) { 
    SharedPreferences.Editor editor = context.getSharedPreferences(APP_PREF, Context.MODE_PRIVATE).edit(); 
    editor.putLong(key, value); 
    editor.apply(); 
} 

public void setData(Context context, String key, String value) { 
    SharedPreferences.Editor editor = context.getSharedPreferences(APP_PREF, Context.MODE_PRIVATE).edit(); 
    editor.putString(key, value); 
    editor.apply(); 
} 

public void setData(Context context, String key, float value) { 
    SharedPreferences.Editor editor = context.getSharedPreferences(APP_PREF, Context.MODE_PRIVATE).edit(); 
    editor.putFloat(key, value); 
    editor.apply(); 
} 

public void setData(Context context, String key, boolean value) { 
    SharedPreferences.Editor editor = context.getSharedPreferences(APP_PREF, Context.MODE_PRIVATE).edit(); 
    editor.putBoolean(key, value); 
    editor.apply(); 
} 

public String getString(Context context, String key) { 
    SharedPreferences prefs = context.getSharedPreferences(APP_PREF, Context.MODE_PRIVATE); 
    return prefs.getString(key, null); 
} 

public int getInt(Context context, String key) { 
    SharedPreferences prefs = context.getSharedPreferences(APP_PREF, Context.MODE_PRIVATE); 
    return prefs.getInt(key, 0); 
} 

public float getFloat(Context context, String key) { 
    SharedPreferences prefs = context.getSharedPreferences(APP_PREF, Context.MODE_PRIVATE); 
    return prefs.getFloat(key, 0); 
} 

public long getLong(Context context, String key) { 
    SharedPreferences prefs = context.getSharedPreferences(APP_PREF, Context.MODE_PRIVATE); 
    return prefs.getLong(key, 0); 
} 

public boolean getBool(Context context, String key) { 
    SharedPreferences prefs = context.getSharedPreferences(APP_PREF, Context.MODE_PRIVATE); 
    return prefs.getBoolean(key, false); 
} 
0

Вы можете сделать общий класс для все общего prefrences работать как этот

public class SharedPrefManager { 

    public static SharedPreferences getSharedPref(Context mContext) { 
     SharedPreferences pref = mContext.getSharedPreferences(Constants.SETTINGS, Context.MODE_PRIVATE); 

     return pref; 
    } 

    public static void setPrefVal(Context mContext, String key, String value) { 
     if(key!=null){ 
     Editor edit = getSharedPref(mContext).edit(); 
     edit.putString(key, value); 
     edit.commit(); 
     } 
    } 

    public static void setIntPrefVal(Context mContext, String key, int value) { 
     if(key!=null){ 
      Editor edit = getSharedPref(mContext).edit(); 
      edit.putInt(key, value); 
      edit.commit(); 
     } 
    } 

    public static void setLongPrefVal(Context mContext, String key, Long value) { 
     if(key!=null){ 
      Editor edit = getSharedPref(mContext).edit(); 
      edit.putLong(key, value); 
      edit.commit(); 
     } 
    } 

    public static void setBooleanPrefVal(Context mContext, String key, boolean value) { 
     if(key!=null){ 
      Editor edit = getSharedPref(mContext).edit(); 
      edit.putBoolean(key, value); 
      edit.commit(); 
     } 
    } 


    public static String getPrefVal(Context mContext, String key) { 
     SharedPreferences pref = getSharedPref(mContext); 
     String val = ""; 
     try { 
      if (pref.contains(key)) 
       val = pref.getString(key, ""); 
      else 
       val = ""; 
     }catch (Exception e){ 
      e.printStackTrace(); 
     } 
     return val; 
    } 

    public static int getIntPrefVal(Context mContext, String key) { 
     SharedPreferences pref = getSharedPref(mContext); 
     int val = 0; 
     try { 
     if(pref.contains(key)) val = pref.getInt(key, 0); 
     }catch (Exception e){ 
      e.printStackTrace(); 
     } 
     return val; 
    } 

    public static Long getLongPrefVal(Context mContext, String key) { 
     SharedPreferences pref = getSharedPref(mContext); 
     Long val = null; 
     try{ 
     if(pref.contains(key)) val = pref.getLong(key, 0); 
    }catch (Exception e){ 
     e.printStackTrace(); 
    } 
     return val; 
    } 

    public static boolean getBooleanPrefVal(Context mContext, String key) { 
     SharedPreferences pref = getSharedPref(mContext); 
     boolean val = false; 
     try{ 
     if(pref.contains(key)) val = pref.getBoolean(key, false); 

     }catch (Exception e){ 
      e.printStackTrace(); 
     } 
     return val; 
    } 


    public static boolean containkey(Context mContext,String key) 
    { 
     SharedPreferences pref = getSharedPref(mContext); 
     return pref.contains(key); 
    } 

    public static void saveTestScreens(Context mContext, String key, 
      String value) { 
     Editor edit = getSharedPref(mContext).edit(); 
     edit.putString(key, value); 
     edit.commit(); 
    } 

    public static String getTestScreens(Context mContext, String key) { 
     SharedPreferences pref = getSharedPref(mContext); 
     String val = ""; 
     if (pref.contains(key)) 
      val = pref.getString(key, ""); 
     else 
      val = ""; 
     return val; 
    } 
} 

, а затем на основе ваших требований, и получать данные из общего prefrences

0

попробовать с этим кодом

EditText editTextName, editDOB, editphone, editcity, editclass, editboard, editschool, edithobbies, editachievements; 
Button buttonSave; 

public static final String MyPREFERENCES = "MyPrefs"; 
public static final String Name = "nameKey"; 
public static final String DOB = "DOBKey"; 
public static final String PHONE = "phoneKey"; 
public static final String City = "cityKey"; 
public static final String CLASS = "classKey"; 
public static final String BOARD = "boardKey"; 
public static final String SCHOOL = "schoolKey"; 
public static final String HOBBIES = "hobbiesKey"; 
public static final String Achievements = "achievementsKey"; 
public String name, dOB, phone, city, classText, borad, school, hobbies, achievements; 
SharedPreferences sharedpreferences; 

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


    editTextName = (EditText) findViewById(R.id.editTextName); 
    editDOB = (EditText) findViewById(R.id.editDOB); 
    editphone = (EditText) findViewById(R.id.editphone); 
    editcity = (EditText) findViewById(R.id.editcity); 
    editclass = (EditText) findViewById(R.id.editclass); 
    editboard = (EditText) findViewById(R.id.editboard); 
    editschool = (EditText) findViewById(R.id.editschool); 
    edithobbies = (EditText) findViewById(R.id.edithobbies); 
    editachievements = (EditText) findViewById(R.id.editachievements); 

    buttonSave = (Button) findViewById(R.id.buttonSave); 
    sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE); 

    showText(); 
    buttonSave.setOnClickListener(new View.OnClickListener() { 
     @Override 
     public void onClick(View v) { 
      String name = editTextName.getText().toString(); 
      String DOBText = editDOB.getText().toString(); 
      String Phone = editphone.getText().toString(); 
      String city = editcity.getText().toString(); 
      String classText = editclass.getText().toString(); 
      String Board = editboard.getText().toString(); 
      String School = editschool.getText().toString(); 
      String Hobbies = edithobbies.getText().toString(); 
      String achievements = editachievements.getText().toString(); 

      SharedPreferences.Editor editor = sharedpreferences.edit(); 

      editor.putString(Name, name); 
      editor.putString(DOB, DOBText); 
      editor.putString(PHONE, Phone); 
      editor.putString(City, city); 
      editor.putString(CLASS, classText); 
      editor.putString(BOARD, Board); 
      editor.putString(SCHOOL, School); 
      editor.putString(HOBBIES, Hobbies); 
      editor.putString(Achievements, achievements); 

      editor.commit(); 
      Toast.makeText(Test.this, "Data saved", Toast.LENGTH_LONG).show(); 
     } 
    }); 
} 

private void showText() { 
    try { 
     SharedPreferences.Editor editor = sharedpreferences.edit(); 
     editTextName.setText(sharedpreferences.getString(Name, "")); 
     editDOB.setText(sharedpreferences.getString(DOB, "")); 
     editphone.setText(sharedpreferences.getString(PHONE, "")); 
     editcity.setText(sharedpreferences.getString(City, "")); 
     editclass.setText(sharedpreferences.getString(CLASS, "")); 
     editboard.setText(sharedpreferences.getString(BOARD, "")); 
     editschool.setText(sharedpreferences.getString(SCHOOL, "")); 
     edithobbies.setText(sharedpreferences.getString(HOBBIES, "")); 
     editachievements.setText(sharedpreferences.getString(Achievements, "")); 
    } catch (Exception e) { 
     e.printStackTrace(); 
    } 
} 
+1

Большое спасибо. Этот код работает отлично ... –

Смежные вопросы