SQLiteのデータの追加・表示・検索
機能
・データの追加
・データベースの表示
・データの検索
activity.xml
MainActivity.java
package com.example.orisa.mydb6; import android.content.ContentValues; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import org.w3c.dom.Text; public class MainActivity extends AppCompatActivity { //部品の変数 EditText addText; Button addBtn; Button showBtn; EditText searchText; Button searchBtn; TextView disp; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //部品の取得 addText = (EditText)findViewById(R.id.addText); addBtn = (Button)findViewById(R.id.addBtn); showBtn = (Button)findViewById(R.id.showBtn); searchText = (EditText)findViewById(R.id.searchText); searchBtn = (Button)findViewById(R.id.searchBtn); disp = (TextView) findViewById(R.id.disp); //データベースの生成 MyDbHelper hlp = new MyDbHelper(this); final SQLiteDatabase db = hlp.getWritableDatabase(); //データの追加 addBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { ContentValues val = new ContentValues(); val.put("task", addText.getText().toString()); db.insert("tasktb", null, val); } }); //データの検索 searchBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { //TextViewのクリア disp.setText("SEARCH RESULTS:\n"); //検索文字列の取得 String str = searchText.getText().toString(); //検索 Cursor c = db.query("tasktb", new String[]{"id", "task"}, "task=?", new String[]{str}, null, null, null); boolean mov = c.moveToFirst(); while(mov){ disp.append(c.getInt(0)+": "+c.getString(1)+"\n"); mov = c.moveToNext(); } c.close(); } }); //データの表示 showBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { //TextViewのリセット disp.setText(null); Cursor c = db.query("tasktb", new String[]{"id", "task"}, null, null, null, null, null); boolean mov = c.moveToFirst(); while(mov){ disp.append(c.getInt(0)+": "+c.getString(1)+"\n"); mov = c.moveToNext(); } c.close(); } }); } }
MyDbHelper.java
package com.example.orisa.mydb6; import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; /** * Created by orisa on 2017/05/31. */ public class MyDbHelper extends SQLiteOpenHelper { public MyDbHelper(Context context){ super(context, null, null, 1); } @Override public void onCreate(SQLiteDatabase db) { db.execSQL("CREATE TABLE tasktb(id INTEGER PRIMARY KEY, task TEXT);"); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { } }