2016-07-28 42 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; 
    }