Book App using SQLite - Android Studio Tutorial

     DESCRIPTION     

This tutorial is about creating the Book App using SQLite. I'll use Tabbed Activity, swipe to change the page. Each record in SQLite file contains Id(as page no), Chapter Name, Title, Detail.
Book App using SQLite - Android Studio Tutorial

     VIDEO     


     SOURCE CODE     

Step 1: Create a new project OR Open your project (Use Tabbed Activity)

Step 2: Create assets folder. Place 'mybook' SQLite file in assets folder

Step 3: Code

Model.java
package com.blogspot.devofandroid.bookappusingsqlite;

public class Model {
    int ids;
    String chapters;
    String titles;
    String details;

    //constructor
    public Model(int ids, String chapters, String titles, String details) {
        this.ids = ids;
        this.chapters = chapters;
        this.titles = titles;
        this.details = details;
    }

    public int getIds() {
        return ids;
    }

    public void setIds(int ids) {
        this.ids = ids;
    }

    public String getChapters() {
        return chapters;
    }

    public void setChapters(String chapters) {
        this.chapters = chapters;
    }

    public String getTitles() {
        return titles;
    }

    public void setTitles(String titles) {
        this.titles = titles;
    }

    public String getDetails() {
        return details;
    }

    public void setDetails(String details) {
        this.details = details;
    }
}

SqlLiteDbHelper.java
package com.blogspot.devofandroid.bookappusingsqlite;

import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.widget.Toast;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;

public class SqlLiteDbHelper extends SQLiteOpenHelper {

    private static final int DATABASE_VERSION =1;
    private static final  String DATABASE_NAME = "mybook";
    private static final String DB_PATH_SUFFIX = "/databases/";
    static Context mCtx;
    SqlLiteDbHelper(Context context){
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
        mCtx = context;
    }

    //get details from db
    public ArrayList<Model> getDetails(){
        SQLiteDatabase db = this.getReadableDatabase();
        ArrayList<Model> modelList = new ArrayList<>();
        Cursor cursor = db.rawQuery("SELECT * FROM booktable", null);
        if (cursor!=null){
            while (cursor.moveToNext()){
                Model count = new Model(cursor.getInt(0), cursor.getString(1), cursor.getString(2) , cursor.getString(3));
                modelList.add(count);
            }
            cursor.close();
            db.close();
        }
        return modelList;
    }

    public void CopyDatabaseFromAssets() throws IOException{
        InputStream myInput = mCtx.getAssets().open(DATABASE_NAME);
        //path to the created db
        String outFileName = getDatabasePath();
        //if the path doesnt exists first. create it
        File f = new File(mCtx.getApplicationInfo().dataDir + DB_PATH_SUFFIX);
        if (!f.exists())
            f.mkdir();

        //open the db as the output stream
        OutputStream myOutput = new FileOutputStream(outFileName);

        //transfer bytes from the inputfile to the output file
        byte[] buffer = new byte[1024];
        int length;
        while ((length = myInput.read(buffer))>0){
            myOutput.write(buffer,0,length);
        }
        //close stream
        myOutput.flush();
        myOutput.close();
        myInput.close();
    }

    private static String getDatabasePath() {
        return mCtx.getApplicationInfo().dataDir + DB_PATH_SUFFIX
                + DATABASE_NAME;
    }
    public SQLiteDatabase openDataBase() throws SQLException{
        File dbFile = mCtx.getDatabasePath(DATABASE_NAME);
        if (!dbFile.exists()){
            try {
                CopyDatabaseFromAssets();
                Toast.makeText(mCtx, "Coppying success from assets folder", Toast.LENGTH_SHORT).show();
            }catch (IOException e){
                throw new RuntimeException("Error creating source database", e);
            }
        }
        return SQLiteDatabase.openDatabase(dbFile.getPath(), null,
                SQLiteDatabase.NO_LOCALIZED_COLLATORS | SQLiteDatabase.CREATE_IF_NECESSARY);
    }

    @Override
    public void onCreate(SQLiteDatabase sqLiteDatabase) {

    }

    @Override
    public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {

    }
}

activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/main_content"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    tools:context=".MainActivity">

    <android.support.design.widget.AppBarLayout
        android:id="@+id/appbar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:paddingTop="@dimen/appbar_padding_top"
        android:theme="@style/AppTheme.AppBarOverlay">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:layout_weight="1"
            android:background="?attr/colorPrimary"
            app:layout_scrollFlags="scroll|exitUntilCollapsed"
            app:popupTheme="@style/AppTheme.PopupOverlay"
            app:title="@string/app_name">

        </android.support.v7.widget.Toolbar>

    </android.support.design.widget.AppBarLayout>

    <android.support.v4.view.ViewPager
        android:id="@+id/container"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_behavior="@string/appbar_scrolling_view_behavior" />

</android.support.design.widget.CoordinatorLayout>

fragment_main.xml
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/constraintLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity$PlaceholderFragment">

    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical"
            android:padding="5dp">
            <View
                android:layout_width="50dp"
                android:layout_height="1dp"
                android:layout_gravity="center"
                android:background="@color/colorPrimaryDark"/>
            <TextView
                android:id="@+id/pageTv"
                android:text="01"
                android:textAlignment="center"
                android:layout_width="match_parent"
                android:layout_height="wrap_content" />
            <View
                android:layout_width="50dp"
                android:layout_height="1dp"
                android:layout_gravity="center"
                android:background="@color/colorPrimaryDark"/>
            <TextView
                android:id="@+id/chaptTv"
                android:text="Chapter"
                android:textStyle="bold|italic"
                android:textAlignment="center"
                android:textColor="@color/colorPrimaryDark"
                android:textSize="30sp"
                android:layout_width="match_parent"
                android:layout_height="wrap_content" />
            <TextView
                android:id="@+id/titleTv"
                android:text="Title"
                android:textStyle="bold"
                android:textColor="#000"
                android:textSize="22sp"
                android:layout_width="match_parent"
                android:layout_height="wrap_content" />
            <TextView
                android:id="@+id/detailTv"
                android:text="Detail of the title"
                android:textColor="#000"
                android:layout_width="match_parent"
                android:layout_height="wrap_content" />
        </LinearLayout>
    </ScrollView>

    <TextView
        android:id="@+id/section_label"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="@dimen/activity_horizontal_margin"
        android:layout_marginTop="@dimen/activity_vertical_margin"
        android:layout_marginEnd="@dimen/activity_horizontal_margin"
        android:layout_marginBottom="@dimen/activity_vertical_margin"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintTop_toTopOf="@+id/constraintLayout"
        tools:layout_constraintLeft_creator="1"
        tools:layout_constraintTop_creator="1" />

</FrameLayout>

MainActivity.java
package com.blogspot.devofandroid.bookappusingsqlite;

import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;

import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;

import android.widget.TextView;

import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {

    /**
     * The {@link android.support.v4.view.PagerAdapter} that will provide
     * fragments for each of the sections. We use a
     * {@link FragmentPagerAdapter} derivative, which will keep every
     * loaded fragment in memory. If this becomes too memory intensive, it
     * may be best to switch to a
     * {@link android.support.v4.app.FragmentStatePagerAdapter}.
     */
    private SectionsPagerAdapter mSectionsPagerAdapter;

    /**
     * The {@link ViewPager} that will host the section contents.
     */
    private ViewPager mViewPager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        // Create the adapter that will return a fragment for each of the three
        // primary sections of the activity.
        mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());

        // Set up the ViewPager with the sections adapter.
        mViewPager = (ViewPager) findViewById(R.id.container);
        mViewPager.setAdapter(mSectionsPagerAdapter);


    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    /**
     * A placeholder fragment containing a simple view.
     */
    public static class PlaceholderFragment extends Fragment {
        /**
         * The fragment argument representing the section number for this
         * fragment.
         */
        private static final String ARG_SECTION_NUMBER = "section_number";

        public PlaceholderFragment() {
        }

        /**
         * Returns a new instance of this fragment for the given section
         * number.
         */
        public static PlaceholderFragment newInstance(int sectionNumber) {
            PlaceholderFragment fragment = new PlaceholderFragment();
            Bundle args = new Bundle();
            args.putInt(ARG_SECTION_NUMBER, sectionNumber);
            fragment.setArguments(args);
            return fragment;
        }

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                 Bundle savedInstanceState) {
            View v = inflater.inflate(R.layout.fragment_main, container, false);
            TextView mPageTv, mChaptTv, mTitleTv, mDetailTv;
            mPageTv = v.findViewById(R.id.pageTv);
            mChaptTv = v.findViewById(R.id.chaptTv);
            mTitleTv = v.findViewById(R.id.titleTv);
            mDetailTv = v.findViewById(R.id.detailTv);

            SqlLiteDbHelper dbHelper;
            ArrayList<Model> modelList;
            int page = 0;
            String chap="", title="", detail="";
            modelList = new ArrayList<>();
            modelList.clear();
            dbHelper = new SqlLiteDbHelper(getContext());
            dbHelper.openDataBase();
            modelList = dbHelper.getDetails();

            if (getArguments().getInt(ARG_SECTION_NUMBER)==1){
                //get first record
                Model count = modelList.get(0);
                //save record in strings
                page = page + count.getIds();
                chap = chap + count.getChapters();
                title = title + count.getTitles();
                detail = detail + count.getDetails().replace(",,,,","\n");
                //set in TextView
                mPageTv.setText(page+"");
                mChaptTv.setText(chap);
                mTitleTv.setText(title);
                mDetailTv.setText(detail);

                return v;
            }
            if (getArguments().getInt(ARG_SECTION_NUMBER)==2){
                //get second record
                Model count = modelList.get(1);
                //save record in strings
                page = page + count.getIds();
                chap = chap + count.getChapters();
                title = title + count.getTitles();
                detail = detail + count.getDetails().replace(",,,,","\n");
                //set in TextView
                mPageTv.setText(page+"");
                mChaptTv.setText(chap);
                mTitleTv.setText(title);
                mDetailTv.setText(detail);

                return v;
            }
            if (getArguments().getInt(ARG_SECTION_NUMBER)==3){
                //get third record
                Model count = modelList.get(2);
                //save record in strings
                page = page + count.getIds();
                chap = chap + count.getChapters();
                title = title + count.getTitles();
                detail = detail + count.getDetails().replace(",,,,","\n");
                //set in TextView
                mPageTv.setText(page+"");
                mChaptTv.setText(chap);
                mTitleTv.setText(title);
                mDetailTv.setText(detail);

                return v;
            }
            if (getArguments().getInt(ARG_SECTION_NUMBER)==4){
                //get fourth record
                Model count = modelList.get(3);
                //save record in strings
                page = page + count.getIds();
                chap = chap + count.getChapters();
                title = title + count.getTitles();
                detail = detail + count.getDetails().replace(",,,,","\n");
                //set in TextView
                mPageTv.setText(page+"");
                mChaptTv.setText(chap);
                mTitleTv.setText(title);
                mDetailTv.setText(detail);

                return v;
            }
            if (getArguments().getInt(ARG_SECTION_NUMBER)==5){
                //get fifth record
                Model count = modelList.get(4);
                //save record in strings
                page = page + count.getIds();
                chap = chap + count.getChapters();
                title = title + count.getTitles();
                detail = detail + count.getDetails().replace(",,,,","\n");
                //set in TextView
                mPageTv.setText(page+"");
                mChaptTv.setText(chap);
                mTitleTv.setText(title);
                mDetailTv.setText(detail);

                return v;
            }

            return v;
        }
    }

    /**
     * A {@link FragmentPagerAdapter} that returns a fragment corresponding to
     * one of the sections/tabs/pages.
     */
    public class SectionsPagerAdapter extends FragmentPagerAdapter {

        public SectionsPagerAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {
            // getItem is called to instantiate the fragment for the given page.
            // Return a PlaceholderFragment (defined as a static inner class below).
            return PlaceholderFragment.newInstance(position + 1);
        }

        @Override
        public int getCount() {
            // Show 5 total pages.
            return 5;
        }
    }
}

Step 4: Run Project

Output


     DOWNLOAD FROM GITHUB     

 Download from github

Comments

Popular posts from this blog

Picture In Picture | Android Studio | Kotlin

Manage External Storage Permission | Android Studio | Kotlin

Add a Back Button to Action Bar Android Studio (Kotlin)