2015年4月3日金曜日

データベースを作成し、ListViewでデータ一覧表示する

DatabaseOpenHelper:データベース作成
中身は、
 データベース名:database_foods
 テーブル名:table_foods
 カラム:ID、商品名、値段

MainActivity:ListViewで一覧表示

DatabaseOpenHelper.java
package lesson.studyandroid_02;

import android.content.ContentValues;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

public class DatabaseOpenHelper extends SQLiteOpenHelper {
    // データベース名
    private static final String DB_NAME  = "database_foods";
    // テーブル名
    public static final String TABLE_NAME = "table_foods";
    // カラム名
    public static final String COLUMN_ID = "_id";
    public static final String COLUMN_NAME = "name";
    public static final String COLUMN_PRICE = "price";
    // 初期 サンプルデータ
    private String[][] datas = new String[][]{
            {"大根", "250"},
            {"長ネギ", "230"},
            {"牛乳", "200"},
            {"食パン", "180"},
            {"バナナ", "280"},
    };

    public DatabaseOpenHelper(Context context) {
        super(context, DB_NAME, null, 1);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.beginTransaction();
        try {
            // テーブルの生成
            StringBuilder sb = new StringBuilder();
            sb.append("create table " + TABLE_NAME + " (");
            sb.append(COLUMN_ID + " integer primary key,");
            sb.append(COLUMN_NAME + " text,");
            sb.append(COLUMN_PRICE + " text");
            sb.append(")");
            db.execSQL(sb.toString());
            db.setTransactionSuccessful();
        } finally {
            db.endTransaction();
        }
        // サンプルデータの投入
        db.beginTransaction();
        try {
            for (String[] data: datas) {
                ContentValues values = new ContentValues();
                values.put(COLUMN_NAME, data[0]);
                values.put(COLUMN_PRICE, data[1]);
                db.insert(TABLE_NAME, null, values);
            }
            db.setTransactionSuccessful();
        } finally {
            db.endTransaction();
        }
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

    }
}

MainActivity.java
package lesson.studyandroid_02;

import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;


public class MainActivity extends ActionBarActivity {
    protected SQLiteDatabase db;
    protected Cursor cursor;
    protected ListView foodsList;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        db = (new DatabaseOpenHelper(this)).getWritableDatabase();
        foodsList = (ListView)findViewById(R.id.list);
        cursor = db.query(DatabaseOpenHelper.TABLE_NAME,
                null, null, null, null, null, null);
        cursor.moveToFirst();

        foodsList.setAdapter(new SimpleCursorAdapter(this,
                android.R.layout.simple_expandable_list_item_2,
                cursor,
                new String[] {
                        DatabaseOpenHelper.COLUMN_NAME,
                        DatabaseOpenHelper.COLUMN_PRICE },
                new int[] {android.R.id.text1, android.R.id.text2},
                0);
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}

activity_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:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:id="@+id/list" />
</LinearLayout>

AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="lesson.studyandroid_02" >

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

string.xml
<resources>
    <string name="app_name">StudyAndroid_02</string>
    <string name="action_settings">Settings</string>
</resources>

0 件のコメント:

コメントを投稿