SQLiteを使ってデータの保存をしてみよう。
プロジェクトの作成
1.新規プロジェクトとしてPrefAppを作成する。
Assetsフォルダの作成
2.新しいプロジェクトを作成したらまずassetsフォルダを作ろう。
appをオプションクリックしてNew->Folder->AssetsFolderを選択する。

3.Assetsフォルダはsrc/main/の直下に配置されなければならない。そこに置くか?というダイアログがでるのでチェックしてfinish

4.フォルダが配置されたことを確認

5.今回はcsvファイルを元にデータベースを作成する。以下のファイルをダウンロードしAssetsフォルダに配置する。
レイアウトの作成
6.activity_main.xmlを以下のように編集する。
01 | < RelativeLayout xmlns:android = "http://schemas.android.com/apk/res/android" |
02 | xmlns:tools = "http://schemas.android.com/tools" |
03 | android:layout_width = "match_parent" |
04 | android:layout_height = "match_parent" |
06 | tools:context = ".MainActivity" > |
09 | android:id = "@+id/linearLayout1" |
10 | android:layout_width = "match_parent" |
11 | android:layout_height = "wrap_content" |
12 | android:background = "@android:drawable/btn_default" |
13 | android:orientation = "vertical" > |
16 | android:layout_width = "match_parent" |
17 | android:layout_height = "wrap_content" > |
20 | android:id = "@+id/textView1" |
21 | android:layout_width = "wrap_content" |
22 | android:layout_height = "match_parent" |
23 | android:background = "@android:drawable/btn_default" |
24 | android:gravity = "center" |
26 | android:textAppearance = "?android:attr/textAppearanceLarge" /> |
29 | android:layout_width = "match_parent" |
30 | android:layout_height = "match_parent" |
31 | android:orientation = "vertical" > |
34 | android:id = "@+id/imageButton1" |
35 | android:layout_width = "match_parent" |
36 | android:layout_height = "wrap_content" |
37 | android:background = "@android:drawable/btn_default" |
38 | android:onClick = "btUp" |
39 | android:src = "@android:drawable/arrow_up_float" /> |
42 | android:id = "@+id/tvId" |
43 | android:layout_width = "match_parent" |
44 | android:layout_height = "wrap_content" |
45 | android:background = "@android:drawable/edit_text" |
46 | android:gravity = "center" |
48 | android:textSize = "32sp" /> |
51 | android:id = "@+id/imageButton2" |
52 | android:layout_width = "match_parent" |
53 | android:layout_height = "wrap_content" |
54 | android:background = "@android:drawable/btn_default" |
55 | android:onClick = "btDown" |
56 | android:src = "@android:drawable/arrow_down_float" /> |
61 | android:id = "@+id/button1" |
62 | android:layout_width = "match_parent" |
63 | android:layout_height = "wrap_content" |
64 | android:background = "@android:drawable/btn_default" |
65 | android:onClick = "btSearch" |
70 | android:id = "@+id/tvResult" |
71 | android:layout_width = "match_parent" |
72 | android:layout_height = "match_parent" |
73 | android:layout_alignLeft = "@+id/linearLayout1" |
74 | android:layout_below = "@+id/linearLayout1" |
75 | android:background = "@android:drawable/alert_dark_frame" |
76 | android:gravity = "center" |
78 | android:textColor = "@android:color/white" |
79 | android:textSize = "20sp" /> |
7.以下のようになればOKだ。

クラスの作成
8.Pref.javaを以下のように作成する。(パッケージを環境に合わせて付与すること)
01 | package com.example.xxxxxx; |
07 | public Pref( int id,String name,String cap){ |
13 | public String toString(){ |
14 | return String.format( "県名:%s\n県庁所在地%s" , name,cap); |
DAOの作成
9.PrefDAO.javaを以下のように作成
01 | import android.database.Cursor; |
02 | import android.database.sqlite.SQLiteDatabase; |
03 | import android.database.sqlite.SQLiteException; |
04 | import android.database.sqlite.SQLiteStatement; |
09 | private SQLiteDatabase db; |
11 | public void setDb(SQLiteDatabase db) { |
15 | public void createTable() { |
16 | String sql = "CREATE TABLE prefs( " + |
23 | public void createData(List<Pref> list) { |
26 | this .db.compileStatement( "INSERT INTO prefs VALUES(?,?,?)" ); |
28 | this .db.beginTransaction(); |
30 | stt.bindLong( 1 , p.id); |
31 | stt.bindString( 2 , p.name); |
32 | stt.bindString( 3 , p.cap); |
36 | this .db.setTransactionSuccessful(); |
37 | } catch (SQLiteException e){ |
46 | public Pref findOne( int id){ |
47 | String sql= "SELECT * FROM prefs WHERE id=?" ; |
48 | String[] param={String.valueOf(id)}; |
49 | Cursor cursor= this .db.rawQuery(sql,param); |
51 | if (cursor.moveToFirst()){ |
52 | String name=cursor.getString(cursor.getColumnIndex( "name" )); |
53 | String cap=cursor.getString(cursor.getColumnIndex( "cap" )); |
54 | return new Pref(id,name,cap); |
61 | public void dropTable(){ |
62 | String sql = "DROP TABLE IF EXISTS prefs" ; |
SQLiteOpenHelperの作成
10.SQLiteOpenHelperクラスを継承したOpenHelper.javaを以下のように作成する。
01 | import android.content.Context; |
02 | import android.content.res.AssetManager; |
03 | import android.database.sqlite.SQLiteDatabase; |
04 | import android.database.sqlite.SQLiteOpenHelper; |
06 | import java.io.BufferedReader; |
07 | import java.io.IOException; |
08 | import java.io.InputStream; |
09 | import java.io.InputStreamReader; |
10 | import java.util.ArrayList; |
14 | public class OpenHelper extends SQLiteOpenHelper { |
16 | private String csv= "prefecture.csv" ; |
18 | private Context context; |
22 | public OpenHelper(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) { |
23 | super (context, name, factory, version); |
30 | public void onCreate(SQLiteDatabase db) { |
36 | List<Pref> list=getListFromCSV(csv); |
43 | public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { |
50 | private List<Pref> getListFromCSV(String csv){ |
51 | List<Pref> list= new ArrayList<>(); |
53 | AssetManager am=context.getAssets(); |
55 | InputStream is=am.open(csv); |
56 | InputStreamReader isr= new InputStreamReader(is); |
57 | BufferedReader br= new BufferedReader(isr); |
59 | while ((line=br.readLine()) != null ){ |
60 | String[] data=line.split( "," ); |
61 | Pref pref= new Pref(Integer.parseInt(data[ 0 ]),data[ 1 ],data[ 2 ]); |
65 | } catch (IOException e) { |
MainActivity
11.MainActivity.javaを以下のように作成する。
01 | import android.database.sqlite.SQLiteDatabase; |
02 | import android.os.Bundle; |
03 | import android.support.v7.app.AppCompatActivity; |
04 | import android.view.View; |
05 | import android.widget.TextView; |
07 | public class MainActivity extends AppCompatActivity { |
08 | static final int MIN= 1 ,MAX= 47 ; |
09 | TextView tvId,tvResult; |
13 | protected void onCreate(Bundle savedInstanceState) { |
14 | super .onCreate(savedInstanceState); |
15 | setContentView(R.layout.activity_main); |
16 | tvId=(TextView)findViewById(R.id.tvId); |
17 | tvResult=(TextView)findViewById(R.id.tvResult); |
18 | OpenHelper helper= new OpenHelper( this , "pref.db" , null , 1 ); |
19 | SQLiteDatabase db=helper.getWritableDatabase(); |
23 | public void btUp(View v){ |
25 | tvId.setText(String.valueOf(id)); |
27 | public void btDown(View v){ |
29 | tvId.setText(String.valueOf(id)); |
31 | public void btSearch(View v){ |
32 | tvResult.setText(dao.findOne(id).toString()); |
実行
12.実行してみよう。県番号を選んでGOボタンを押して、県庁所在地が表示されれば成功だ。
コメント