2016年4月10日日曜日

Sqliteを使ってみる(queryによる読み出し追加)

保存したデータを読み取ってみます
結果は、listで表示します

1.activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
    android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity"
    android:orientation="vertical">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:weightSum="1">

        <EditText
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/editText_dataText"
            android:layout_weight="1.04"
            android:text="good morning" />

        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Save"
            android:id="@+id/button_save"
            android:onClick="onButtonSaveClick" />

        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Load"
            android:id="@+id/button_load"
            android:onClick="onButtonLoadClick" />
    </LinearLayout>
    <!-- 読み込み用 -->
    <TextView
        android:layout_width="wrap_content" android:layout_height="wrap_content"
        android:id="@+id/labelList"
        />

</LinearLayout>

2.  FeedReadeerContract.java クラスを新規作成
package com.example.training.sqldatasave;

import android.provider.BaseColumns;

/**
 * Created by on 2016/04/02.
 */
public final class FeedReaderContract {
    // To prevent someone from accidentally instantiating the contract class,
    // give it an empty constructor.
    public FeedReaderContract() {}

    /* Inner class that defines the table contents */
    public static abstract class FeedEntry implements BaseColumns {
        public static final String TABLE_NAME = "entry";
        public static final String COLUMN_NAME_ENTRY_ID = "entryid";
        public static final String COLUMN_NAME_TITLE = "title";
        public static final String COLUMN_NAME_CONTENT = "content";
    }
}

3. FeedReaderDbHelper.javaを新規作成
package com.example.training.sqldatasave;

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

import com.example.training.sqldatasave.FeedReaderContract.FeedEntry;

/**
 * Created by 2016/04/02.
 */
public class FeedReaderDbHelper extends SQLiteOpenHelper {
    private static final String TEXT_TYPE = " TEXT";
    private static final String COMMA_SEP = ",";
    private static final String SQL_CREATE_ENTRIES =
            "CREATE TABLE " + FeedEntry.TABLE_NAME + " (" +
                    FeedEntry._ID + " INTEGER PRIMARY KEY," +
                    FeedEntry.COLUMN_NAME_ENTRY_ID + TEXT_TYPE + COMMA_SEP +
                    FeedEntry.COLUMN_NAME_TITLE + TEXT_TYPE + COMMA_SEP +
                    FeedEntry.COLUMN_NAME_CONTENT + TEXT_TYPE  +
            " )";
    private static final String SQL_DELETE_ENTRIES =
            "DROP TABLE IF EXISTS " + FeedEntry.TABLE_NAME;

    // If you change the database schema, you must increment the database version.
    public static final int DATABASE_VERSION = 1;
    public static final String DATABASE_NAME = "FeedReader.db";

    public FeedReaderDbHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    public void onCreate(SQLiteDatabase db) {
        db.execSQL(SQL_CREATE_ENTRIES);
    }

    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // This database is only a cache for online data, so its upgrade policy is
        // to simply to discard the data and start over
        db.execSQL(SQL_DELETE_ENTRIES);
        onCreate(db);
    }

    public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        onUpgrade(db, oldVersion, newVersion);
    }
    public void insertDb(SQLiteDatabase db, int id, String title, String content){
        // Create a new map of values, where column names are the keys
        ContentValues values = new ContentValues();
        values.put(FeedEntry.COLUMN_NAME_ENTRY_ID, id);
        values.put(FeedEntry.COLUMN_NAME_TITLE, title);
        values.put(FeedEntry.COLUMN_NAME_CONTENT, content);

        // Insert the new row, returning the primary key value of the new row
        long newRowId;
        newRowId = db.insert(
                FeedEntry.TABLE_NAME,
                null, //FeedEntry.COLUMN_NAME_NULLABLE,     // "COLUMN_NAME_NULLABLE"は認識されないみたい
                values);
        if(newRowId < 0){
            Log.e("sample", "insertDbでエラー発生");
        }
    }
}

4. MainActivity.javaはこんな感じに
package com.example.training.sqldatasave;

import android.app.Activity;
import android.database.Cursor;
import android.database.sqlite.SQLiteAbortException;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.example.training.sqldatasave.FeedReaderContract.FeedEntry;


public class MainActivity extends Activity {

    TextView tv;
    /*
    DatabaseHelper mDbHelper;
    SQLiteDatabase mDb;
    */

    FeedReaderDbHelper feedReaderDbHelper;
    SQLiteDatabase db;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        tv = (TextView)findViewById(R.id.editText_dataText);
        // mDbHelper = new DatabaseHelper(this);
        // mDb = mDbHelper.getWritableDatabase();

        feedReaderDbHelper = new FeedReaderDbHelper(this);
        db = feedReaderDbHelper.getWritableDatabase();
    }

    @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);
    }

    public void onButtonSaveClick(View v){
        Toast.makeText(MainActivity.this, "Saveクリックした", Toast.LENGTH_SHORT).show();
        // mDbHelper.insert(mDb, 1,  tv.getText().toString(), 0);
        feedReaderDbHelper.insertDb(db, 1, "title1", tv.getText().toString());
        tv.setText("Saveクリック");
    }

    public void onButtonLoadClick(View v){
        Toast.makeText(MainActivity.this, "Loadクリックした", Toast.LENGTH_SHORT).show();
        tv.setText("Loadクリック");
        StringBuilder text = new StringBuilder();

        SQLiteDatabase db = feedReaderDbHelper.getReadableDatabase();
        try {
            Cursor cursor = db.query(FeedEntry.TABLE_NAME,  // table
                    new String[]{FeedEntry.COLUMN_NAME_ENTRY_ID, FeedEntry.COLUMN_NAME_TITLE, FeedEntry.COLUMN_NAME_CONTENT},   // cols
                    null,           // selection
                    null,           // selection args
                    null,           // group by
                    null,           // having
                    "_id DESC"  // "_id ASC"           // order by(_idをDESCで降順指定)            );
            cursor.moveToFirst();
            do {
                text.append("," + cursor.getString(1));
                text.append("," + cursor.getString(2));
                // text.append("," + cursor.getString(3));
                text.append("\n");
            } while (cursor.moveToNext());
        } catch (SQLiteAbortException e){
            Toast.makeText(MainActivity.this, "SQL Exception発生", Toast.LENGTH_SHORT).show();
        } finally {
    }
        TextView lblList = (TextView)this.findViewById(R.id.labelList);
        lblList.setText(text);
    }
}

0 件のコメント:

コメントを投稿