// KidsDb3 Example // Source code file: MainActivity.java package it372.kidsdb3; import androidx.appcompat.app.AppCompatActivity; import android.content.ContentValues; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.os.Bundle; import android.view.View; import android.widget.EditText; import android.widget.TextView; import java.util.Locale; public class MainActivity extends AppCompatActivity { private SQLiteDatabase db; private EditText edtRowData; private EditText edtPrimaryKey; private TextView txtOutput; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); SQLiteOpenHelper dbh = new KidsDbHelper(this); db = dbh.getWritableDatabase( ); db.execSQL("create table if not exists " + "kids(name text, gender text, age integer);"); edtRowData = findViewById(R.id.edt_row_data); edtPrimaryKey = findViewById(R.id.edt_primary_key); txtOutput = findViewById(R.id.txt_output); } public void insertRow(View view) { String row = edtRowData.getText( ).toString( ); String[ ] fields = row.split(","); String name = fields[0]; String gender = fields[1]; int age = Integer.parseInt(fields[2]); ContentValues values = new ContentValues( ); values.put("name", name); values.put("gender", gender); values.put("age", age); db.insert("kids", null, values); } public void showRow(View view) { String key = edtPrimaryKey.getText( ).toString( ); Cursor c = db.query("kids", new String[ ] {"name", "gender", "age"}, "name=?", new String[ ] {key}, null, null, null); if (c.moveToFirst( )) { String name = c.getString(0); String gender = c.getString(1); int age = c.getInt(2); String output = String.format(Locale.ENGLISH, "%s %s %d\n", name, gender, age); txtOutput.setText(output); } else { txtOutput.setText(""); } } public void clearTable(View view) { db.execSQL("delete from kids"); txtOutput.setText(""); } }