在完成保存app的数据的时候直接采用了sqlite进行存储~
1,继承于sqliteopenhelper的类
public class MySqliteHelper extends SQLiteOpenHelper { public MySqliteHelper(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) { super(context, name, factory, version); } @Override public void onCreate(SQLiteDatabase db) { db.execSQL("create table if not exists my_table(_id integer primary key autoincrement,task text,date text,task_type text)"); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { } }2,主程序保存数据
MySqliteHelper mySqliteHelper=new MySqliteHelper(this,"mydata.db",null,1); //mydata.db的数据库
在这里自定义insert方法
//保存到数据库并返回主界面 iv1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String tasktext=et3.getText().toString(); String datetext=et2.getText().toString(); String task_typetext=et1.getText().toString(); ContentValues values=new ContentValues(); //通过key-value对的形式将数据插入到表中 values.put("task",tasktext); values.put("date", datetext); values.put("task_type", task_typetext); Insert(mySqliteHelper, values); Intent intent=new Intent(add_task.this,MainActivity.class); startActivity(intent); finish(); } });
//插入 public void Insert(MySqliteHelper mySqliteHelper,ContentValues values) { SQLiteDatabase db=mySqliteHelper.getWritableDatabase(); //获得可写数据表 db.insert("my_table", null, values); //用原有的sql语句将数据插入到表中 db.close(); }
3.读取
Cursor c获取到的还是用原生sql语句得到的
//获取数据库的所有信息到List public ArrayList<HashMap<String,Object>> getALLlist() { ArrayList<HashMap<String, Object>> list = new ArrayList<HashMap<String , Object>>(); SQLiteDatabase db = mySqliteHelper.getReadableDatabase(); Cursor c = db.query("my_table", new String[]{"_id", "task", "date", "task_type"}, null, null, null, null, null); if (c != null) { while (c.moveToNext()) { HashMap<String, Object> item = new HashMap<String, Object>(); item.put("_id", c.getInt(c.getColumnIndex("_id"))); item.put("task", c.getString(c.getColumnIndex("task"))); item.put("date", c.getString(c.getColumnIndex("date"))); item.put("task_type", c.getString(c.getColumnIndex("task_type"))); item.put("image", R.drawable.quan1); list.add(item); } } c.close(); return list; }4,修改
db.update("my_table",values,"_id="+String.valueOf(id),null);5.删除
//删除 bt2.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { new AlertDialog.Builder(task_read.this) .setPositiveButton("确定",new DialogInterface.OnClickListener(){ @Override public void onClick(DialogInterface dialog, int which) { db.delete("my_table","_id="+String.valueOf(id),null); Intent intent1=new Intent(task_read.this,MainActivity.class); startActivity(intent1); } }).setNegativeButton("取消", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { } }).setTitle("是否要删除").create().show(); } });