Insert data in to sqlite and display on Android Listview

15/04/2017   03:12:13 PM

Hello in this android article i will explain how to insert data in to sqlite database & display on Listview Android.In previous example we seen simple way to insert and modify data in sqlite database,here in this example we will see advance concept to store data in sqlite and this time we display data on listview.

1. Create a new project in android studio

2. Create a java class Controllerdb.java and extends SQLiteOpenHelper to create sqlite database

What is SQLiteOpenHelper?

SQLiteOpenHelper is predefined class in android to create and manage sqlite database and tables.

It has methods to create, delete, and execute sql statements.

It manages all databases with version management

So in this example I used SQLiteOpenHelper class

package com.simplylearnprogramming.slitetolistview;
import  android.content.Context;
import  android.database.sqlite.SQLiteDatabase;
import  android.database.sqlite.SQLiteOpenHelper;
/**
 * Created by Shree on 10/22/2016.
 */
public class Controllerdb extends SQLiteOpenHelper
{
    private static final String DATABASE_NAME="SqliteListviewDB";
    public Controllerdb(Context applicationcontext) {
        super(applicationcontext, DATABASE_NAME, null,1);
    }
    @Override
    public void onCreate(SQLiteDatabase db) {
        //create table to insert data
        String query;
        query = "CREATE TABLE IF NOT EXISTS UserDetails(Id INTEGER PRIMARY KEY AUTOINCREMENT,Username VARCHAR,Mailid VARCHAR,Age VARCHAR);";
        db.execSQL(query);

 
    }
    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        String query ;
        query = "DROP TABLE IF EXISTS UserDetails";
        db.execSQL(query);
        onCreate(db);
    }
}

 

3. To design activity go to activity_main.xml  for insert data in to sqlite 

<?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.xperiaitinnovations.slitetolistview.MainActivity">
    <EditText
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/etName"
        android:layout_alignParentTop="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_alignParentRight="true"
        android:layout_alignParentEnd="true"
        android:hint="Enter Name"
        />
    <EditText
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/etMailid"
        android:layout_below="@+id/etName"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_alignRight="@+id/etName"
        android:layout_alignEnd="@+id/etName"
        android:hint="Enter MailId"
        />
    <EditText
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/etAge"
        android:layout_below="@+id/etMailid"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_alignRight="@+id/etMailid"
        android:layout_alignEnd="@+id/etMailid"
        android:hint="Enter Age"
        />
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Submit"
        android:id="@+id/btnSave"
        android:layout_centerVertical="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_marginLeft="41dp"
        android:layout_marginStart="41dp" />
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Show"
        android:id="@+id/btnShow"
        android:layout_centerVertical="true"
        android:layout_alignParentRight="true"
        android:layout_alignParentEnd="true" />
</RelativeLayout>
 

 

4. Add following code in to MainActivity.java for insert data to sqlite 
 
package com.simplylearnprogramming.slitetolistview;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
 
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    Controllerdb db =new Controllerdb(this);
    SQLiteDatabase database;
    EditText Name,Mail,Age;
    Button Submitdatabtn,Showdatabtn;
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Name= (EditText) findViewById(R.id.etName);
        Mail= (EditText) findViewById(R.id.etMailid);
        Age= (EditText) findViewById(R.id.etAge);
        Submitdatabtn= (Button) findViewById(R.id.btnSave);
        Showdatabtn=(Button) findViewById(R.id.btnShow);
        Submitdatabtn.setOnClickListener(this);
        Showdatabtn.setOnClickListener(this);
    }
 
    @Override
    public void onClick(View v)
    {
        if(v.getId()==R.id.btnSave)
        {
            database=db.getWritableDatabase();
            database.execSQL("INSERT INTO UserDetails(Username,Mailid,Age)VALUES('"+Name.getText()+"','"+Mail.getText()+"','"+Age.getText()+"')" );
            Toast.makeText(this,"Data Inserted To Sqlite Database",Toast.LENGTH_LONG).show();
       }
      else  if(v.getId()==R.id.btnShow)
        {
Intent intent=new Intent(this,ShowdataListview.class);
startActivity(intent);
 
        }
    }
}

 

5. Add new activity in project and  Add a listview  

 

6. Add xml layout file res/layout/New/xml/layout

 
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <TextView
        android:layout_width="20dp"
        android:layout_height="wrap_content"
        android:text="New Text"
        android:id="@+id/tvid" />
    <TextView
        android:layout_width="100dp"
        android:layout_height="wrap_content"
        android:text="New Text"
        android:id="@+id/tvname"
        android:layout_marginLeft="15dp"
        android:layout_marginRight="15dp" />
    <TextView
        android:layout_width="100dp"
        android:layout_height="wrap_content"
        android:text="New Text"
        android:id="@+id/tvmailid"
        android:layout_marginRight="15dp"
        android:layout_marginLeft="15dp" />
    <TextView
        android:layout_width="25dp"
        android:layout_height="wrap_content"
        android:text="New Text"
        android:id="@+id/tvage"
        android:layout_marginLeft="15dp"
        android:layout_marginRight="15dp" />
</LinearLayout>

 

7. Create a class  CustomAdapter.java  &  extends  predefined BaseAdapter class 

package com.simplylearnprogramming.slitetolistview;
 
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import java.util.ArrayList;
 
/**
 * Created by Shree on 10/22/2016.
 */
public class CustomAdapter extends BaseAdapter {
    private Context mContext;
    Controllerdb controldb;
    SQLiteDatabase db;
    private ArrayList<String> Id = new ArrayList<String>();
    private ArrayList<String> Name = new ArrayList<String>();
    private ArrayList<String> MailId = new ArrayList<String>();
    private ArrayList<String> Age = new ArrayList<String>();
    public CustomAdapter(Context  context,ArrayList<String> Id,ArrayList<String> Name, ArrayList<String> MailId,ArrayList<String> Age
)
    {
        this.mContext = context;
        this.Id = Id;
        this.Name = Name;
        this.MailId = MailId;
        this.Age=Age
    }
    @Override
    public int getCount() {
        return Id.size();
    }
    @Override
    public Object getItem(int position) {
        return null;
    }
    @Override
    public long getItemId(int position) {
        return 0;
    }
    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        final    viewHolder holder;
        controldb =new Controllerdb(mContext);
        LayoutInflater layoutInflater;
        if (convertView == null) {
            layoutInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            convertView = layoutInflater.inflate(R.layout.layout, null);
            holder = new viewHolder();
            holder.id = (TextView) convertView.findViewById(R.id.tvid);
            holder.name = (TextView) convertView.findViewById(R.id.tvname);
            holder.mail = (TextView) convertView.findViewById(R.id.tvmailid);
            holder.age = (TextView) convertView.findViewById(R.id.tvage);
            convertView.setTag(holder);
        } else {
            holder = (viewHolder) convertView.getTag();
        }
        holder.id.setText(Id.get(position));
        holder.name.setText(Name.get(position));
        holder.mail.setText(MailId.get(position));
        holder.age.setText(Age.get(position));
        return convertView;
    }
   public class viewHolder {
        TextView id;
        TextView name;
        TextView mail;
        TextView age;
    }
}

 

8. Add following code to ShowdataListview.java class for display data to ListView

package com.simplylearnprogramming.slitetolistview;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.ListView;
import java.util.ArrayList;
 
public class ShowdataListview extends AppCompatActivity {
    Controllerdb controllerdb = new Controllerdb(this);
    SQLiteDatabase db;
    private ArrayList<String> Id = new ArrayList<String>();
    private ArrayList<String> Name = new ArrayList<String>();
    private ArrayList<String> MailId = new ArrayList<String>();
    private ArrayList<String> Age = new ArrayList<String>();
    ListView lv;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_showdata_listview);
        lv = (ListView) findViewById(R.id.lstvw);
    }
    @Override
    protected void onResume() {
        displayData();
        super.onResume();
    }
    private void displayData() {
        db = controllerdb.getReadableDatabase();
        Cursor cursor = db.rawQuery("SELECT * FROM  UserDetails",null);
        Id.clear();
        Name.clear();
        MailId.clear();
        Age.clear(); 
    if (cursor.moveToFirst()) {
            do {
                Id.add(cursor.getString(cursor.getColumnIndex("Id")));
                Name.add(cursor.getString(cursor.getColumnIndex("Username")));
                MailId.add(cursor.getString(cursor.getColumnIndex("Mailid")));
                Age.add(cursor.getString(cursor.getColumnIndex("Age")));
            } while (cursor.moveToNext());
        }
        CustomAdapter ca = new CustomAdapter(ShowdataListview.this,Id, Name,MailId,Age);
        lv.setAdapter(ca);
        //code to set adapter to populate list
        cursor.close();
    }
}

 

OUTPUT 

1.Insert Data Into Sqlite Database

Insert Data Into Sqlite Android

2.Display Data From Sqlite To ListView

Display Data From Sqlite To ListView Android


Output

                   

Support us by Sharing