Display data Recyclerview using SQLiteCursor in Android, SQLite is an open source embedded database. SQLite is one of the most widely deployed databases in the world. SQLite database is mainly used in Smartphone operating Systems like IOS, Android etc. Android SQLite database has three main Classes. in this tutorial, we will learn how to Display data Recyclerview using SQLiteCursor in Android. so let’s start…

  • SQLiteOpenHelper Class
  • SQLiteDatabase Class
  • SQLiteCursor Class

SQLiteOpenHelper Class: – SQLiteOpenHelper class has mainly two methods onCreate and onUpgrade. onCreate method is used to create the table. onUpgrade method is used to upgrade the database.

SQLiteDatabase class: – SQLiteDabase is used to open the database either in readable or writable form. it has two methods

Writable form

// writable form
 
SQLiteDatabase db = this.getWritableDatabase();

Readable form

// Readable form
 
SQLiteDatabase db = this.getReadableDatabase();

SQLiteCursor Class: – SQLiteCursor class is used to iterate the table.

Display data Recyclerview using SQLiteCursor in Android: –

Download APK –    [media-downloader media_id=”723″ texts=”APK”]

Download Project – Download Here

Wants to Learn Android application development from the scratch  ?

Output Result: –

1.Create a project in android studio name it Databasechecker. Now Create a Java file in java>packagename>MainActivity.java . MainActivity.java file is the launcher activity by which user can enter the details into the database.

package com.mytrendin.databasecheck;

import android.content.Intent;
import android.database.Cursor;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {
        Button submit,show;
        DatabaseHelper databaseHelper;

         EditText etname,etemail,etcompany,etnumber;
         String name,city,company,country ;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        etname = (EditText) findViewById(R.id.etname);
        etemail = (EditText) findViewById(R.id.etemail);
        etcompany = (EditText) findViewById(R.id.etcompany);
        etnumber = (EditText) findViewById(R.id.etphone);
        submit = (Button) findViewById(R.id.submit);


        submit = (Button) findViewById(R.id.submit);
        show= (Button) findViewById(R.id.show);

        databaseHelper = new DatabaseHelper(this);


        submit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                name = etname.getText().toString();
                city = etemail.getText().toString();
                company=etcompany.getText().toString();
                country = etnumber.getText().toString();
                //Toast.makeText(MainActivity.this,name, Toast.LENGTH_SHORT).show();
                if (name.isEmpty() && city.isEmpty()&& company.isEmpty()&& country.isEmpty()){

                    Toast.makeText(MainActivity.this, "please fill details", Toast.LENGTH_SHORT).show();
                }else {

                    databaseHelper.insertdata(name,company,city,country);
                    etname.setText("");
                    etemail.setText("");
                    etcompany.setText("");
                    etnumber.setText("");
                    Intent intent = new Intent(MainActivity.this,Viewall.class);
                    startActivity(intent);

                }
            }
        });

        show.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MainActivity.this,Viewall.class);
                startActivity(intent);
            }
        });
    }
}

2. Create a XML file in res>layout>activity_main.xml. This XML file contains some Edittext to get the value from the user and send them to the database.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/snack"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    >

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:layout_centerInParent="true"
        android:layout_marginTop="30dp">

        <EditText
            android:id="@+id/etname"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textColorHint="#aeb0a5"
            android:hint="Name"
            android:layout_gravity="center"
            android:inputType="text"
            android:background="#00000000"
            android:textSize="12dp"
            android:letterSpacing="0.1"/>

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="0.5dp"
            android:background="#c1c1c1"
            android:layout_marginLeft="60dp"
            android:layout_marginRight="60dp"
            android:layout_marginTop="5dp"

            ></LinearLayout>

        <EditText
            android:id="@+id/etemail"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textColorHint="#aeb0a5"
            android:hint="city"
            android:layout_gravity="center"
            android:inputType="text"
            android:background="#00000000"
            android:textSize="12dp"
            android:letterSpacing="0.1"
            android:layout_marginTop="30dp"/>

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="0.5dp"
            android:background="#c1c1c1"
            android:layout_marginLeft="60dp"
            android:layout_marginRight="60dp"
            android:layout_marginTop="5dp"
            ></LinearLayout>

        <EditText
            android:id="@+id/etcompany"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textColorHint="#aeb0a5"
            android:hint="Company"
            android:layout_gravity="center"
            android:inputType="text"
            android:background="#00000000"
            android:textSize="12dp"
            android:letterSpacing="0.1"
            android:layout_marginTop="30dp"/>

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="0.5dp"
            android:background="#c1c1c1"
            android:layout_marginLeft="60dp"
            android:layout_marginRight="60dp"
            android:layout_marginTop="5dp"
            ></LinearLayout>
        <EditText
            android:id="@+id/etphone"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textColorHint="#aeb0a5"
            android:hint="country"
            android:layout_gravity="center"
            android:inputType="text"
            android:background="#00000000"
            android:textSize="12dp"
            android:letterSpacing="0.1"
            android:layout_marginTop="30dp"/>

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="0.5dp"
            android:background="#c1c1c1"
            android:layout_marginLeft="60dp"
            android:layout_marginRight="60dp"
            android:layout_marginTop="10dp"
            ></LinearLayout>


        <!--


          <ImageView
              android:layout_width="130dp"
              android:layout_height="70dp"
              android:src="@drawable/signin"
              android:scaleType="fitXY"
              android:layout_gravity="center"
              android:layout_marginTop="22dp"
              />
          -->

        <Button
            android:id="@+id/submit"
            android:layout_width="200dp"
            android:layout_height="40dp"
            android:scaleType="fitXY"
            android:text="Submit"
            android:layout_gravity="center"
            android:layout_marginTop="22dp"
            android:textSize="12dp"
            android:background="#c1c1c1"


            />
        <Button
            android:id="@+id/show"
            android:layout_width="200dp"
            android:layout_height="40dp"
            android:scaleType="fitXY"
            android:text="View"
            android:layout_gravity="center"
            android:layout_marginTop="22dp"
            android:textSize="12dp"
            android:background="#c1c1c1"


            />
        
    </LinearLayout>




</RelativeLayout>

3. Create a java file in java>com.mytrendin.databasecheck>DataModel. name it DataModel.java. This file will hold the values in the form getter and setter methods.

package com.mytrendin.databasecheck;

/**
 * Created by csa on 3/1/2017.
 */

public class DataModel {

    public String name;
    public String county;
    public String city;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getCounty() {
        return county;
    }

    public void setCounty(String county) {
        this.county = county;
    }

    public String getCity() {
        return city;
    }

    public void setCity(String city) {
        this.city = city;
    }
}

4. Now create a java file in java>com.mytrendin.databasecheck>DatabaseHelper . name it DatabaseHelper.java .This file holds all the operation all SQLite database.

package com.mytrendin.databasecheck;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by csa on 3/1/2017.
 */

public class DatabaseHelper extends SQLiteOpenHelper {


    public static String DATABASE = "database.db";
    public static String TABLE ="mytable";
    public static String NAME ="name";
    public static String COMPANY ="company";
    public static String CITY ="city";
    public static String COUNTRY ="country";
    String br;

    public DatabaseHelper(Context context) {
        super(context, DATABASE, null, 1);

    }

    @Override
    public void onCreate(SQLiteDatabase db) {
         //  br= "CREATE TABLE mytable(name TEXT,company TEXT,city TEXT,country TEXT);";
         br = "CREATE TABLE "+TABLE+"("+NAME+ " Text, "+COMPANY+ " Text, "+CITY+ " Text, "+COUNTRY+ " Text);";
        db.execSQL(br);

    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
      db.execSQL("DROP TABLE IF EXISTS "+TABLE+" ;");
    }


    public void insertdata(String name,String company ,String city,String country){
        System.out.print("Hello "+br);
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues contentValues= new ContentValues();


            contentValues.put(NAME, name);
            contentValues.put(COMPANY, company);
            contentValues.put(CITY,city);
            contentValues.put(COUNTRY,country);
            db.insert(TABLE,null,contentValues);


    }

    public List<DataModel> getdata(){
       // DataModel dataModel = new DataModel();
        List<DataModel> data=new ArrayList<>();
        SQLiteDatabase db = this.getWritableDatabase();
        Cursor cursor = db.rawQuery("select * from "+TABLE+" ;",null);
         StringBuffer stringBuffer = new StringBuffer();
        DataModel dataModel = null; 
        while (cursor.moveToNext()) {
            dataModel= new DataModel();
            String name = cursor.getString(cursor.getColumnIndexOrThrow("name"));
            String country = cursor.getString(cursor.getColumnIndexOrThrow("country"));
            String city = cursor.getString(cursor.getColumnIndexOrThrow("city"));
            dataModel.setName(name);
            dataModel.setCity(city);
            dataModel.setCounty(country);
            stringBuffer.append(dataModel);
           // stringBuffer.append(dataModel);
            data.add(dataModel);
        }

        for (DataModel mo:data ) {

            Log.i("Hellomo",""+mo.getCity());
        }

        //

        return data;
    }



}

Related:

Understanding the use of Application Class in Android

What is Singleton Class(Design Pattern)?

Drag and Swipe with RecyclerView

Swipeable RecyclerView in Android

ItemDecoration in RecyclerView in Android

Best security tips for android phone

Secure phone contacts on your gmail account

Best Android apps to hide Photos and Videos

5+ best free YouTube intro maker websites

Watch Related Video

5. Now create a java file in java>com.mytrendin.databasecheck>Viewall. name it Viewall.java. This file will show the data in Recyclerview in an arranged manner.

package com.mytrendin.databasecheck;

import android.app.Activity;
import android.database.Cursor;
import android.os.Bundle;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by csa on 3/1/2017.
 */

public class Viewall extends Activity {

     Button show;
    DatabaseHelper database;
    RecyclerView recyclerView;
    RecycleAdapter recycler;
    List<DataModel> datamodel;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.view);
        show = (Button) findViewById(R.id.view);
        datamodel =new ArrayList<DataModel>();
        recyclerView = (RecyclerView) findViewById(R.id.recycle);


        show.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                database = new DatabaseHelper(Viewall.this);
                datamodel=  database.getdata();
                recycler =new RecycleAdapter(datamodel);


                Log.i("HIteshdata",""+datamodel);
                RecyclerView.LayoutManager reLayoutManager =new LinearLayoutManager(getApplicationContext());
                recyclerView.setLayoutManager(reLayoutManager);
                recyclerView.setItemAnimator(new DefaultItemAnimator());
                recyclerView.setAdapter(recycler);


            }
        });

    }
}

6. Now add the recyclerview dependencies in build.gradle file which supports Material design.add the following code to build.gradle file.

compile 'com.android.support:design:25.0.1'

project build.gradle file: –

apply plugin: 'com.android.application'

android {
    compileSdkVersion 25
    buildToolsVersion "25.0.2"
    defaultConfig {
        applicationId "com.mytrendin.databasecheck"
        minSdkVersion 13
        targetSdkVersion 25
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile 'com.android.support:appcompat-v7:25.1.0'

compile ‘com.android.support:design:25.0.1’

    testCompile 'junit:junit:4.12'
}

7. Update or Create color.xml, strings.xml, styles.xml files in res>values folder.

color.xml: –

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="colorPrimary">#00B873</color>
    <color name="colorPrimaryDark">#303F9F</color>
    <color name="colorGray">#495C67</color>
    <color name="colorAccent">#FF4081</color>
    <color name="colorOrange">#F68159</color>
    <color name="colorLightGray">#a6abae</color>

    <color name="colorBackroundWhite">#f0f2ea</color>
</resources>

strings.xml file: –

<resources>
    <string name="app_name">Databasecheck</string>
</resources>

styles.xml file: –

<resources>

    <!-- Base application theme. -->
    <style name="AppTheme" parent="Theme.AppCompat.Light">
        <!-- Customize your theme here. -->
        <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
        <item name="colorAccent">@color/colorAccent</item>
    </style>

</resources>

8. Create a XML file inside drawable folder(drawable>cardview_bg.xml). which is responsible for the background of an itemview in recyclerview.

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle" >
    <solid android:color="#ffffff" />
    <stroke android:width="1.5dp" android:color="@color/colorBackroundWhite"/>
    <corners android:radius="2dp"/>
</shape>

9. Create a XML file inside drawable folder(drawable>roun_rect_orange.xml). which is responsible to shape of an itemview in recyclerview.

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">

    <solid android:color="@color/colorOrange"></solid>

    <padding
        android:bottom="6dp"
        android:left="18dp"
        android:right="18dp"
        android:top="6dp"></padding>

    <corners
        android:bottomLeftRadius="20dp"
        android:bottomRightRadius="20dp"
        android:topLeftRadius="20dp"
        android:topRightRadius="20dp" />

</shape>

10.create a XML file in res>layout folder name it itemview.xml. This XML file renders a single row in recycler view by displaying name, company, city.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">


    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="80dp"
        android:layout_marginTop="20dp"
        >

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:background="@drawable/cardview_bg">

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_gravity="center_vertical"
                android:layout_margin="5dp"
                android:orientation="horizontal"
                android:weightSum="5">

                <ImageView
                    android:id="@+id/profile_image"
                    android:layout_width="0dp"
                    android:layout_height="55dp"
                    android:layout_weight="1"
                    android:src="@drawable/person3"
                     />

                <LinearLayout
                    android:layout_width="0dp"
                    android:layout_height="match_parent"
                    android:layout_weight="2.8"
                    android:gravity="center_vertical"
                    android:orientation="vertical"
                    android:paddingLeft="10dp">

                    <TextView
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:text="Jessyka swan"
                        android:textColor="@color/colorGray"
                        android:textSize="15dp"
                        android:textStyle="bold"
                        android:id="@+id/city1"

                        />

                    <TextView
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_marginTop="2dp"
                        android:text="Team leader"
                        android:id="@+id/name1"
                        android:textColor="@color/colorLightGray"
                        android:textSize="14dp" />
                </LinearLayout>

                <LinearLayout
                    android:layout_width="0dp"
                    android:layout_height="match_parent"
                    android:layout_weight="1.2"
                    android:gravity="center">

                    <TextView
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:background="@drawable/roun_rect_orange"
                        android:text="Invite"
                        android:id="@+id/country1"
                        android:textColor="#fff"
                        android:textSize="15sp"
                        android:textStyle="bold" />
                </LinearLayout>

            </LinearLayout>
        </LinearLayout>
    </RelativeLayout>

</RelativeLayout>

11. Create a layout XML file inside layout folder name it view.xml. this file contains Recyclerview.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">

    <Button
        android:text="show"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/view" />

    <android.support.v7.widget.RecyclerView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/recycle"
        >

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



</LinearLayout>

12.  Create an Adapter class inside java folder name it as RecycleAdapter. Here onCreateViewHolder() method inflates itemview.xml . In onBindViewHolder() method the appropriate data (name, country, and city) set to each row.

package com.mytrendin.databasecheck;

import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by csa on 3/1/2017.
 */

public class RecycleAdapter extends RecyclerView.Adapter<RecycleAdapter.Myholder> {
    List<DataModel> dataModelArrayList;

    public RecycleAdapter(List<DataModel> dataModelArrayList) {
        this.dataModelArrayList = dataModelArrayList;
    }

    class Myholder extends RecyclerView.ViewHolder{
        TextView name,city,country;

        public Myholder(View itemView) {
            super(itemView);

            name = (TextView) itemView.findViewById(R.id.name1);
            city = (TextView) itemView.findViewById(R.id.city1);
            country = (TextView) itemView.findViewById(R.id.country1);
        }
    }


    @Override
    public Myholder onCreateViewHolder(ViewGroup parent, int viewType) {
         View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.itemview,null);
         return new Myholder(view);

    }

    @Override
    public void onBindViewHolder(Myholder holder, int position) {
        DataModel dataModel=dataModelArrayList.get(position);
        holder.name.setText(dataModel.getName());
        holder.city.setText(dataModel.getCity());
        holder.country.setText(dataModel.getCounty());

    }

    @Override
    public int getItemCount() {
        return dataModelArrayList.size();
    }
}

13. finally update your AndroidManifest.xml.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.mytrendin.databasecheck">

    <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>
        <activity android:name=".Viewall"></activity>
    </application>

</manifest>

If You are Beginner Learn Android application development from the scratch


If you really liked the article, please subscribe to our YouTube Channel for videos related to this article.Please find us on Twitter and Facebook.

If you really liked the article, please subscribe to our YouTube Channel for videos related to this article.Please find us on Twitter and Facebook.

Related Posts