1

我正在尝试使用共享首选项数据创建一个列表视图,并且每次我必须添加一个数据来重新填充 listivew,但它只获取输入的最新数据,因此列表视图中的显示往往具有1 row only every time.

代码片段:

String strSavedMem1 = sharedPreferences.getString("food", "");   
String[] values = new String[] { strSavedMem1 }; //That you got from your intent bundle  
LVAdapter adapter = new LVAdapter(this, R.layout.foodlist, values);
setListAdapter(adapter);

LVAdapter.java

public class LVAdapter extends ArrayAdapter<String> {
  private final Context context;
  private final String[] values;

  public LVAdapter(Context context, int foodlist, String[] values) {
    super(context, R.layout.foodlist, values);
    this.context = context;
    this.values = values;
  }


@Override
  public View getView(int position, View convertView, ViewGroup parent) {
    LayoutInflater inflater = (LayoutInflater) context
        .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    View rowView = inflater.inflate(R.layout.foodlist, parent, false);
    TextView textView = (TextView) rowView.findViewById(R.id.foods);        
    textView.setText(values[position]);     
    return rowView;
  }
} 

将值存储在共享首选项中的代码。

 String item_content1 = cursor.getString(cursor.getColumnIndex(SQLiteAdapter.KEY_FOODNAME));
    food.setText(item_content1);

    SavePreferences("food", food.getText().toString());
    LoadPreferences();

      }};

  protected void SavePreferences(String key, String value) {
        // TODO Auto-generated method stub
        SharedPreferences sharedPreferences = getSharedPreferences("MY_SHARED_PREF", MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.putString(key, value);
        editor.commit();

    }  
  protected void LoadPreferences() {
        // TODO Auto-generated method stub
        SharedPreferences sharedPreferences = getSharedPreferences("MY_SHARED_PREF", MODE_PRIVATE);
        String strSavedMem1 = sharedPreferences.getString("food", "");
        food.setText(strSavedMem1);

    }

我必须在哪里更改上述代码,才能从共享偏好中获取全部数据?

4

2 回答 2

1

String[] values = new String[] { strSavedMem1 }总是有一个元素。尝试找到将更多元素添加到您的数组中。

我假设您的 sharedpreferences 中有更多元素

String strSavedMem1 = sharedPreferences.getString("food1", ""); 
String strSavedMem2 = sharedPreferences.getString("food2", ""); 
String strSavedMem3 = sharedPreferences.getString("food3", ""); 

String[] values = new String[] { strSavedMem1, strSavedMem2 ,strSavedMem3}
于 2013-03-09T04:43:38.817 回答
1

请使用 Shared Preferences 进行应用程序相关设置,同时避免将大数据列表存储在 Shared Preferences 中。 Shared Preferences 的物理路径是 /data/data/YOUR_PACKAGE_NAME/ ,这样会减少你的手机内存。

于 2013-03-09T05:59:05.287 回答