27
24

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

sqliteで取得した値をListViewに表示する簡単な例

Last updated at Posted at 2014-10-06

###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")));
        }
    }
}

27
24
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
27
24

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?