我正在開發一個項目,我需要創建一個動態列表。爲此,我使用共享首選項永久性地將值存儲在列表中。但是當我重新啓動項目時,我進入不是退出。我嘗試了很多時間,但問題沒有解決。
這是我的代碼。
NumberListActivity.javaAndroid中的動態列表使用SharedPreferences
public class NumberListActivity extends Activity {
ListView numList;
ArrayList<String> list = new ArrayList<String>();
ArrayAdapter<String> adapter;
public static final String Place = "placeKey";
Button btnAdd;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.custom_list);
numList = (ListView) findViewById(R.id.list);
btnAdd = (Button) findViewById(R.id.btnAdd);
adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, list);
numList.setAdapter(adapter);
btnAdd.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
SharedPreferences preferences = getSharedPreferences("place",
Context.MODE_PRIVATE);
SharedPreferences.Editor spEditor = preferences.edit();
EditText edit = (EditText) findViewById(R.id.txtItem);
spEditor.putString("Value", edit.getText().toString());
spEditor.commit();
list.add(preferences.getString("Value", ""));
adapter.notifyDataSetChanged();
}
});
list.toArray();
}
}
custom_list.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<EditText
android:id="@+id/txtItem"
android:layout_width="240dp"
android:layout_height="wrap_content"
android:inputType="text" />
<Button
android:id="@+id/btnAdd"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_toRightOf="@id/txtItem" />
<ListView
android:id="@+id/list"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="@id/txtItem" />
<TextView
android:id="@+id/empty"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="@id/txtItem"
android:gravity="center_horizontal" />
</RelativeLayout>
@NirHartmann:這是存儲在列表中值的完整代碼。 –
@NirHartmann:這兩行添加列表中的數據。** list.add(preferences.getString(「Value」,「」)); adapter.notifyDataSetChanged(); ** –
@ZiaUrRehman查看我的回答 – Hariharan