public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//crate a database
SQLiteDatabase sqLiteDatabase = getBaseContext().openOrCreateDatabase("sqllite-db1.db", MODE_PRIVATE, null);
//create a table in database
sqLiteDatabase.execSQL("CREATE TABLE IF NOT EXISTS contacts(name TEXT, phone INTEGER, email TEXT)");
//add data
sqLiteDatabase.execSQL("INSERT INTO contacts VALUES ('MyName', 32543446, 'myemail@domain/com');");
sqLiteDatabase.execSQL("INSERT INTO contacts VALUES ('yourName', 32543446, 'yourmail@domain/com');");
//retrieve the data
Cursor query = sqLiteDatabase.rawQuery("SELECT * from contacts", null);
if(query.moveToFirst()) { //return false if there there is no data (check if the first record has data)
//Cycle through all records in all tables rows
//do = will execute at least once
do {
String name = query.getString(0);
int phone = query.getInt(1);
String email = query.getString(2);
Toast.makeText(this, "Name = " + name + ", phone = " + phone + ", email = " + email, Toast.LENGTH_SHORT).show();
} while(query.moveToNext());
}else {
Toast.makeText(this, "Error retrieving data", Toast.LENGTH_SHORT).show();
}
sqLiteDatabase.close();
}
}
Categories: Android Developer