中身は、
データベース名:database_foods
テーブル名:table_foods
カラム:ID、商品名、値段
MainActivity:ListViewで一覧表示。
リストを選択すると画面(RegisterActivity)に遷移する。
RegisterActivity:MianActivityから受け取ったデータを表示。
Button押下でアクティビティ終了。
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.content.Intent; 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.view.View; import android.widget.AdapterView; 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(); final SimpleCursorAdapter adapter = 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); foodsList.setAdapter(adapter); foodsList.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView parent, View view, int position, long id) { ListView listView = (ListView)parent; Cursor cursor1 = (Cursor)listView.getItemAtPosition(position); String string = cursor1.getString( cursor1.getColumnIndex(DatabaseOpenHelper.COLUMN_ID)); Intent intent = new Intent(MainActivity.this, RegisterActivity.class); intent.putExtra("SELECTED_DATA",string); startActivity(intent); } }); } @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); } }
RegisterActivity.java
package lesson.studyandroid_02; import android.app.Activity; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.ListView; import android.widget.TextView; public class RegisterActivity extends Activity { protected SQLiteDatabase db; protected ListView foodsList; protected String strData; @Override protected void onCreate(Bundle savedInstanceState) { String strName = ""; String strPrice = ""; super.onCreate(savedInstanceState); setContentView(R.layout.activity_register); db = (new DatabaseOpenHelper(this)).getWritableDatabase(); foodsList = (ListView)findViewById(R.id.list); strData = getIntent().getStringExtra("SELECTED_DATA"); String strSQL = "SELECT name, price FROM table_foods WHERE _id = " + strData; Cursor cursor = db.rawQuery(strSQL, null); /* Cursor cursor = db.query(DatabaseOpenHelper.TABLE_NAME, new String[] { DatabaseOpenHelper.COLUMN_NAME, DatabaseOpenHelper.COLUMN_PRICE }, DatabaseOpenHelper.COLUMN_ID + "='" + strData + "'", null, null, null, null); */ while (cursor.moveToNext()){ strName = cursor.getString( cursor.getColumnIndex(DatabaseOpenHelper.COLUMN_NAME)); strPrice = cursor.getString( cursor.getColumnIndex(DatabaseOpenHelper.COLUMN_PRICE)); } TextView textView = (TextView)findViewById(R.id.text_id); textView.setText(strData); EditText editText1 = (EditText)findViewById(R.id.editText_name); editText1.setText(strName); EditText editText2 = (EditText)findViewById(R.id.editText_price); editText2.setText(strPrice); Button btn_end = (Button)findViewById(R.id.btn_finish); btn_end.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { finish(); } }); } }
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>
activity_register.xml
<?xml version="1.0" encoding="utf-8"?> <TableLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="wrap_content"> <TableRow android:layout_width="fill_parent" android:layout_height="fill_parent"> <TextView android:layout_width="70dp" android:layout_height="wrap_content" android:text="@string/textView1" android:id="@+id/textView_id" /> <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:id="@+id/text_id" /> </TableRow> <TableRow android:layout_width="fill_parent" android:layout_height="fill_parent"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/textView2" android:id="@+id/textView_name" /> <EditText android:layout_width="fill_parent" android:layout_height="wrap_content" android:id="@+id/editText_name" android:hint="@string/text_name" /> </TableRow> <TableRow android:layout_width="fill_parent" android:layout_height="fill_parent"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/textView3" android:id="@+id/textView_price" /> <EditText android:layout_width="fill_parent" android:layout_height="wrap_content" android:id="@+id/editText_price" android:hint="@string/text_price" android:inputType="number" /> </TableRow> <LinearLayout android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent"> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/button_finish" android:id="@+id/btn_finish" /> </LinearLayout> </TableLayout>
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> <activity android:name=".RegisterActivity" android:label="@string/app_name" > </activity> </application> </manifest>
string.xml
<resources> <string name="app_name">StudyAndroid_02</string> <string name="action_settings">Settings</string> <string name="textView1">ID</string> <string name="textView2">商品名</string> <string name="textView3">価格</string> <string name="text_name">商品名を入力</string> <string name="text_price">価格を入力</string> <string name="button_finish">戻る</string> </resources>