Android DB Connectivity
Step:1
Create java class for all DB Operations at the location where mainactivity.java file is present i.e.
appjavacom.example…. --> right click new class
give the name as “DBHelper”
======== Code in DBHelper.java============
step:2
Extend this class using SQLiteOpenHelper
hover and click on implement methods
hover and define constructor and keep only context part and remove the remaining par.
Step:3
declare following objects globally
1. private static final String DB_NAME="STUDDB.db";
2. private static final int DB_VERSION=1;
3. private static final String TB_NAME="studinfo";
4. private static final String COL1="sid";
5. private static final String COL2="sname";
6. ContentValues valOb = new ContentValues();
7. Context conObj;
Initialize context object in DBHelper constructor as:
conObj=context;
[ OnCreate and onUpgrade provide object for SQLiteDatabase]
In onCreate methodcreate table as:
SQLob.execSQL("CREATE TABLE studinfo(sid INTEGER,sname text)");
Toast.makeText(conObj, "Table Created", Toast.LENGTH_SHORT).show();
Write following code in OnUpgrade method
SQLob.execSQL("DROP TABLE IF EXISTS studinfo");
Step:4
Create method to insert record as:
public long insertRec(int sid,String sname)
{
1. long rst=-1;
2. SQLiteDatabase sqldb=this.getWritableDatabase();
3. try {
4. valOb.put(COL1,sid);
5. valOb.put(COL2, sname);
6. rst=sqldb.insertOrThrow(TB_NAME,null,valOb);
7. }catch(SQLiteConstraintException ex1) {
8. Toast.makeText(conObj, ex1.getMessage(), Toast.LENGTH_SHORT).show();
9. }
10. catch(SQLiteDatabaseLockedException ex2)
11. { Toast.makeText(conObj, ex2.getMessage(), Toast.LENGTH_SHORT).show();}
12. catch(Exception ex3){Toast.makeText(conObj, ex3.getMessage(), Toast.LENGTH_SHORT).show();}
13. finally {
14. sqldb.close();
15. }
16. return rst;
}
Step:5
Create method to Read record as:
1. public Cursor getData()
2. {
3. SQLiteDatabase sqldb=this.getReadableDatabase();
4. return sqldb.query(TB_NAME,null,null,null,null,null,null);
5. }
======= Code in mainactivity.xml===========
- Set linear layout with vertical horizontal orientation
- Add two textviews ,two edit text , two buttons as Save Record, Read Record
- Add one ListView
======= Code in mainactivity.java===========
1. Declare two EditText objects, 2 buttons objects and one ListView obj
2. Declare DBHelper object as ; DBHelper DBobj;
3. Initialize all the objects of line 1 using findby….
4. Init DBHelper obj as : DBobj=new DBHelper(this);
5. Declare one String data[] array
6. Insert button code:
I. if(txtSid.getText().toString().isEmpty() || txtSname.getText().toString().isEmpty())
II. Toast.makeText(MainActivity.this, "ERROR - SID or SNAME is Empty",
Toast.LENGTH_SHORT).show();
III. else {
IV. int sid = Integer.parseInt(txtSid.getText().toString());
V. String sname = txtSname.getText().toString();
VI. long id = DBobj.insertRec(sid, sname);
VII. if (id > 0) {
a. Toast.makeText(MainActivity.this, "Record Saved", Toast.LENGTH_SHORT).show();
b. txtSid.setText("");
c. txtSname.setText("");
VIII. }
IX. }
7. Code to read record/s
a. Cursor crObj=DBobj.getData();
b. int k=0;
c. if(crObj.moveToFirst())
d. {
e. do {
f. int sid=crObj.getInt(crObj.getColumnIndexOrThrow("sid"));
g. String s=crObj.getString(crObj.getColumnIndexOrThrow("sname"));
h. data[k]=""+sid+"---"+s;
i. k++;
j. }while(crObj.moveToNext());
k. }
l. crObj.close();
m. if(k==0)
n. Toast.makeText(MainActivity.this, "No Records", Toast.LENGTH_SHORT).show();
o. else
p. {
q. ArrayAdapter <String> adpObj=new ArrayAdapter<>(MainActivity.this,
android.R.layout.simple_list_item_1,data);
r. lstView.setAdapter(adpObj);
s. }