public class MainActivity extends AppCompatActivity {
Mydata shp;
SQLiteDatabase sdb;
ListView lv;
Cursor cursor;
ListAdapter adapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lv=(ListView) findViewById(R.id.lv);
shp=new Mydata(this,"students",null,2);
sdb=shp.getWritableDatabase();
cursor=sdb.rawQuery("select * from students",null);
if(cursor!=null)
adapter=new SimpleCursorAdapter(this,R.layout.mylist,cursor,new String[]{"_id","sname"},new int[]{R.id.tid,R.id.tname});
lv.setAdapter(adapter);
}
}
//SQLiteOpenHelper是数据库管理的帮助类
public class Mydata extends SQLiteOpenHelper{
public static final String CREATE_BOOK = "create table Book("
+"id integer primart key autoincrement, "
+"author text,"
+"price real,"
+"pages integer,"
+"name text)";
public static final String CREATE_CATEGORY="create table Category("
+"id integer primary key autoincrement,"
+"category_name text,"
+"category_code integer)";
Context mcontext;
public Mydata(Context context, String name, SQLiteDatabase.CursorFactory factory,int version){
super(context,name,factory,version);
mcontext=context;
}
//在调getReadableDatabase或getWritableDatabase时,会判断指定的数据库是否存在,
// 不存在,onCreate()方法在初次生成数据库时才会被调用
@Override
public void onCreate(SQLiteDatabase db) {
//db.execSQL(CREATE_BOOK);
db.execSQL("create table if not exists students(_id text,sname text)");
// db.execSQL(CREATE_CATEGORY);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
switch (oldVersion){
case 1:
//db.execSQL(CREATE_CATEGORY);
db.execSQL("insert into students values('2','b')");
default:
}
onCreate(db);
}
}