我创建了一个数组。我希望能够保存它并在应用程序从内存关闭时加载它。 。我做了一些研究,发现你可以使用这些命令:SaveArrayListToSD和ReadArrayListFromSD。
但是,我不知道如何将这些与我的其余代码相关联...... 打开/关闭应用程序时如何保存和加载数组?
经过进一步的研究,我已经改变了对SQLite数据库的看法 - 如果它更容易,我不介意使用它。如果我要使用SQLite数据库,我该如何将我的arraylist保存到数据库中?
代码:
public class MainActivity extends ActionBarActivity {
@Override
protected void onCreate(Bundle savedInstanceState) { //Rendering the UI
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ListView myListView = (ListView)findViewById(R.id.myListView);
final EditText myEditText = (EditText)findViewById(R.id.myEditText);
//Creating Array of Strings
final ArrayList todoItems = new ArrayList();
final ArrayAdapter aa;
aa = new ArrayAdapter(this,android.R.layout.simple_list_item_1,
todoItems);
myListView.setAdapter(aa);
myEditText.setOnKeyListener(new OnKeyListener() {
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (event.getAction() == KeyEvent.ACTION_DOWN)
if (keyCode == KeyEvent.KEYCODE_DPAD_CENTER){
todoItems.add(0, myEditText.getText().toString());
aa.notifyDataSetChanged();
return true;
}
return false;
}
});
}
public static void SaveArrayListToSD(Context mContext, String savedArray, ArrayList todoItems) {
try {
FileOutputStream fos = mContext.openFileOutput(savedArray + ".dat", mContext.MODE_PRIVATE);
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(todoItems);
fos.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public static Object ReadArrayListFromSD(Context mContext,String savedArray){
try {
FileInputStream fis = mContext.openFileInput(savedArray + ".dat");
ObjectInputStream ois = new ObjectInputStream(fis);
Object obj= (Object) ois.readObject();
fis.close();
return obj;
} catch (Exception e) {
e.printStackTrace();
return new ArrayList<Object>();
}
}
}
答案 0 :(得分:0)
您可以使用内部存储将字符串保存在ArrayList中。 Here is more info on using internal storage.您可以在onStop或onDestory中写入数据,并在onCreate中读取数据。
答案 1 :(得分:0)
我可以为你写一个简单的例子。
初始化SQLite
SQLiteDatabase db = db=openOrCreateDatabase("yourDBName", Context.MODE_PRIVATE, null);
db.execSQL("CREATE TABLE IF NOT EXISTS Employee(id VARCHAR,name VARCHAR,email VARCHAR);");
db.execSQL("INSERT INTO student VALUES('"+idField.getText()+"','"+nameTextfield.getText()+"','"+emailtextfield.getText()+"');");
db.execSQL("DELETE FROM Employee WHERE id='"+idField.getText()+"'");
db.execSQL("UPDATE Employee SET name='"+nameTextfield.getText()+"',email='"+emailTextfield.getText()+"'WHERE id='"+idField.getText()+"'");
要从数据库中选择,请按照
进行操作Cursor c=db.rawQuery("SELECT * FROM Employee WHERE id='"+idField.getText()+"'", null);
if(c.moveToFirst()){
//String id = c.getString(0);
String name = c.getString(1);
String email = c.getString(2);
}