· 8 years ago · Nov 30, 2017, 05:26 PM
1public class MainActivity extends AppCompatActivity {
2
3//Assign below 3 variables as global variables where class start.
4
5 SQLiteDatabase db; //Assign as a global variable
6 String DBName = "MyDB"; //Assign as a global variable
7 String TableName = "PeopleData"; //Assign as a global variable
8
9//Call 3 function inside oncreate method.
10
11protected void onCreate(Bundle savedInstanceState) {
12 super.onCreate(savedInstanceState);
13 setContentView(R.layout.activity_main);
14
15 createDB_Table(); //calling 3 functions.
16 InsertDataToDB();
17 ReadDBData();
18 }
19
20public void createDB_Table(){ //This function use to create database, table & columns.
21 db = this.openOrCreateDatabase(DBName, MODE_PRIVATE, null);
22 db.execSQL("CREATE TABLE IF NOT EXISTS " + TableName + " (ID INTEGER PRIMARY KEY AUTOINCREMENT, Name TEXT, Address TEXT, City TEXT, Country TEXT);");
23 db.close();
24 }
25
26public void InsertDataToDB(){ //This function use to inset values to database.
27 db = this.openOrCreateDatabase(DBName, MODE_PRIVATE, null);
28 ContentValues cv = new ContentValues();
29 cv.put("Name","Steve Hardy");
30 cv.put("Address","16 Somewhere Land");
31 cv.put("City","Colorado");
32 cv.put("Country","USA");
33 db.insert(TableName, null, cv);
34 db.close();
35 }
36
37public void ReadDBData() { //This function use to read data from database.
38 db = this.openOrCreateDatabase(DBName, MODE_PRIVATE, null);
39 Cursor cursor = db.rawQuery("SELECT * FROM " + TableName, null);
40
41 if (cursor.getCount() > 0) { //check cursor is not empty.
42 cursor.moveToFirst();
43 String DName = cursor.getString(cursor.getColumnIndex("Name"));
44 String DAddress = cursor.getString(cursor.getColumnIndex("Address"));
45 String DCity = cursor.getString(cursor.getColumnIndex("City"));
46 String DCountry = cursor.getString(cursor.getColumnIndex("Country"));
47 //Got the values from database. Then you can set those values to text view or something you use.
48 }
49 cursor.close();
50 db.close();
51 }
52 }