
How to save data into SQLite from Android App
While developing the app you might have thought about how to deal with the database. You can work with either an online(MySql) database or with an offline(SQLite) database. SQLite is the database that is used to store app data and comes with Android OS. Here you can deal with the database without requiring an internet connection.
When the term Database comes to mind this must be the next thinking, how to accomplish CURD(Create, Update, Read, Delete) operations. We will see it one by one so that you can get it clearly. Here I am going to explain how to store data into SQLite from Android App.
I am creating a table that will store a sample blog post into SQLite.
Step 1. Create a new project in Android having the name WorkingWithSqlite.
Step 2. Create a Post class having post details variables and its getter and setter methods.
package com.buzzmycode.workingwithsqlite; /** * Created by OMIXA on 9/9/2016. */ public class Post { String title; String content; public Post(String author, String content, String date, String title) { this.author = author; this.content = content; this.date = date; this.title = title; } public void setDate(String date) { this.date = date; } public void setAuthor(String author) { this.author = author; } public void setContent(String content) { this.content = content; } public void setTitle(String title) { this.title = title; } String date; String author; public String getAuthor() { return author; } public String getContent() { return content; } public String getDate() { return date; } public String getTitle() { return title; } }
Step 3. Open activity_main.xml from res package and copy the below code.
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context="com.buzzmycode.workingwithsqlite.MainActivity"> <EditText android:layout_width="match_parent" android:layout_height="50dp" android:id="@+id/name" android:hint="POST NAME" android:textSize="20dp"/> <EditText android:layout_width="match_parent" android:layout_height="50dp" android:layout_marginTop="10dp" android:inputType="textMultiLine" android:ems="10" android:textSize="20dp" android:id="@+id/content" android:layout_below="@id/name" android:hint="POST CONTENT"/> <EditText android:layout_width="match_parent" android:layout_height="50dp" android:layout_marginTop="10dp" android:id="@+id/date" android:layout_below="@id/content" android:textSize="20dp" android:hint="POST DATE"/> <EditText android:layout_width="match_parent" android:layout_height="50dp" android:layout_marginTop="10dp" android:id="@+id/author" android:textSize="20dp" android:layout_below="@id/date" android:hint="POST AUTHOR"/> <Button android:layout_width="match_parent" android:layout_height="50dp" android:text="SAVE TO SQLITE" android:id="@+id/savetosqlite" android:layout_below="@+id/author" android:textSize="20dp" android:textAlignment="center" android:layout_alignParentStart="true" android:layout_marginTop="117dp" /> </RelativeLayout>
This will create the layout as shown below:
Step 4. For dealing with SQLite, I am creating a separate class called DBHandle which extends SQLiteOpenHelper. It will give an error until we import its method. These are as below:
onCreate(): This method is called when the database is created. In this method query for creating a table is written.
onUpgrade(): This method is called when the database is upgraded that is when there are any changes in the database table.
Here onCreate() and onUpgrade() method will remain same for CURD operation.
package com.buzzmycode.workingwithsqlite; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.SQLException; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteException; import android.database.sqlite.SQLiteOpenHelper; import android.util.Log; import android.widget.Toast; public class DBHandler extends SQLiteOpenHelper { public static final String TABLE_NAME = "tsqlite"; public static final String DATABASE_NAME = "BMC"; public static final int DATABASE_VERSION = 1; public static final String POST_ID = "id"; public static final String POST_TITLE = "title"; public static final String POST_CONTENT = "content"; public static final String POST_DATE = "date"; public static final String POST_AUTHOR = "author"; private static DBHandler mInstance = null; static Context context; public static DBHandler getInstance(Context ctx) { if (mInstance == null) { mInstance = new DBHandler(ctx.getApplicationContext()); context = ctx; } return mInstance; } private DBHandler(Context ctx) { super(ctx, DATABASE_NAME, null, DATABASE_VERSION); } @Override public void onCreate(SQLiteDatabase db) { String CREATE_POST_TABLE = "CREATE TABLE " + TABLE_NAME + "(" + POST_ID + " INTEGER PRIMARY KEY," + POST_TITLE + " TEXT," + POST_CONTENT + " TEXT," + POST_DATE + " TEXT," + POST_AUTHOR + " TEXT" + ");"; db.execSQL(CREATE_POST_TABLE); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME); onCreate(db); } }
Step 5. Open MainActivity.java and copy the below code.
package com.buzzmycode.workingwithsqlite; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; import com.buzzmycode.workingwithsqlite.DBHandler; public class MainActivity extends AppCompatActivity { EditText pname, pcontent, pdate, pauthor; Button savePost; DBHandler dbHandler; String name,content,date,author; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); dbHandler = DBHandler.getInstance(getApplicationContext()); pname = (EditText) findViewById(R.id.name); pcontent = (EditText) findViewById(R.id.content); pdate = (EditText) findViewById(R.id.date); pauthor = (EditText) findViewById(R.id.author); savePost = (Button) findViewById(R.id.savetosqlite); savePost.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { name = pname.getText().toString(); content = pcontent.getText().toString(); date = pdate.getText().toString(); author = pauthor.getText().toString(); dbHandler.addEntry(name,content,date,author); } }); } }
Step 6. Now add the below code in DBHandler.java. This code will deal with adding the entry to the table and return whether the record is inserted into the table or not.
public void addEntry(String title, String content, String date, String author) throws SQLiteException { SQLiteDatabase database = this.getWritableDatabase(); ContentValues cv = new ContentValues(); Log.d("Insert: ", "Inserting .."); cv.put(POST_TITLE, title); cv.put(POST_CONTENT, content); cv.put(POST_DATE,date); cv.put(POST_AUTHOR,author); long rowInserted = database.insert(TABLE_NAME,null,cv); if(rowInserted != -1) Toast.makeText(context, "New row added, row id: " + rowInserted, Toast.LENGTH_SHORT).show(); else Toast.makeText(context, "Something wrong", Toast.LENGTH_SHORT).show(); Log.d("Insert: ", "Successful"); }
So the finale DBHandler will be as below:
package com.buzzmycode.workingwithsqlite; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.SQLException; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteException; import android.database.sqlite.SQLiteOpenHelper; import android.util.Log; import android.widget.Toast; public class DBHandler extends SQLiteOpenHelper { public static final String TABLE_NAME = "tsqlite"; public static final String DATABASE_NAME = "BMC"; public static final int DATABASE_VERSION = 1; public static final String POST_ID = "id"; public static final String POST_TITLE = "title"; public static final String POST_CONTENT = "content"; public static final String POST_DATE = "date"; public static final String POST_AUTHOR = "author"; private static DBHandler mInstance = null; static Context context; public static DBHandler getInstance(Context ctx) { if (mInstance == null) { mInstance = new DBHandler(ctx.getApplicationContext()); context = ctx; } return mInstance; } private DBHandler(Context ctx) { super(ctx, DATABASE_NAME, null, DATABASE_VERSION); } @Override public void onCreate(SQLiteDatabase db) { String CREATE_POST_TABLE = "CREATE TABLE " + TABLE_NAME + "(" + POST_ID + " INTEGER PRIMARY KEY," + POST_TITLE + " TEXT," + POST_CONTENT + " TEXT," + POST_DATE + " TEXT," + POST_AUTHOR + " TEXT" + ");"; db.execSQL(CREATE_POST_TABLE); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME); onCreate(db); } public void addEntry(String title, String content, String date, String author) throws SQLiteException { SQLiteDatabase database = this.getWritableDatabase(); ContentValues cv = new ContentValues(); Log.d("Insert: ", "Inserting .."); cv.put(POST_TITLE, title); cv.put(POST_CONTENT, content); cv.put(POST_DATE,date); cv.put(POST_AUTHOR,author); long rowInserted = database.insert(TABLE_NAME,null,cv); if(rowInserted != -1) Toast.makeText(context, "New row added, row id: " + rowInserted, Toast.LENGTH_SHORT).show(); else Toast.makeText(context, "Something wrong", Toast.LENGTH_SHORT).show(); Log.d("Insert: ", "Successful"); } }
Step 6. This will be the AndroidManifest.xml.
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.buzzmycode.workingwithsqlite"> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:supportsRtl="true" android:theme="@style/AppTheme"> <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest>
Step 7. Finally, run your project you will be having following output.
Here the data is entered into the Sqlite. In the upcoming post, I will show you how to check the SQLite database. I hope you did it successfully and have the correct output. for any query comment below.