Today I am going to share with you a topic which is Backbone of any app called SQLiteDatabase.
No doubt you can save small and simple data in SharedPrefrences but when you need to save complex and repeated data SQLite play a big role in that situation.So like every post i will make module of steps and we will follow all step to complete this tutorial. In this post we are going to
make a sample project in which we will save user data in First Activity and will show it in Recycler view of Second Activity,we will also add a delete button in Recyclerview of second Activity to delete that row you can see preview in above picture.
Time to start coding with our First step.
1.Create a new project in your Android Studio Go to File-> New ->New project and select Empty Activity from template and leave every thing as default. like below picture.
2.Add Five EditText for username,college,place,userId and number, also add a button to activity_main.xml. here is my activity_main.xml.
3.Create one more activity and add Recyclerview to its xml. To add Recyclerview you also need to add Library for Recyclerview in my case I added Design Support Library to build.gradle of app module. you can use either Support Library for Recyclerview or Design Support Library Simply copy and Paste one library from below code.
Now Add Recyclerview to xml of Second Activity here is my xml of Second Activity.
4.Create a new Java class and name it DbHelper. Now we are going to play with SQLite.
5.Extend SQLiteOpenHelper in DbHelper class. when you will extend this class it will ask you to implement its methods onCreate(SQLiteDatabase db) and onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) it will also ask you to create a constructor matching super. after messing with all these your class will be like this.
Now I will add some variables for Database name,Table name,Database version and all the column name like this.
Now i will add SQL query to create Table inside onCreate(),for that i am making a string of query to create Table and here is that String.
you can see i am making _id as primary key and it will auto increase. Now use execSQL() method to execute query. here is my onCreate() method .
Since onUpgrade() method is use to update your Database But i will refer you to Drop complete table and callonCreate() method inside onUpgrade() and add updation code inside onCreate(),here is my onUpgrade() method.
Now i am updating existing constructor and also adding a method which will return instance of DbHelper I will use this method in complete code where i need instance of DbHelper to insert,update or delete data. here is my constructor and getInstance() method.
5.Create a new Java class name it UserData and implement Serializable Interface to it and declare Five String varriable name,college,place,user_id and number in this class.
here is my UserData class.
6.Write method in DbHelper class to insert user data in to Database and to delete from Database.
In this step we will make three method one for Insert data,one for delete data and one for fetch all data. steps are simple.
Here is all three method..
7.Create a new Java class for Recyclerview Adapter and complete all the code for Recyclerview Adapter.
In this step I am creating a new java class name as ListAdapter and extend Recyclerview.Adapter ,If you are not familiar with Recyclerview check our Recyclerview tutorial . So first make a layout for single row of Recyclerview ,I am making a simple layout with one TextView and one ImageView. TextView to show user name and ImageView for delete icon. here is xml for single row
Now i am creating a Interface for callback to get position of item to delete. and then we will call delete method of SQLite to delete that row from Activity. Here is My Interface.
Now here is complete code for ListAdapter class.
8.Save user data in MainActivity on Button click and call second Activity. Now open your MainActivity and Register all your EditText and Button and save all data in SQLite by using Insert method of DbHelper on Button click. here is my MainActivity.java.
Don't be confused because code is very simple. onClick of button I am checking Text of all EditText for null and Empty in that case I am saving empty string. I am saving Text of Every EditText into UserData object and callinginsertUserDetail() method to save data into SQLite.
9.Show all the inserted data in Recyclerview of Second Activity. Open your Second Activity and Register Recyclerview. get all user data by calling getAllUser() method of DbHelper and pass List of type UserData type to ListAdapter. here is code of Second Activity .
Hey finally we have completed this tutorial, I know it was a lengthy tutorial but trust me If you follow all the steps it will help you a lot. Still having any problem feel free to comment below.
No doubt you can save small and simple data in SharedPrefrences but when you need to save complex and repeated data SQLite play a big role in that situation.So like every post i will make module of steps and we will follow all step to complete this tutorial. In this post we are going to
make a sample project in which we will save user data in First Activity and will show it in Recycler view of Second Activity,we will also add a delete button in Recyclerview of second Activity to delete that row you can see preview in above picture.
- Create a new project in your Android Studio Go to File-> New ->New project and select Empty Activity from template and leave every thing as default.
- Add Five EditText for username,college,place,userId and number, also add a button to activity_main.xml.
- Create one more activity and add Recyclerview to its xml.
- Create a new Java class and name it DbHelper.
- Extend SQLiteOpenHelper in DbHelper class.
- Create a new Java class name it UserData and implement Serializable Interface to it and declare Five String varriable name,college,place,user_id and number in this class.
- Write method in DbHelper class to insert user data in to Database and to delete from Database.
- Write one more method to fetch all data from Database to show into Recyclerview
- Create a new Java class for Recyclerview Adapter and complete all the code for Recyclerview Adapter.
- Save user data in MainActivity on Button click and call second Activity.
- Show all the inserted data in Recyclerview of Second Activity.
1.Create a new project in your Android Studio Go to File-> New ->New project and select Empty Activity from template and leave every thing as default. like below picture.
2.Add Five EditText for username,college,place,userId and number, also add a button to activity_main.xml. here is my activity_main.xml.
3.Create one more activity and add Recyclerview to its xml. To add Recyclerview you also need to add Library for Recyclerview in my case I added Design Support Library to build.gradle of app module. you can use either Support Library for Recyclerview or Design Support Library Simply copy and Paste one library from below code.
compile 'com.android.support:recyclerview-v7:23.1.0'
compile 'com.android.support:design:23.1.1'
Now Add Recyclerview to xml of Second Activity here is my xml of Second Activity.
5.Extend SQLiteOpenHelper in DbHelper class. when you will extend this class it will ask you to implement its methods onCreate(SQLiteDatabase db) and onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) it will also ask you to create a constructor matching super. after messing with all these your class will be like this.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
| public class DbHelper extends SQLiteOpenHelper {
public DbHelper(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
super(context, name, factory, version);
}
@Override
public void onCreate(SQLiteDatabase db) {
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
|
Now I will add some variables for Database name,Table name,Database version and all the column name like this.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
| private static final String TAG = "DbHelper";
// Database Info
private static final String DATABASE_NAME = "UserDatabase";
private static final int DATABASE_VERSION = 1;
//Table Names
private static final String TABLE_USERdETAIL = "userdetail";
//userdetail Table Columns
private static final String _ID = "_id";
private static final String NAME = "name";
private static final String COLLEGE = "college";
private static final String PLACE = "place";
private static final String USER_ID = "userId";
private static final String NUMBER = "number";
|
Now i will add SQL query to create Table inside onCreate(),for that i am making a string of query to create Table and here is that String.
1
2
3
4
5
6
7
8
9
| String CREATE_USERDETAIL_TABLE = "CREATE TABLE " + TABLE_USERdETAIL +
"(" +
_ID + " INTEGER PRIMARY KEY ," +
USER_ID + " TEXT," +
NAME + " TEXT," +
COLLEGE + " TEXT," +
PLACE + " TEXT," +
NUMBER + " TEXT" +
")";
|
you can see i am making _id as primary key and it will auto increase. Now use execSQL() method to execute query. here is my onCreate() method .
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
| /*
Called when the database is created for the FIRST time.
If a database already exists on disk with the same DATABASE_NAME, this method will NOT be called.
*/
@Override
public void onCreate(SQLiteDatabase db) {
String CREATE_USERDETAIL_TABLE = "CREATE TABLE " + TABLE_USERdETAIL +
"(" +
_ID + " INTEGER PRIMARY KEY ," +
USER_ID + " TEXT," +
NAME + " TEXT," +
COLLEGE + " TEXT," +
PLACE + " TEXT," +
NUMBER + " TEXT" +
")";
db.execSQL(CREATE_USERDETAIL_TABLE);
}
|
Since onUpgrade() method is use to update your Database But i will refer you to Drop complete table and callonCreate() method inside onUpgrade() and add updation code inside onCreate(),here is my onUpgrade() method.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
| /*
Called when the database needs to be upgraded.
This method will only be called if a database already exists on disk with the same DATABASE_NAME,
but the DATABASE_VERSION is different than the version of the database that exists on disk.
*/
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
if (oldVersion != newVersion) {
// Simplest implementation is to drop all old tables and recreate them
db.execSQL("DROP TABLE IF EXISTS " + TABLE_USERdETAIL);
onCreate(db);
}
}
|
Now i am updating existing constructor and also adding a method which will return instance of DbHelper I will use this method in complete code where i need instance of DbHelper to insert,update or delete data. here is my constructor and getInstance() method.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
| private static DbHelper mDbHelper;
public static synchronized DbHelper getInstance(Context context) {
// Use the application context, which will ensure that you
// don't accidentally leak an Activity's context.
if (mDbHelper == null) {
mDbHelper = new DbHelper(context.getApplicationContext());
}
return mDbHelper;
}
/**
* Constructor should be private to prevent direct instantiation.
* Make a call to the static method "getInstance()" instead.
*/
private DbHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
|
5.Create a new Java class name it UserData and implement Serializable Interface to it and declare Five String varriable name,college,place,user_id and number in this class.
here is my UserData class.
6.Write method in DbHelper class to insert user data in to Database and to delete from Database.
In this step we will make three method one for Insert data,one for delete data and one for fetch all data. steps are simple.
- Call getWritableDatabase()/getReadableDatabase() according to need.
- Begin Transaction
- Execute query
- End Transaction
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
| /*
Insert a user detail into database
*/
public void insertUserDetail(UserData userData) {
SQLiteDatabase db = getWritableDatabase();
db.beginTransaction();
try {
ContentValues values = new ContentValues();
values.put(NAME, userData.name);
values.put(COLLEGE, userData.college);
values.put(PLACE, userData.place);
values.put(USER_ID, userData.user_id);
values.put(NUMBER, userData.number);
db.insertOrThrow(TABLE_USERdETAIL, null, values);
db.setTransactionSuccessful();
} catch (SQLException e) {
e.printStackTrace();
Log.d(TAG, "Error while trying to add post to database");
} finally {
db.endTransaction();
}
}
/*
fetch all data from UserTable
*/
public List<UserData> getAllUser() {
List<UserData> usersdetail = new ArrayList<>();
String USER_DETAIL_SELECT_QUERY = "SELECT * FROM " + TABLE_USERdETAIL;
SQLiteDatabase db = getReadableDatabase();
Cursor cursor = db.rawQuery(USER_DETAIL_SELECT_QUERY, null);
try {
if (cursor.moveToFirst()) {
do {
UserData userData = new UserData();
userData.name = cursor.getString(cursor.getColumnIndex(NAME));
userData.college = cursor.getString(cursor.getColumnIndex(COLLEGE));
userData.place = cursor.getString(cursor.getColumnIndex(PLACE));
userData.user_id = cursor.getString(cursor.getColumnIndex(USER_ID));
userData.number = cursor.getString(cursor.getColumnIndex(NUMBER));
usersdetail.add(userData);
} while (cursor.moveToNext());
}
} catch (Exception e) {
Log.d(TAG, "Error while trying to get posts from database");
} finally {
if (cursor != null && !cursor.isClosed()) {
cursor.close();
}
}
return usersdetail;
}
/*
Delete single row from UserTable
*/
void deleteRow(String name) {
SQLiteDatabase db = getWritableDatabase();
try {
db.beginTransaction();
db.execSQL("delete from " + TABLE_USERdETAIL + " where name ='" + name + "'");
db.setTransactionSuccessful();
} catch (SQLException e) {
Log.d(TAG, "Error while trying to delete users detail");
} finally {
db.endTransaction();
}
}
|
7.Create a new Java class for Recyclerview Adapter and complete all the code for Recyclerview Adapter.
In this step I am creating a new java class name as ListAdapter and extend Recyclerview.Adapter ,If you are not familiar with Recyclerview check our Recyclerview tutorial . So first make a layout for single row of Recyclerview ,I am making a simple layout with one TextView and one ImageView. TextView to show user name and ImageView for delete icon. here is xml for single row
Now i am creating a Interface for callback to get position of item to delete. and then we will call delete method of SQLite to delete that row from Activity. Here is My Interface.
9.Show all the inserted data in Recyclerview of Second Activity. Open your Second Activity and Register Recyclerview. get all user data by calling getAllUser() method of DbHelper and pass List of type UserData type to ListAdapter. here is code of Second Activity .
Hey finally we have completed this tutorial, I know it was a lengthy tutorial but trust me If you follow all the steps it will help you a lot. Still having any problem feel free to comment below.
0 comments: