package it372.smiths.studentsdb1; import android.content.ContentValues; import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; public class StudentsDBHelper bextends SQLiteOpenHelper { private static final String DB_NAME = "students.db"; private static final int DB_VERSION = 1; public StudentsDBHelper(Context context) { super(context, DB_NAME, null, DB_VERSION); } @Override public void onCreate(SQLiteDatabase db) { db.execSQL("create table students(" + "name text, grade integer, gender text);"); insertStudent(db, "Alice", 6, "female"); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { // Body to be added later. } private static void insertStudent(SQLiteDatabase db, String name, int grade, String gender) { ContentValues studentValues = new ContentValues( ); studentValues.put("name", name); studentValues.put("grade", grade); studentValues.put("gender", gender); db.insert("students", null, studentValues); } }
TextView txtOutput = findViewById(R.id.txt_output); SQLiteOpenHelper dbh = new StudentsDBHelper(this); try { SQLiteDatabase db = dbh.getReadableDatabase(); Cursor cursor = db.query("students", new String[ ] {"name", "grade", "gender"}, null, null, null, null, null) ; if (cursor.moveToLast()) { String name = cursor.getString(0); int grade = cursor.getInt(1); String gender = cursor.getString(2); String output = String.format("%s %d %s", name, grade, gender); // This statement writes to the Logcat window. // Log.i("111", output); // This statement writes to the Run window. // System.out.println(output); // Display output in txt_output TextView widget. txtOutput.setText(output); } } catch(SQLiteException e) { Toast toast = Toast.makeText(this, "Database not created.", Toast.LENGTH_LONG); }
/data/data/it372/ssmiths/studentsdb1/databases/students.db
Here are the source code files:
activity_main.xml
MainActivity.java
StudentsDBHelper.java