我无法从共享的偏好中获得价值

时间:2017-01-25 22:09:49

标签: android sharedpreferences

我的主要活动如下。正如在这段代码中m试图设置各种年龄的值,empid等但是当我加载值时,我无法获得ice1和ice2的值,而其他值如age和empid很容易被检索。我无法找到错误。

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        SharedPrefManager.Init(this);

        try{SharedPrefManager.LoadFromPref();}
        catch (Exception e)
        {
            Toast.makeText(this, "No Previous Data ", Toast.LENGTH_LONG).show();
        }
        editTextName = (EditText) findViewById(R.id.editTextEnterName);
        editTextEmpID = (EditText) findViewById(R.id.editTextEnterEid);
        editTextAge = (EditText) findViewById(R.id.editTextEnterAge);
        editTextBloodGroup = (EditText) findViewById(R.id.editTextEnterBloodGroup);
        editTextICE1 = (EditText) findViewById(R.id.editTextEnterICE1);
        editTextICE2 = (EditText) findViewById(R.id.editTextEnterICE2);

        buttonLoad = (Button) findViewById(R.id.buttonLoad);
        try {
            buttonLoad.performClick();
        } catch(Exception e)
        {
            Toast.makeText(this,"This is not working",Toast.LENGTH_LONG).show();
        }
    }

    public void onClickStore(View v)

    {


        if (editTextAge.getText().toString().trim().length() > 0 && editTextName.getText().toString().trim().length() > 0 && editTextEmpID.getText().toString().trim().length() > 0 && editTextBloodGroup.getText().toString().trim().length() > 0 && editTextICE1.getText().toString().trim().length() > 0  && editTextICE2.getText().toString().trim().length() > 0) {
            //get user input first, then store. we will use our SharedPrefManager Class functions
            //convert EditText to string
            String srtTextName = editTextName.getText().toString();
            String srtTextEmpID = editTextEmpID.getText().toString();
            String strTextAge = editTextAge.getText().toString();
            String srtTextBloodGroup = editTextBloodGroup.getText().toString();
            String strTextICE2 = editTextICE2.getText().toString();
             String iTextICE1=editTextICE1.getText().toString();

            if (0 != srtTextName.length())
                SharedPrefManager.SetName(srtTextName); // need string value so convert it
            if (0 != srtTextEmpID.length())
                SharedPrefManager.SetEmployeeID(Integer.parseInt(srtTextEmpID)); // need string value so convert it
            if (0 != strTextAge.length())
                SharedPrefManager.SetAge(Integer.parseInt(strTextAge)); // need integer value so convert it

            if (0 != srtTextBloodGroup.length())
                SharedPrefManager.SetBloodGroup(srtTextBloodGroup); // need string value so convert it

            if (0 != iTextICE1.length())
                SharedPrefManager.SetICE1(Integer.parseInt(iTextICE1)); // need string value so convert it
            if (0 != strTextICE2.length())
                SharedPrefManager.SetICE2(Integer.parseInt(strTextICE2));


            //now save all to shared pref, all updated values are now available in SharedPrefManager class, as we set above
            SharedPrefManager.StoreToPref();

            //reset all fields to blank before load and update from sharedpref
            EditText tv = null;
            tv = (EditText) findViewById(R.id.editTextEnterName);
            tv.setText("");
            tv = (EditText) findViewById(R.id.editTextEnterEid);
            tv.setText("");
            tv = (EditText) findViewById(R.id.editTextEnterAge);
            tv.setText("");
            tv = (EditText) findViewById(R.id.editTextEnterBloodGroup);
            tv.setText("");
            tv = (EditText) findViewById(R.id.editTextEnterICE1);
            tv.setText("");
            tv = (EditText) findViewById(R.id.editTextEnterICE2);
            tv.setText("");
            Toast.makeText(this, "Ice2 "+ strTextICE2, Toast.LENGTH_LONG).show();

           //Toast.makeText(this, "Ice1 "+iTextICE1, Toast.LENGTH_LONG).show();
           // Toast.makeText(this, "Data Successfully Stored ", Toast.LENGTH_LONG).show();
         //   SharedPrefManager.LoadFromPref();
            //After saving data,data should be displayed also,so here we will call load button functionality explicitly
          //  try{ buttonLoad.performClick(); }
           // catch (Exception e){  Toast.makeText(this, "Your Who Am I Section is having no details!", Toast.LENGTH_LONG).show();}
        }

        else{
            Toast.makeText(this, "Please Fill all fields! :)", Toast.LENGTH_LONG).show();
        }
    }


    public void onClickLoad(View v) {
        String strTextName, strTextBloodGroup;
        int iTextAge, iTextEmpID, iTextICE1, iTextICE2;

              //Get all values from SharedPrefference file

              SharedPrefManager.LoadFromPref(); // all values are loaded into corresponding variables of SharedPrefManager class
              //Now get the values form SharedPrefManager class using it's static functions.

              strTextName = SharedPrefManager.GetName();
              iTextEmpID = SharedPrefManager.GetEmployeeID();
              iTextAge = SharedPrefManager.GetAge();
              strTextBloodGroup = SharedPrefManager.GetBloodGroup();
              iTextICE1 = SharedPrefManager.GetICE1();
              iTextICE2 = SharedPrefManager.GetICE2();
              //Now we can show these persistent values on our activity (GUI)
              EditText tv = null;
              tv = (EditText) findViewById(R.id.editTextEnterName);
              tv.setText(strTextName);
              tv = (EditText) findViewById(R.id.editTextEnterEid);
              tv.setText(String.valueOf(iTextEmpID));
              tv = (EditText) findViewById(R.id.editTextEnterAge);
              tv.setText(String.valueOf(iTextAge));
              tv = (EditText) findViewById(R.id.editTextEnterBloodGroup);
              tv.setText(strTextBloodGroup);
              tv = (EditText) findViewById(R.id.editTextEnterICE1);
              tv.setText(String.valueOf(iTextICE1));
              tv = (EditText) findViewById(R.id.editTextEnterICE2);
              tv.setText(String.valueOf(iTextICE2));



       // Toast.makeText(this,"Ice 1"+iTextICE1,Toast.LENGTH_LONG).show();
        //Toast.makeText(this,"Ice 2"+iTextICE2,Toast.LENGTH_LONG).show();

    // Toast.makeText(this, "This Data is Used in Beacon!", Toast.LENGTH_LONG).show();
    }

    public void onClickDelete(View v){

        SharedPrefManager.DeleteAllEntriesFromPref();
        clearForm((ViewGroup) findViewById(R.id.whoamiform));
        EditText tv = null;
        tv = (EditText) findViewById(R.id.editTextEnterName);
        tv.setText("");
        tv = (EditText) findViewById(R.id.editTextEnterEid);
        tv.setText("");
        tv = (EditText) findViewById(R.id.editTextEnterAge);
        tv.setText("");
        tv = (EditText) findViewById(R.id.editTextEnterBloodGroup);
        tv.setText("");
        tv = (EditText) findViewById(R.id.editTextEnterICE1);
        tv.setText("");
        tv = (EditText) findViewById(R.id.editTextEnterICE2);
        tv.setText("");
        Toast.makeText(this, "Data Successfully Deleted! You may now enter new Values!", Toast.LENGTH_LONG).show();

    }


    // Clears all EditTexts on Screen! Like a Boss :D
    // Use this method to clear form after entries are deleted from database as values were persisting on front-end
    private void clearForm(ViewGroup group)
    {
        for (int i = 0, count = group.getChildCount(); i < count; ++i) {
            View view = group.getChildAt(i);
            if (view instanceof EditText) {
                ((EditText)view).setText("");
            }
            if(view instanceof ViewGroup && (((ViewGroup)view).getChildCount() > 0))
                clearForm((ViewGroup)view);
        }
    }

}

public class SharedPrefManager {

    //this is your shared preference file name, in which we will save data
    public static final String MY_EMP_PREFS = "MySharedPref";

    //saving the context, so that we can call all
    //shared pref methods from non activity classes.
    //because getSharedPreferences required the context.
    //but in activity class we can call without this context
    private static Context  mContext;

    // will get user input in below variables, then will store in to shared pref
    private static String   mName           = "";
    private static int  mEid;
    private static int      mAge  ;
    private static String   mBlood          = "";
    private static int  mICE1;
    private static int      mICE2;

    public static void Init(Context context)
    {
        mContext        = context;
    }
    public static void LoadFromPref()
    {
        SharedPreferences settings  = mContext.getSharedPreferences(MY_EMP_PREFS, 0);
        // Note here the 2nd parameter 0 is the default parameter for private access,
        //Operating mode. Use 0 or MODE_PRIVATE for the default operation,
        mName           = settings.getString("Name",""); //
        // 1st parameter Name is the key and 2nd parameter is the default if data not found
        mEid            = settings.getInt("EmpID",0);
        mAge            = settings.getInt("Age",0);
        mBlood          = settings.getString("Blood Group",""); //
        // 1st parameter Name is the key and 2nd parameter is the default if data not found
        mICE1           = settings.getInt("ICE1",0);
        mICE2           = settings.getInt("ICE2",0);
    }
    public static void StoreToPref()
    {
        // get the existing preference file
        SharedPreferences settings = mContext.getSharedPreferences(MY_EMP_PREFS, 0);
        //need an editor to edit and save values
        SharedPreferences.Editor editor = settings.edit();
        editor.putString("Name",mName); // Name is the key and mName is holding the value
        editor.putInt("EmpID",mEid);// EmpID is the key and mEid is holding the value
        editor.putInt("Age", mAge); // Age is the key and mAge is holding the value
        editor.putString("Blood Group",mBlood); // Name is the key and mName is holding the value
        editor.putInt("ICE 1",mICE1);// EmpID is the key and mEid is holding the value
        editor.putInt("ICE 2", mICE2); // Age is the key and mAge is holding the value
        //final step to commit (save)the changes in to the shared pref
        editor.commit();
    }

    public static void DeleteSingleEntryFromPref(String keyName)
    {
        SharedPreferences settings = mContext.getSharedPreferences(MY_EMP_PREFS, 0);
        //need an editor to edit and save values
        SharedPreferences.Editor editor = settings.edit();
        editor.remove(keyName);
        editor.commit();
    }

    public static void DeleteAllEntriesFromPref()
    {
        SharedPreferences settings = mContext.getSharedPreferences(MY_EMP_PREFS, 0);
        //need an editor to edit and save values
        SharedPreferences.Editor editor = settings.edit();
        editor.clear();
        editor.commit();
    }

    public static void SetName(String name)
    {
        mName=name;
    }
    public static void SetEmployeeID(int empID)
    {
        mEid = empID ;
    }
    public static void SetAge(int age)
    {
        mAge = age;
    }

    public static String GetName()
    {
        return mName ;
    }
    public static int GetEmployeeID()
    {
        return mEid ;
    }
    public static int GetAge()
    {
        return mAge ;
    }


    public static void SetBloodGroup(String blood)
    {
        mBlood =blood;
    }
    public static void SetICE1(int i1)
    {
        mICE1 = i1 ;
    }
    public static void SetICE2(int i2)
    {
        mICE2 = i2;
    }

    public static String GetBloodGroup()
    {

        return mBlood ;
    }
    public static int GetICE1()
    {
        return mICE1 ;
    }
    public static int GetICE2()
    {
        return mICE2 ;
    }
}

2 个答案:

答案 0 :(得分:2)

您在python.exe方法中拼错了ICE 1ICE 2 ..

因此,您在保存中将其称为LoadFromPref()ICE1,在加载方法中将其称为ICE2ICE 1。你必须留意空间。

修改

ICE 2

public static void LoadFromPref() { SharedPreferences settings = mContext.getSharedPreferences(MY_EMP_PREFS, 0); // Note here the 2nd parameter 0 is the default parameter for private access, //Operating mode. Use 0 or MODE_PRIVATE for the default operation, mName = settings.getString("Name",""); // // 1st parameter Name is the key and 2nd parameter is the default if data not found mEid = settings.getInt("EmpID",0); mAge = settings.getInt("Age",0); mBlood = settings.getString("Blood Group",""); // // 1st parameter Name is the key and 2nd parameter is the default if data not found mICE1 = settings.getInt("ICE1",0); mICE2 = settings.getInt("ICE2",0); } public static void StoreToPref() { // get the existing preference file SharedPreferences settings = mContext.getSharedPreferences(MY_EMP_PREFS, 0); //need an editor to edit and save values SharedPreferences.Editor editor = settings.edit(); editor.putString("Name",mName); // Name is the key and mName is holding the value editor.putInt("EmpID",mEid);// EmpID is the key and mEid is holding the value editor.putInt("Age", mAge); // Age is the key and mAge is holding the value editor.putString("Blood Group",mBlood); // Name is the key and mName is holding the value editor.putInt("ICE 1",mICE1);// EmpID is the key and mEid is holding the value editor.putInt("ICE 2", mICE2); // Age is the key and mAge is holding the value //final step to commit (save)the changes in to the shared pref editor.commit(); } 中,您在单词StoreToPref与您的号码之间有一个空格,在ICE中没有空格。所以就像这样调整它:

LoadFromPref

答案 1 :(得分:0)

在静态变量中保存值不是最好的方法。

如果想要拥有&#34; getName,getAge&#34;这是一种变体。方法。 第二种变体更短。

1

public class SharedPrefManager {

    public static final String MY_EMP_PREFS = "MySharedPref";
    public static final String NAME = "name";
    public static final String EMP_ID = "empID";
    public static final String AGE = "age";
    public static final String BLOOD_GROUP = "bloodGroup";
    public static final String ICE_1 = "ice1";
    public static final String ICE_2 = "ice2";
    public static final String DEFAULT_STRING = "default";
    public static final int DEFAULT_INT = 0;

    static SharedPreferences sharedPreferences;

    public static void init(Context context) {
        sharedPreferences = context.getSharedPreferences(MY_EMP_PREFS, 0);
    }

    public static void deleteSingleEntryFromPref(String key) {
        sharedPreferences.edit().remove(key).commit();
    }

    public static void deleteAll() {
        sharedPreferences.edit().clear().commit();
    }

    public static void setName(String name) {
        sharedPreferences.edit().putString(NAME, name).commit();
    }

    public static void setEmployeeID(int empID) {
        sharedPreferences.edit().putInt(EMP_ID, empID).commit();
    }

    public static void setAge(int age) {
        sharedPreferences.edit().putInt(AGE, age).commit();
    }

    public static String getName() {
        return sharedPreferences.getString(NAME, DEFAULT_STRING);
    }

    public static int getEmployeeID() {
        return sharedPreferences.getInt(EMP_ID, DEFAULT_INT);
    }

    public static int getAge() {
        return sharedPreferences.getInt(AGE, DEFAULT_INT);
    }


    public static void setBloodGroup(String blood) {
        sharedPreferences.edit().putString(BLOOD_GROUP, blood);
    }

    public static void setICE1(int i1) {
        sharedPreferences.edit().putInt(ICE_1, i1).commit();
    }

    public static void setICE2(int i2) {
        sharedPreferences.edit().putInt(ICE_2, i2).commit();
    }

    public static String getBloodGroup() {
        return sharedPreferences.getString(BLOOD_GROUP, DEFAULT_STRING);
    }

    public static int getICE1() {
        return sharedPreferences.getInt(ICE_1, DEFAULT_INT);
    }

    public static int getICE2() {
        return sharedPreferences.getInt(ICE_2, DEFAULT_INT);
    }
}

2

public class SharedPrefManager {
    public static final String MY_EMP_PREFS = "MySharedPref";
    public static final String NAME = "name";
    public static final String EMP_ID = "empID";
    public static final String AGE = "age";
    public static final String BLOOD_GROUP = "bloodGroup";
    public static final String ICE_1 = "ice1";
    public static final String ICE_2 = "ice2";
    public static final String DEFAULT_STRING = "default";
    public static final int DEFAULT_INT = 0;

    static SharedPreferences sharedPreferences;

    public static void init(Context context) {
        sharedPreferences = context.getSharedPreferences(MY_EMP_PREFS, 0);
    }

    public static void deleteSingleEntryFromPref(String key) {
        sharedPreferences.edit().remove(key).commit();
    }

    public static void deleteAll() {
        sharedPreferences.edit().clear().commit();
    }

    public static void setInt(String key, int value) {
        sharedPreferences.edit().putInt(key, value).commit();
    }

    public static int getInt(String key) {
        return sharedPreferences.getInt(key, DEFAULT_INT);
    }

    public static void setString(String key, String value) {
        sharedPreferences.edit().putString(key, value).commit();
    }

    public static String getString(String key) {
        return sharedPreferences.getString(key, DEFAULT_STRING);
    }
}

比在你的活动类中只调用:

SharedPrefManager.init(this);
// ...

SharedPrefManager.getInt(SharedPrefManager.ICE_1);
SharedPrefManager.getString(SharedPrefManager.BLOOD_GROUP);
// ...