我正在尝试使用 SharedPreferences 来存储来自 ArrayList 的数据。但我迷路了。我正在使用 for 循环来检索数据并将其存储在列表视图中。此外,当我按下按钮时,首选项会被存储。
package com.example.todolist;
import java.util.ArrayList;
import android.app.Activity;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnKeyListener;
import android.view.Window;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;
public class MainActivity extends Activity {
ArrayList<String> items;
ArrayAdapter<String> adapter;
ListView l;
EditText et;
Button bt, bt2;
Object ob;
int i = 0, k = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_main);
et = (EditText) findViewById(R.id.editText1);
bt = (Button) findViewById(R.id.button1);
bt2 = (Button) findViewById(R.id.button2);
l = (ListView) findViewById(R.id.listView1);
items = new ArrayList<String>();
adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, items);
l.setAdapter(adapter);
bt.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
action();
SharedPreferences prfs = getSharedPreferences("PREFS", i);
Editor edit = prfs.edit();
edit.putString("" + i, et.getText().toString());
edit.putInt("counter", i);
edit.commit();
et.setText("");
k = prfs.getInt("counter", 0);
i = i + 1;
}
});
for (i = 0; i < k + 1; i++) {
SharedPreferences prfs = getSharedPreferences("PREFS", i);
items.add(0, (String) prfs.getString("" + i, "Null"));
adapter.notifyDataSetChanged();
}
}
private void action() {
// TODO Auto-generated method stub
if (!("".equals(et.getText().toString()))) {
ob = et.getText().toString();
items.add(0, (String) ob);
adapter.notifyDataSetChanged();
} else {
Toast.makeText(getBaseContext(), "Field should not be empty!",
Toast.LENGTH_LONG).show();
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}