【问题标题】:Taking user selection in a spinner, storing it in sharedPreferences, and using it in another activity在微调器中获取用户选择,将其存储在 sharedPreferences 中,并在另一个活动中使用它
【发布时间】:2014-06-10 01:04:46
【问题描述】:

我需要用户选择一家餐厅,得到一个包含不同选择的相当大的列表。 然后我需要保存该选择,最好保存在 sharedPreferences 之类的东西中。并在另一个活动中使用它来显示 excel 文档中的一些数据。

目前我的代码如下所示:

在 onCreate 中:

resturantSpinner = (Spinner) findViewById(R.id.resturantSpinner);
     // Create an ArrayAdapter using the string array and a default spinner layout
    ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,
            R.array.resturant_arrays, android.R.layout.simple_spinner_item);
    // Specify the layout to use when the list of choices appears
    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
   // Apply the adapter to the spinner
    resturantSpinner.setAdapter(adapter);

onItemSelected:

public void onItemSelected(View view) {
      int userChoice = resturantSpinner.getSelectedItemPosition();
      SharedPreferences sharedPref = getSharedPreferences("resturantFile",0);
      SharedPreferences.Editor prefEditor = sharedPref.edit();
      prefEditor.putInt("userChoiceSpinner", userChoice);
      prefEditor.commit();
}

在另一个活动中检索数据:

resturantTextView = (TextView) findViewById(R.id.resturantChoice);

    Intent intent = getIntent();

    SharedPreferences sharedPref = getSharedPreferences("resturantFile",MODE_PRIVATE);
    int resturantChoice = sharedPref.getInt("userChoiceSpinner",-1);

    resturantTextView.setText("" + resturantChoice);

我只是使用 textView 来查看它保存的样子,目前它只显示 -1

编辑:还不如添加这个,userChoice 值为 0。

【问题讨论】:

  • 你能调试一下看看 userChoice 有什么价值吗?
  • userCoice 值为 0..
  • 在进行第二个活动之前,您是否在第一个活动的其他任何地方调用 sharedPref.edit() ?调用 .edit() 会重置 sharedPref 编辑器。

标签: java android sharedpreferences android-spinner


【解决方案1】:

试试这个:

像这样添加SharedPreferences sharedPref = getSharedPreferences("resturantFile",Activity.MODE_PRIVATE) 而不是
SharedPreferences sharedPref = getSharedPreferences("resturantFile",0)

例如:保存方式

SharedPreferences sp = getSharedPreferences("your_prefs", Activity.MODE_PRIVATE);
SharedPreferences.Editor editor = sp.edit();
editor.putInt("your_int_key", yourIntValue);
editor.commit();

在另一个activity中获取数据的方式:

SharedPreferences sp = getSharedPreferences("your_prefs", Activity.MODE_PRIVATE);
int myIntValue = sp.getInt("your_int_key", -1);

如果这不适合你,那么试试这个: 将默认值-1改为0,

int myIntValue = sp.getInt("your_int_key", 0);

有关更多信息,请使用此question

【讨论】:

  • 在保存到 SharedPreferences 之前,您是否检查了 userChoice 变量以确保它不为空?
  • 很高兴听到您解决了它。如果此答案有助于为您解决问题,您能否将其标记为已接受的答案。
猜你喜欢
  • 1970-01-01
  • 2023-03-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-08-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多