###Helper
MyDbHelper.java
public class MyDbHelper extends SQLiteOpenHelper {
public MyDbHelper(Context context){
super(context,"test.db",null,1);
}
@Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {
//create
sqLiteDatabase.execSQL("create table members(_id integer primary key autoincrement,name text,age integer)");
//init
sqLiteDatabase.execSQL("insert into members(name,age) values('hoge',23)");
}
@Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i2) {
//delete
sqLiteDatabase.execSQL("drop table if exist members");
//create
onCreate(sqLiteDatabase);
}
}
###Activity
MyActivity.java
public class MyActivity extends Activity {
ListView myListView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
//listview
myListView = (ListView)findViewById(R.id.myListView);
//db
MyDbHelper mDbHelper = new MyDbHelper(this);
SQLiteDatabase db = mDbHelper.getWritableDatabase();
//select
Cursor c = db.rawQuery("select * from members",null);
//adapterの準備
//表示するカラム名
String[] from = {"name","_id"};
//バインドするViewリソース
int[] to = {android.R.id.text1,android.R.id.text2};
//adapter生成
SimpleCursorAdapter adapter = new SimpleCursorAdapter(this,android.R.layout.simple_list_item_2,c,from,to,0);
//bindして表示
myListView.setAdapter(adapter);
//クリックしたとき各行のデータ(特に_id)を取得
myListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
//各要素を取得
String s1 = ((TextView)view.findViewById(android.R.id.text1)).getText().toString();
String s2 = ((TextView)view.findViewById(android.R.id.text2)).getText().toString();
Log.v("tama","position=" + s1);
Log.v("tama","position=" + s2);
}
});
//loop(いらない)
while(c.moveToNext()){
Log.v("tama", c.getString(c.getColumnIndex("name")));
}
}
}