我必须以哪种顺序编码?

时间:2015-11-21 01:05:27

标签: java android sharedpreferences

在我的应用中,用户可以在微调器中选择一些内容,并在单击按钮时收到带有所选文本的Toast。

现在在我的情况下,当他点击按钮时,会弹出一个吐司,但是空了。我认为吐司的共享偏好不会实现,因为它们不会在代码行的开头被识别出来?看看:

.
.
   @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        prefs = this.getSharedPreferences("spinnerSelection", 0);
        btn = (Button) findViewById(R.id.send);

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

                spinnergipfeli.setSelection(prefs.getInt("spinnerSelection", 0));
                Context context = getApplicationContext();
                CharSequence text = (thetime);
                int duration = Toast.LENGTH_SHORT;

                Toast toast = Toast.makeText(context, text, duration);
                toast.show();
            }
    });
.
.

以及稍后的代码:

@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
    TextView myText = (TextView) view;
    editor = prefs.edit();
    selectedPosition = spinnergipfeli.getSelectedItemPosition();
    String Text = spinnergipfeli.getSelectedItem().toString();
    editor.putInt("spinnerSelection", selectedPosition);
    editor.putString("thetime", Text);
    editor.commit();
}    
@Override
public void onNothingSelected(AdapterView<?> parent) {
}

1 个答案:

答案 0 :(得分:1)

您的代码运行正常。您只需检索“ thetime ”条目即可获取您要查找的字符串:

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

        spinnergipfeli.setSelection(prefs.getInt("spinnerSelection", 0));
        Context context = getApplicationContext();
        String text = prefs.getString("thetime", "default empty value");
        Toast.makeText(context, text, Toast.LENGTH_LONG).show();
    }
});