android 資料庫 SQLite
阿新 • • 發佈:2018-11-15
public class SqliteHelper extends SQLiteOpenHelper{ private static String db_name="mydb.db"; private static int db_version=1; public SqliteHelper(Context context){ super(context,db_name,null,db_version); } public SqliteHelper(Context context, String name, SQLiteDatabase.CursorFactory factory, intversion) { super(context, name, factory, version); } @Override public void onCreate(SQLiteDatabase db) { String sql="create table person(_id Integer primary key autoincrement,name varchar(10),age Integer) "; db.execSQL(sql); } @Override public voidonUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { } }
private ListView lv; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); SqliteHelper sqliteHelper=newSqliteHelper(MainActivity.this); SQLiteDatabase db = sqliteHelper.getReadableDatabase(); lv= (ListView) findViewById(R.id.lv); Button button=new Button(mContext); if (AppUtils.isInstallApp("com.unking.personexercisedemo")){ Log.i("tag","安裝了這個軟體"); } button.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { return false; } }); String path=Environment.getExternalStorageDirectory().getAbsolutePath()+ File.separator+"mydb.db"; Cursor cursor = db.rawQuery("select * from person", null); SimpleCursorAdapter adapter=new SimpleCursorAdapter(this,R.layout.list_item,cursor, new String[]{"_id","name","age"}, new int[]{R.id.tv_id,R.id.tv_name,R.id.tv_age}, SimpleCursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER); //flag_register_content_observer //3.將介面卡資料展示到控制元件 lv.setAdapter(adapter); // insert(db); // update(db); // queryData(db); } private void insert(SQLiteDatabase db){ //插入資料SQL語句 String stu_sql="insert into person(name,age) values('xiaoming',20)"; //執行SQL語句 db.execSQL(stu_sql); } private void update(SQLiteDatabase db){ //修改SQL語句 String sql = "update person set name = 654321 where _id = 1"; //執行SQL db.execSQL(sql); } //查詢資料,在資料庫中 private void queryData(SQLiteDatabase db){ Cursor cursor = db.query("person", new String[]{"_id,name,age"}, "_id>1", null, null, null, null); List<Person> persons = cursorToList(cursor); for (Person p:persons) { Log.i("tag",p.getName()); } db.close(); } private List<Person> cursorToList(Cursor cursor){ List<Person>cursorList=new ArrayList<>(); while (cursor.moveToNext()){ int ColumnIndexid = cursor.getColumnIndex("_id"); int id = cursor.getInt(ColumnIndexid); int ColumnIndexname = cursor.getColumnIndex("name"); String name = cursor.getString(ColumnIndexname); int ColumnIndexage = cursor.getColumnIndex("age"); int age = cursor.getInt(ColumnIndexage); Person person=new Person(id,name,age); cursorList.add(person); } return cursorList; }