データベース・基礎(固定値INSERT) … 作成編5

アプリ ソースコード家計簿アプリ

データの保存方法

 状態:学習中  閲覧数:1,497  投稿日:2013-08-02  更新日:2013-08-03
3つある
1.プリファレンス
2.ローカルファイル
3.データベース


1.プリファレンス


・int型やString型などの、単発の値を保存するときに使用
・家計簿アプリでは、項目欄などに使用


2.ローカルファイル


・複数の行など、プリファレンスよりは長いデータを保存するときに使用
・txtファイルに保存して使用
・設定値をまとめたいときに使用


3.データベース


・複雑なデータを多く扱いたいときに使用
・家計簿アプリの出費等のデータは毎日使うので、このデータベースを使用
手順
・オープン→読み取り・書込み→クローズ

SubOpenHelperクラス作成

 閲覧数:436 投稿日:2013-08-02 更新日:2013-08-02

概要


・オープン処理をするためのクラス

処理の流れ

 閲覧数:389 投稿日:2013-08-02 更新日:2013-08-03

概要


1.内訳サーチボタンクリック
2.「データベース」作成
3.「テーブル」「カラム」作成
4.「データ」をテーブルに追加
5.「カーソルリストのデータ」を読み込む


1.内訳サーチボタンクリック


・button2クリック
▼/src/android/style/householdaccount/Item.java
    public void onClick(View v) {
    if(v==button2){//内訳サーチボタン



2.「データベース」作成


・SubOpenHelperクラスのインスタンス生成
▼/src/android/style/householdaccount/Item.java
    		// 正常起動時 
     try{
      // クラスのインスタンス化
       SubOpenHelper helper = new SubOpenHelper(getApplicationContext(),"test.db3",1);
       //コンストラクタのデータを決める。コンテキスト、DBファイル名、バージョン。


▼/src/android/style/householdaccount/SubOpenHelper.java
・SubOpenHelperクラスのコンストラクタが呼ばれる
・引数で受け取ったデータベースがなければ作成。あればオープン


3.「テーブル」「カラム」作成


・SubOpenHelperクラスの、onCreateメソッドによって、「テーブル定義」を作成
	@Override
   public void onCreate(SQLiteDatabase db) {

・データベースが一番最初に作られたとき(コンストラクタに渡されたDBファイル名が存在しない場合)、呼ばれる
・「テーブル」「カラム」生成


4.「データ」をテーブルに追加


▼/src/android/style/householdaccount/Item.java
・「insert」メソッドで、データをテーブルに追加


5.「カーソルリストのデータ」を読み込む


▼/src/android/style/householdaccount/Item.java
・「queryメソッド」で、カーソルリストのデータを読み込む
package android.style.householdaccount;

import java.util.Calendar;

import android.style.householdaccount.Item;

import android.style.householdaccount.R;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.graphics.Canvas;
import android.graphics.Color;
import android.os.Bundle;
import android.text.SpannableString;
import android.text.style.UnderlineSpan;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

public class Item extends Activity implements OnClickListener{
//public class Item extends Activity{
private EditText edit1,edit2,edit3;
private Button button1,button2,button4;
private TextView text_test;
private String number;
int year,month,day,itemcheck=0,utiwakecheck=0;
private TextView dbtest1;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.item);

text_test = (TextView)this.findViewById(R.id.text_test);
dbtest1 = (TextView)this.findViewById(R.id.dbtest1);
edit1 = (EditText)this.findViewById(R.id.item_edit1);
edit2 = (EditText)this.findViewById(R.id.item_edit2);
edit3 = (EditText)this.findViewById(R.id.item_edit3);
button1=(Button)this.findViewById(R.id.item_button1);//項目サーチボタン
button2=(Button)this.findViewById(R.id.item_button2);//内訳サーチボタン
button4=(Button)this.findViewById(R.id.item_button4);//記入ボタン
SpannableString spannableString = new SpannableString("現金");

text_test.setText(number);

Calendar calendar = Calendar.getInstance();
Intent intent1 = getIntent();
year = intent1.getIntExtra("year",calendar.get(Calendar.YEAR));
month = intent1.getIntExtra("month",calendar.get(Calendar.MONTH));
day = intent1.getIntExtra("day",calendar.get(Calendar.DAY_OF_MONTH));
String listitem = intent1.getStringExtra("listitem");
String listutiwake = intent1.getStringExtra("listutiwake");
edit1.setText(listitem);
edit2.setText(listutiwake);

//--上の直線--
LinearLayout linear1 = (LinearLayout) findViewById(R.id.Linear01);
LinearLayout.LayoutParams liner01 = new LinearLayout.LayoutParams(480,3);
Maindraw linerA;
linerA = new Maindraw(this);
linerA.setLayoutParams(liner01);
linear1.addView(linerA);
//--上の直線--


button1.setOnClickListener(this);//項目サーチボタン
button2.setOnClickListener(this);//内訳サーチボタン
button4.setOnClickListener(this);//記入ボタン
}

public void onClick(View v) {
if(v==button2){//内訳サーチボタン
// 正常起動時
try{
// クラスのインスタンス化
SubOpenHelper helper = new SubOpenHelper(getApplicationContext(),"test.db3",1);
//コンストラクタのデータを決める。コンテキスト、DBファイル名、バージョン。

// データベースの設定
SQLiteDatabase db;
db = helper.getWritableDatabase();
//データベースに書き込めるように設定
// db.execSQL("insert into Date_Table(Koumoku,Utiwake,Kingaku) values ('食事', 'ステーキ',1000);");
db.execSQL("insert into Date_Table(Item,Utiwake,Kingaku) values ('食事', 'ステーキ',1000);");
//insertで行に追加
dbtest1.setText("");
//dbtest1の初期化

// カーソルの設定
// String[] cols = {"Koumoku","Utiwake","Kingaku"};
String[] cols = {"Item","Utiwake","Kingaku"};
Cursor c = db.query("Date_Table",cols,null, null, null, null, null,null);
//カーソルのリストを作る。1:テーブル名、2:取得する列名(カラム等)の配列、
//3&4:取得するレコードの条件、5:GROUP BY条件、6:「HAVING」条件、
//7:「ORDER BY」条件、8:「limit」条件
boolean isEof = c.moveToFirst();
//カーソルを先頭に移動
while (isEof) {
//while文。カーソルが最後に行くまで繰り返す。
dbtest1.append(c.getString(0));
dbtest1.append(c.getString(1));
dbtest1.append(String.valueOf(c.getInt(2)));
//getString(0)メソッドで、カーソルの一行目を追加。2,3も同じ。
isEof = c.moveToNext();}
//次のリストにカーソルを移す。
c.close();
//終わったら閉じる。これがないとエラーとなる。データベースも。
db.close();
}

// 異常終了時
catch(SQLiteException e){
dbtest1.setText("エラー");
return;
}
}
else if (v==button4){//記入ボタンクリックされたら
Intent intent2=new Intent(Item.this,MainActivity.class);
// edit1~3に入力したデータをgetText()メソッドで取得
// toString()メソッドで文字列に変換
// putExtraメソッドでintent1のdata1~3へ格納
intent2.putExtra("data1", edit1.getText().toString());
intent2.putExtra("data2", edit2.getText().toString());
intent2.putExtra("data3", edit3.getText().toString());
intent2.putExtra("year", year);
intent2.putExtra("month", month);
intent2.putExtra("day", day);
startActivity(intent2);
}
}




//上の直線、設定
class Maindraw extends View {
public Maindraw(Context context) {
super(context);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);

// 黒で塗る
canvas.drawColor(Color.DKGRAY);
}
}
//直線設定終わり




//@Override
//public void onClick(View v) {
// Intent intent2=new Intent(Item.this,MainActivity.class);
// intent2.putExtra("data1", edit1.getText().toString());
// intent2.putExtra("data2", edit2.getText().toString());
// intent2.putExtra("data3", edit3.getText().toString());
// intent2.putExtra("month", month);
// intent2.putExtra("day", day);
// startActivity(intent2);

//}








}



Next


・あらかじめ決められた値を入れているだけ
・取得した値をデータベースに入れるよう、変更

注意事項 DB関連

 閲覧数:415 投稿日:2013-08-02 更新日:2013-08-02

エラーログ1


・指定テーブル「Date_Table」が存在しない
08-01 21:28:03.786: E/Database(284): Failure 1 (no such table: Date_Table) on 0x292710 when preparing 'insert into  Date_Table(Koumoku,Utiwake,Kingaku) values ('食事', 'ステーキ',1000);'.


対応1


・指定テーブルを作成すれば良い


注意事項


・初めにDB作成する際、「テーブル」「カラム」を作成する
・そのため、「テーブル」「カラム」を作成し直す際は、DB名を変更するか、一旦作成したDBを削除する必要がある


エラーログ2


・指定カラム「Koumoku」が存在しない
08-01 22:29:07.586: E/Database(277): Failure 1 (table Date_Table has no column named Koumoku) on 0x2926c8 when preparing 'insert into  Date_Table(Koumoku,Utiwake,Kingaku) values ('食事', 'ステーキ',1000);'.
・以下、同上


DB以外


・DBに注意を払い過ぎて、テキストオブジェクトを取得し忘れたため、nullエラー発生
実際に遭遇した例


コマンド履歴

 閲覧数:406 投稿日:2013-08-02 更新日:2013-08-02

adb


・今回利用
C:\Users\Administrator>adb shell
cd data/data/android.style.householdaccount/databases
ls
sqlite3 test.db3
.table
select * from Date_Table;



履歴


Microsoft Windows [Version 6.1.7601]
Copyright (c) 2009 Microsoft Corporation.  All rights reserved.

C:\Users\Administrator>adb shell
# cd data/data/android style/databases
cd data/data/android style/databases
cd: bad substitution
# ls
ls
config
cache
sdcard
acct
mnt
d
etc
system
sys
sbin
proc
init.rc
init.goldfish.rc
init
default.prop
data
root
dev
# cd data
cd data
# ls
ls
anr
misc
local
app-private
data
property
backup
dontpanic
system
app
dalvik-cache
lost+found
# cd data
cd data
# ls
ls
android.style.listview
android.style.dialog
com.android.quicksearchbox
com.android.inputmethod.latin
com.android.providers.userdictionary
com.fc2.blog98.andromaker.housekeepingbook
net.kazhik.android.kmoney
com.android.customlocale
com.android.inputmethod.pinyin
com.android.providers.subscribedfeeds
com.android.providers.drm
com.android.cardock
com.android.development
com.android.defcontainer
com.android.server.vpn
com.android.soundrecorder
com.android.calculator2
com.android.spare_parts
com.android.fallback
com.android.gallery
com.android.carhome
com.android.htmlviewer
com.android.certinstaller
com.android.wallpaper.livepicker
com.android.music
com.android.netspeed
com.android.packageinstaller
android.tts
com.svox.pico
com.android.sdksetup
com.android.term
com.example.android.livecubes
com.example.resource1
com.example.practice1
com.android.protips
android.style.linearlayout1
android.style.relativelayout
android.style.progressbar
android.style.optionsmenu1
com.android.providers.applications
com.android.speechrecorder
android.style.alertdialog1
com.google.code.androidrome.demo
android.style.listviewadd
android.style.tablelayout
com.example.android.apis
android.style.relativelayout1
com.android.providers.contacts
com.example.android.softkeyboard
com.android.gesture.builder
com.android.camera
com.android.phone
com.android.providers.settings
com.android.launcher
com.android.settings
com.android.providers.telephony
com.android.mms
com.android.email
com.android.browser
com.android.providers.downloads
com.android.alarmclock
com.android.providers.media
com.android.contacts
jp.co.spookies.android.rssreader
android.style
codezine.androidjava.chap1
jp.co.omronsoft.openwnn
android.style.householdaccount
androidstyle.linearlayout
# cd android.style
cd android.style
# ls
ls
lib
# cd android.style.houseaccount
cd android.style.houseaccount
cd: can't cd to android.style.houseaccount
# cd android.style.householdaccount
cd android.style.householdaccount
cd: can't cd to android.style.householdaccount
# ls
ls
lib
# cd ../
cd ../
# cd android.style.householdaccount
cd android.style.householdaccount
# ls
ls
lib
databases
# cd databases
cd databases
# ls
ls
test.db
# sqlite3 test.db
sqlite3 test.db
SQLite version 3.6.22
Enter ".help" for instructions
Enter SQL statements terminated with a ";"
sqlite> .table 
.table 
Error: unknown command or invalid arguments:  "table ". Enter ".help" for help
sqlite> .table
.table
aaaa              android_metadata
sqlite>


C:\Users\Administrator>adb shell
error: device not found

C:\Users\Administrator>adb shell
# cd data/data/android.style.householdaccount/databases
cd data/data/android.style.householdaccount/databases
# ls
ls
test.db
# sqlite3 test.db
sqlite3 test.db
SQLite version 3.6.22
Enter ".help" for instructions
Enter SQL statements terminated with a ";"
sqlite> .table;
.table;
Error: unknown command or invalid arguments:  "table;". Enter ".help" for help
sqlite> .table
.table
aaaa              android_metadata
sqlite>
C:\Users\Administrator>adb shell
# cd data/data/android.style.householdaccount/databases
cd data/data/android.style.householdaccount/databases
# sqlite3 test.db
sqlite3 test.db
SQLite version 3.6.22
Enter ".help" for instructions
Enter SQL statements terminated with a ";"
sqlite> .table
.table
aaaa              android_metadata
.exit
# ls
ls
test.db
#
C:\Users\Administrator>adb shell
# cd data/data/android.style.householdaccount/databases
cd data/data/android.style.householdaccount/databases
# .table
.table
.table: not found
# ls
ls
test.db
# sqlite3 test.db
sqlite3 test.db
SQLite version 3.6.22
Enter ".help" for instructions
Enter SQL statements terminated with a ";"
sqlite> .table
.table
aaaa              android_metadata
sqlite>
C:\Users\Administrator>adb shell
# cd data/data/android.style.householdaccount/databases
cd data/data/android.style.householdaccount/databases
# ls
ls
test.db2
test.db
# sqlite3 test.db2
sqlite3 test.db2
SQLite version 3.6.22
Enter ".help" for instructions
Enter SQL statements terminated with a ";"
sqlite> .table
.table
Date_Table        android_metadata
sqlite> select * from Date_Table;
select * from Date_Table;
sqlite> select * from Date_Table;
select * from Date_Table;
sqlite>
C:\Users\Administrator>adb shell
# cd data/data/android.style.householdaccount/databases
cd data/data/android.style.householdaccount/databases
# .table
.table
.table: not found
# .table
.table
.table: not found
# ls
ls
test.db
test.db2
# sqlite3 test.db2
sqlite3 test.db2
SQLite version 3.6.22
Enter ".help" for instructions
Enter SQL statements terminated with a ";"
sqlite> .table
.table
Date_Table        android_metadata
sqlite> select * from Date_Table;
select * from Date_Table;
1|鬟滉コ弓繧ケ繝・・繧ュ|1000
sqlite>
C:\Users\Administrator>adb shell
# cd data/data/android.style.householdaccount/databases
cd data/data/android.style.householdaccount/databases
# ls
ls
test.db3
test.db
test.db2
# sqlite3 test.db3
sqlite3 test.db3
SQLite version 3.6.22
Enter ".help" for instructions
Enter SQL statements terminated with a ";"
sqlite> .table
.table
Date_Table        android_metadata
sqlite> select * from Date_Table;
select * from Date_Table;
1|鬟滉コ弓繧ケ繝・・繧ュ|1000
sqlite>
C:\Users\Administrator>



インテント … 項目画面からのデータをメイン画面に反映(DB未利用) … 作成編4

データベース・ソート(取得値をINSERT) … 作成編6



週間人気ページランキング / 5-12 → 5-18
順位 ページタイトル抜粋 アクセス数
アクセスが、ありませんでした! 0
2024/5/19 1:01 更新