共享首选项以创建Listview

时间:2013-03-09 04:41:28

标签: android listview sharedpreferences

我正在尝试使用共享首选项数据创建列表视图,并且每次我都要添加数据来重新填充listivew,但它只获取最近输入的数据,因此listview中的显示趋向于{ {1}}。

代码段:

1 row only every time

LVAdapter.java

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);

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

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;
  }
} 

我必须在上面的代码中进行更改,才能从共享首选项中获取整个数据?

2 个答案:

答案 0 :(得分:1)

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

我假设你的共享偏好中有更多元素

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

String[] values = new String[] { strSavedMem1, strSavedMem2 ,strSavedMem3}

答案 1 :(得分:1)

请使用共享首选项进行与应用程序相关的设置,并避免在共享首选项中存储大数据列表。共享首选项的物理路径是 / data / data / YOUR_PACKAGE_NAME /这样会降低手机内存。