2016-07-28 86 views
-1

我有一個年齡輸入編輯文本,我想用戶的上一個輸入使用共享首選項(用於第一次輸入後)。我寫了下面的代碼,但它強制關閉。問題是什麼??使用共享首選項檢索數據

@Override 
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { 

//setting text for editText 
age_editText.setText(my_prefs.getInt("age_value", 0) + ""); //when i delete this part, it doesn't force close 

btn_calculate.setOnClickListener(new View.OnClickListener() { 
     @Override 
     public void onClick(View v) { 
       try { 
        Int age_value = Integer.parseInt(age_editText.getText().toString()); 
        //shared preferences 
        sharedPreferences my_prefs = getActivity().getPreferences(Context.MODE_PRIVATE); 
        SharedPreferences.Editor editor = my_prefs.edit(); 
        editor.putInt("age_value", age_value); 
        editor_bmi.commit(); 

       } catch (Exception e) { 
        Toast.makeText(getContext(), getString(R.string.please_fill_all_inputs), Toast.LENGTH_LONG).show(); 
       } 
     } 
    }); 
+2

發表您的日誌貓錯誤信息 – Arshak

回答

0

變化

sharedPreferences my_prefs = getActivity().getPreferences(Context.MODE_PRIVATE); 

sharedPreferences my_prefs = getActivity().getSharedPreferences("my_pref", Context.MODE_PRIVATE); 

,寫這上面

age_editText.setText(my_prefs.getInt("age_value", 0) + ""); 

適當的方式做到這一點。

@Override 
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { 

    sharedPreferences my_prefs getActivity().getSharedPreferences("my_pref", Context.MODE_PRIVATE); 
    age_editText.setText(my_prefs.getInt("age_value", 0) + ""); //when i delete this part, it doesn't force close 

    btn_calculate.setOnClickListener(new View.OnClickListener() { 
     @Override 
     public void onClick(View v) { 
      try { 

       Int age_value = Integer.parseInt(age_editText.getText().toString()); 

       SharedPreferences.Editor editor = my_prefs.edit(); 
       editor.putInt("age_value", age_value); 
       editor_bmi.commit(); 

      } catch (Exception e) { 
       Toast.makeText(getContext(), getString(R.string.please_fill_all_inputs), Toast.LENGTH_LONG).show(); 
      } 
     } 
    }); 
} 
+1

'sharedPreferences my_prefs = getActivity()。getSharedPreferences(「my_pref」,Context.MODE_PRIVATE);' 您錯過了'='來創建一個對象。 –

1

您需要,如下圖所示代替getPreferences()使用getSharedPreferences()

SharedPreferences sharedPreferences = getSharedPreferences("name", MODE_PRIVATE); 

注:getPreferences()getSharedPreferences()是返回不同的偏好對象的兩種不同的方法。

0

您可以通過以下方法保存你的年齡到SharedPreferences:

public void saveAge(int age_value) { 
     SharedPreferences pre = getSharedPreferences("my_age", MODE_PRIVATE); 
     SharedPreferences.Editor editor = pre.edit(); 
     editor.putInt("age_value", age_value); 
     editor.commit(); 
    } 

而當你想要得到你的年齡,使用此:

public int readAge() { 
     SharedPreferences pre = getSharedPreferences("my_age", MODE_PRIVATE); 
     int age = pre.getInt("age_value", 0); 
     return age; 
    }