カテゴリー
SugiBlog Webデザイナー・プログラマーのためのお役立ちTips

データベースの内容をListViewに表示 [Android]

この記事は最終更新日から1年以上経過しています。

ListAdpterを使って、データベースの内容を一括で簡単にリスト表示
CursorとListAdpterを組み合わせて使うときは、Cursorオブジェクトに「_id」列を含んでいないといけません。

【HelloSqliteActivity】

import android.app.Activity;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;

public class HelloSqliteActivity extends Activity {

  SQLiteDatabase db;
  Cursor c;

  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    MySqlite helper = new MySqlite(this);
    db = helper.getReadableDatabase();
    c = db.query(SerializeData.tblName,
        new String[] { "_id", "number", "latitude", "longitude" },
        null, null, null, null, null);

    startManagingCursor(c); //リソースの扱いをActivityに委ねます

    c.moveToFirst();

    ListAdapter adapter = new SimpleCursorAdapter(this,
      R.layout.list_item, c,
        new String[] { "_id", "number" },
        new int[] { R.id._id, R.id.number });

    ListView lv = (ListView)findViewById(R.id.list);
    lv.setAdapter(adapter);

  }

  @Override
  protected void onDestroy() {
      super.onDestroy();
    c.close();
    db.close();
  }
    
}

【main.xml】

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

  <ListView
    android:id="@+id/list"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" />

</LinearLayout>

【list_item】

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="horizontal"
    android:padding="8px" >

    <TextView
        android:id="@+id/_id"
        android:layout_width="105sp"
        android:layout_height="wrap_content"
        android:textSize="35sp" />

    <TextView
        android:id="@+id/number"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="6px"
        android:textSize="35sp" />

</LinearLayout>
この記事がお役に立ちましたらシェアお願いします
18,320 views

コメントを残す

メールアドレスが公開されることはありません。 が付いている欄は必須項目です