如何使用共享首选项保存多个数据?

时间:2018-12-27 09:08:41

标签: java android sharedpreferences

我正在制作一个应用,其中在本次活动中,我试图从用户那里获取数据并使用共享的首选项进行保存。但是单击注册按钮后,应用崩溃。 enter image description here

这是SignUpActivity.java文件-

package com.example.abinas.myapplication;

import android.content.Context;
import android.content.SharedPreferences; 
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText; 
import android.widget.RadioButton;
import android.widget.RadioGroup;

public class SignUpActivity extends AppCompatActivity {

private EditText e3;
private EditText e4;
private EditText e5;
private EditText e6;
private Button b2;
private RadioGroup rg;
private RadioButton rb;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_sign_up);
    rg = (RadioGroup)findViewById(R.id.radioroup);
    e3 = (EditText)findViewById(R.id.editText3);
    e4 = (EditText)findViewById(R.id.editText4);
    e5 = (EditText)findViewById(R.id.editText5);
    e6 = (EditText)findViewById(R.id.editText6);
    b2 = (Button)findViewById(R.id.button2);
    int selected_id = rg.getCheckedRadioButtonId();
    rb = (RadioButton)findViewById(selected_id);
}

public void onButtonClick(View view){

    final SharedPreferences pref;
    pref = getSharedPreferences("user_info",Context.MODE_PRIVATE);
    SharedPreferences.Editor edit = pref.edit();
    edit.putString("gender",rb.getText().toString());
    edit.putString("username",e4.getText().toString());
    edit.putString("name",e3.getText().toString());
    edit.putString("password",e5.getText().toString());
    edit.putInt("phone",Integer.parseInt(e6.getText().toString()));
    edit.apply();
    edit.commit();
    //b2.setText("SAVED");
    //b2.setClickable(false);
}
}

要成功保存数据,应进行哪些更改?

3 个答案:

答案 0 :(得分:2)

  1. 创建一个公共类SharedPreference Manager和一个Keystring类,它将包含多个数据,例如名称,用户名,密码,电话号码。
  2. 然后在项目中的任何地方创建此类的对象
  3. 在任何地方轻松获得和放置价值

    SharedPreferenceManager ##

    import android.content.Context; 导入android.content.SharedPreferences; 导入android.content.SharedPreferences.Editor;

公共类SharedPreferenceManager {

protected Context mContext;


protected SharedPreferences mSettings;
protected Editor mEditor;

public SharedPreferenceManager(Context ctx, String prefFileName) {
    mContext = ctx;

    mSettings = mContext.getSharedPreferences(prefFileName,
            Context.MODE_PRIVATE);
    mEditor = mSettings.edit();
}

/***
 * Set a value for the key
 ****/
public void setValue(String key, String value) {
    mEditor.putString(key, value);
    mEditor.commit();
}


/***
 * Set a value for the key
 ****/
public void setValue(String key, int value) {
    mEditor.putInt(key, value);
    mEditor.commit();
}

/***
 * Set a value for the key
 ****/
public void setValue(String key, double value) {
    setValue(key, Double.toString(value));
}

/***
 * Set a value for the key
 ****/
public void setValue(String key, long value) {
    mEditor.putLong(key, value);
    mEditor.commit();
}

/****
 * Gets the value from the settings stored natively on the device.
 *
 * @param defaultValue Default value for the key, if one is not found.
 **/
public String getValue(String key, String defaultValue) {
    return mSettings.getString(key, defaultValue);
}

public int getIntValue(String key, int defaultValue) {
    return mSettings.getInt(key, defaultValue);
}

public long getLongValue(String key, long defaultValue) {
    return mSettings.getLong(key, defaultValue);
}

/****
 * Gets the value from the preferences stored natively on the device.
 *
 * @param defValue Default value for the key, if one is not found.
 **/
public boolean getValue(String key, boolean defValue) {
    return mSettings.getBoolean(key, defValue);
}

public void setValue(String key, boolean value) {
    mEditor.putBoolean(key, value);
    mEditor.commit();
}



/**
 * Clear all the preferences store in this {@link android.content.SharedPreferences.Editor}
 */
public boolean clear() {
    try {
        mEditor.clear().commit();
        return true;
    } catch (Exception e) {
        e.printStackTrace();
        return false;
    }
}

/**
 * Removes preference entry for the given key.
 *
 * @param key
 */
public void removeValue(String key) {
    if (mEditor != null) {
        mEditor.remove(key).commit();
    }
}

}

KeyString

public class KeyString {
public static String PREFERENCE_NAME ="APP_PREF";
public static String NAME="NAME";
public static String USER_NAME="USER_NAME";
public static String PHONE_NUMBER="PHONE_NUMBER";
public static String PASSWORD="PASSWORD";
public static String USER_ID="USER_ID";

}

在项目中任何地方的任何活动中

private SharedPreferenceManager preferenceManager=new new SharedPreferenceManager(context, KeyString.PREFERENCE_NAME);

现在设置一些值

preferenceManager.setValue(KeyString.PHONE_NUMBER,"017xxxxx");

从偏好中获取数据

String phoneNumber=preferenceManager.getValue(KeyString.PHONE_NUMBER,""); //default value ""

通过此方法,您可以设置并获取所需数量的变量和值。只需添加keyString并进行play.happy编码即可。

答案 1 :(得分:0)

您的代码同时具有edit.apply()edit.commit()。只能使用其中之一。

答案 2 :(得分:0)

您只需保存每个EditText值,并在下次重新加载Activity时检索它们。

public class SignUpActivity extends AppCompatActivity {

private EditText e3;
private EditText e4;
private EditText e5;
private EditText e6;
private Button b2;
private RadioGroup rg;
private RadioButton rb;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_sign_up);
    rg = (RadioGroup)findViewById(R.id.radioroup);
    e3 = (EditText)findViewById(R.id.editText3);
    e4 = (EditText)findViewById(R.id.editText4);
    e5 = (EditText)findViewById(R.id.editText5);
    e6 = (EditText)findViewById(R.id.editText6);
    b2 = (Button)findViewById(R.id.button2);
    int selected_id = rg.getCheckedRadioButtonId();
    rb = (RadioButton)findViewById(selected_id);

    // In case no value is already saved, use a Default Value
editText1.setText(savednotes.getString("editText1", "Default Value 1"));
        editText2.setText(savednotes.getString("editText2", "Default Value 2"));


}


        // Save the changes upon button click

    public void onButtonClick(View view){

            SharedPreferences.Editor preferencesEditor = savedFields.edit();
            if(e3.getText().length() > 0) // Not empty
                 preferencesEditor.putString("editText1", editText1.getText());
            if(e4.getText().length() > 0) // Not empty
                 preferencesEditor.putString("editText2", editText2.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();
            }
        }

    };

注意:我向您展示了两个编辑文本,您可以以类似的方式申请其他文本。谢谢。