Skip to main content

Android List View using Custom Adapter and SQLite

following is a simple applicaton to create ListView using  Custom adapter.screenshot of the application  is like this .

ListView is not used in android Anymore. We use RecyclerView and CardView  in Android
  • RecyclerView Demo is available on the following link
http://androidtuts4u.blogspot.in/2017/04/android-recyclerview-example.html
  • RecyclerView with Cardview Example is available on the following link
http://androidtuts4u.blogspot.in/2017/09/android-card-view-example.html

The ListView below the submit button is populated using Custom Adapter.Data is stored and retrieved using SQLite databsase.

you can download the source code of this project from  google drive  https://drive.google.com/folderview?id=0BySLpWhqmbbdUXE5aTNhazludjQ&usp=sharing
click on the above link ->sign into  your  google account ->add this to your google drive -> open it in google drive and download it.

To create a simple application like this


1. Create a class which extends  SQLiteOpenHelper , this class is used to create SQLite database, The class is given below



package com.arun.democustomadapter;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;

public class SqlDbHelper extends SQLiteOpenHelper {
 public static final String DATABASE_TABLE = "PHONE_CONTACTS";

 public static final String COLUMN1 = "slno";
 public static final String COLUMN2 = "name";
 public static final String COLUMN3 = "phone";
 private static final String SCRIPT_CREATE_DATABASE = "create table "
   + DATABASE_TABLE + " (" + COLUMN1
   + " integer primary key autoincrement, " + COLUMN2
   + " text not null, " + COLUMN3 + " text not null);";

 public SqlDbHelper(Context context, String name, CursorFactory factory,
   int version) {
  super(context, name, factory, version);
  // TODO Auto-generated constructor stub

 }

 @Override
 public void onCreate(SQLiteDatabase db) {
  // TODO Auto-generated method stub
  db.execSQL(SCRIPT_CREATE_DATABASE);

 }

 @Override
 public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
  // TODO Auto-generated method stub
  db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE);
  onCreate(db);
 }

}



2. After creating the database we need another class which is used as handler to  insert,update,delete,update operation on our database . Handler class is given below


package com.arun.democustomadapter;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

public class SqlHandler {

 public static final String DATABASE_NAME = "MY_DATABASE";
 public static final int DATABASE_VERSION = 1;
 Context context;
 SQLiteDatabase sqlDatabase;
 SqlDbHelper dbHelper;

 public SqlHandler(Context context) {

  dbHelper = new SqlDbHelper(context, DATABASE_NAME, null,
    DATABASE_VERSION);
  sqlDatabase = dbHelper.getWritableDatabase();
 }

 public void executeQuery(String query) {
  try {

   if (sqlDatabase.isOpen()) {
    sqlDatabase.close();
   }

   sqlDatabase = dbHelper.getWritableDatabase();
   sqlDatabase.execSQL(query);

  } catch (Exception e) {

   System.out.println("DATABASE ERROR " + e);
  }

 }

 public Cursor selectQuery(String query) {
  Cursor c1 = null;
  try {

   if (sqlDatabase.isOpen()) {
    sqlDatabase.close();

   }
   sqlDatabase = dbHelper.getWritableDatabase();
   c1 = sqlDatabase.rawQuery(query, null);

  } catch (Exception e) {

   System.out.println("DATABASE ERROR " + e);

  }
  return c1;

 }

}



3. Now we created basic classes for all database operation .Now we need to design our main XML page,Main.xml is given below




<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

    xmlns:tools="http://schemas.android.com/tools"

    android:id="@+id/LinearLayout1"

    android:layout_width="match_parent"

    android:layout_height="fill_parent"

    android:orientation="vertical" >



    <TableLayout

        android:layout_width="match_parent"

        android:layout_height="wrap_content" >



        <TableRow

            android:id="@+id/tableRow1"

            android:layout_width="wrap_content"

            android:layout_height="wrap_content" >



            <TextView

                android:id="@+id/textView1"

                android:layout_width="wrap_content"

                android:layout_height="wrap_content"

                android:text="@string/name" />



            <EditText

                android:id="@+id/et_name"

                android:layout_width="wrap_content"

                android:layout_height="wrap_content"

                android:ems="10" >

            </EditText>

        </TableRow>



        <TableRow

            android:id="@+id/tableRow2"

            android:layout_width="wrap_content"

            android:layout_height="wrap_content" >



            <TextView

                android:id="@+id/textView1"

                android:layout_width="wrap_content"

                android:layout_height="wrap_content"

                android:text="@string/phone" />



            <EditText

                android:id="@+id/et_phone"

                android:layout_width="wrap_content"

                android:layout_height="wrap_content"

                android:ems="10" >

            </EditText>

        </TableRow>

    </TableLayout>



    <LinearLayout

        android:id="@+id/LinearLayout2"

        android:layout_width="match_parent"

        android:layout_height="wrap_content"

        android:orientation="vertical" >



        <Button

            android:id="@+id/btn_submit"

            android:layout_width="80dp"

            android:layout_height="40dp"

            android:layout_marginLeft="40dp"

            android:text="@string/submit" />

    </LinearLayout>



    <LinearLayout

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:layout_marginTop="20dp" >



        <TextView

            android:id="@+id/tv_slno"

            android:layout_width="50dp"

            android:layout_height="wrap_content"

            android:text="slno"

            android:textColor="#000" />



        <TextView

            android:id="@+id/tv_name"

            android:layout_width="100dp"

            android:layout_height="wrap_content"

            android:layout_marginLeft="10dp"

            android:text="@string/name"

            android:textColor="#000" />



        <TextView

            android:id="@+id/tv_phone"

            android:layout_width="match_parent"

            android:layout_height="wrap_content"

            android:layout_marginLeft="10dp"

            android:text="@string/phone"

            android:textColor="#000" />

    </LinearLayout>



    <ListView

        android:id="@+id/lv_custom_list"

        android:layout_width="match_parent"

        android:layout_height="wrap_content"

        android:layout_marginTop="10dp" >

    </ListView>



</LinearLayout>
4. After designing Main.xml next is to create the MainActivity, the class is given below



package com.arun.democustomadapter;

import java.util.ArrayList;

import android.app.Activity;
import android.database.Cursor;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;

public class MainActivity extends Activity {

 SqlHandler sqlHandler;
 ListView lvCustomList;
 EditText etName, etPhone;
 Button btnsubmit;

 @Override
 public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.main);

  lvCustomList = (ListView) findViewById(R.id.lv_custom_list);
  etName = (EditText) findViewById(R.id.et_name);
  etPhone = (EditText) findViewById(R.id.et_phone);
  btnsubmit = (Button) findViewById(R.id.btn_submit);
  sqlHandler = new SqlHandler(this);
  showList();
  btnsubmit.setOnClickListener(new OnClickListener() {

   @Override
   public void onClick(View v) {

    String name = etName.getText().toString();
    String phoneNo = etPhone.getText().toString();

    String query = "INSERT INTO PHONE_CONTACTS(name,phone) values ('"
      + name + "','" + phoneNo + "')";
    sqlHandler.executeQuery(query);
    showList();
    etName.setText("");
    etPhone.setText("");

   }
  });

 }

 private void showList() {

  ArrayList<contactlistitems> contactList = new ArrayList<contactlistitems>();
  contactList.clear();
  String query = "SELECT * FROM PHONE_CONTACTS ";
  Cursor c1 = sqlHandler.selectQuery(query);
  if (c1 != null &amp;&amp; c1.getCount() != 0) {
   if (c1.moveToFirst()) {
    do {
     ContactListItems contactListItems = new ContactListItems();

     contactListItems.setSlno(c1.getString(c1
       .getColumnIndex("slno")));
     contactListItems.setName(c1.getString(c1
       .getColumnIndex("name")));
     contactListItems.setPhone(c1.getString(c1
       .getColumnIndex("phone")));
     contactList.add(contactListItems);

    } while (c1.moveToNext());
   }
  }
  c1.close();

  ContactListAdapter contactListAdapter = new ContactListAdapter(
    MainActivity.this, contactList);
  lvCustomList.setAdapter(contactListAdapter);

 }

 @Override
 public boolean onCreateOptionsMenu(Menu menu) {
  getMenuInflater().inflate(R.menu.main, menu);
  return true;
 }
}
How code works>>>when the submit button is clicked values in EditTextfields are inserted into database that is written inside
                  btnsubmit.setOnClickListener(new OnClickListener() {

   @Override
   public void onClick(View v) {.....

then showList( ) function is called  which will populate value to listView .  To populate values we need to do the following

  I. select data from the database

           String query = "SELECT * FROM PHONE_CONTACTS ";

 II . Create a bean class for setting and getting values (ContactListItems)

III. Values selected from the databse is set to the object of the bean class

             
   ContactListItems contactListItems = new ContactListItems();

       contactListItems.setSlno(c1.getString(c1
    .getColumnIndex("slno")))
IV. Object of the bean class(contactListItems) is added to a ArrayList of type ContactListItems(Bean class)


     ArrayList<contactlistitems> contactList = new ArrayList<contactlistitems>();     contactList.add(contactListItems);

V. The Created ArrayList and context of the class is passed to CustomAdapter which will do the rest

       ContactListAdapter contactListAdapter = new ContactListAdapter(
    MainActivity.this, contactList);



5. The bean class is given below



  
package com.arun.democustomadapter;

public class ContactListItems {

 String slno;
 String name;
 String phone;

 public String getSlno() {
  return slno;
 }

 public void setSlno(String slno) {
  this.slno = slno;
 }

 public String getName() {
  return name;
 }

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

 public String getPhone() {
  return phone;
 }

 public void setPhone(String phone) {
  this.phone = phone;
 }

}

6. Then create a Custom Adapter class by extending BaseAdapter ,      class is given below
  
package com.arun.democustomadapter;

import java.util.ArrayList;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

public class ContactListAdapter extends BaseAdapter {

 Context context;
 ArrayList<ContactListItems> contactList;

 public ContactListAdapter(Context context, ArrayList<ContactListItems> list) {

  this.context = context;
  contactList = list;
 }

 @Override
 public int getCount() {

  return contactList.size();
 }

 @Override
 public Object getItem(int position) {

  return contactList.get(position);
 }

 @Override
 public long getItemId(int position) {

  return position;
 }

 @Override
 public View getView(int position, View convertView, ViewGroup arg2) {
  ContactListItems contactListItems = contactList.get(position);

  if (convertView == null) {
   LayoutInflater inflater = (LayoutInflater) context
     .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
   convertView = inflater.inflate(R.layout.contact_list_row, null);

  }
  TextView tvSlNo = (TextView) convertView.findViewById(R.id.tv_slno);
  tvSlNo.setText(contactListItems.getSlno());
  TextView tvName = (TextView) convertView.findViewById(R.id.tv_name);
  tvName.setText(contactListItems.getName());
  TextView tvPhone = (TextView) convertView.findViewById(R.id.tv_phone);
  tvPhone.setText(contactListItems.getPhone());

  return convertView;
 }

}


how custom Adapter works >>>> the main part of custom Adapter is
public View getView(int position, View convertView, ViewGroup arg2) {.....
to customize the listview we need to create an xml(contact_list_row.xml).This xml layout is the row of our listView.This layout is inflated using inflater service

           
    LayoutInflater inflater = (LayoutInflater) context

                       .getSystemService(Context.LAYOUT_INFLATER_SERVICE);

       convertView = inflater.inflate(R.layout.contact_list_row, null);
The value we passed through ArrayList(contactList) is set to corresponding textView < <
       ContactListItems contactListItems = contactList.get(position);
      TextView tvSlNo = (TextView) convertView.findViewById(R.id.tv_slno);
      tvSlNo.setText(contactListItems.getSlno());
6.The contact_list_row.xml is given below
    <?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/LinearLayout1"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal" >

    <TextView
        android:id="@+id/tv_slno"
        android:layout_width="50dp"
        android:layout_height="wrap_content"
        android:text="slno"
        android:textColor="#000" />

    <TextView
        android:id="@+id/tv_name"
        android:layout_width="100dp"
        android:layout_height="wrap_content"
        android:layout_marginLeft="10dp"
        android:text="TextView"
        android:textColor="#000" />

    <TextView
        android:id="@+id/tv_phone"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="10dp"
        android:text="TextView"
        android:textColor="#000" />

</LinearLayout>

Comments

  1. This comment has been removed by the author.

    ReplyDelete
  2. Hello and thanks for the post.It helped me a lot.
    I have one question thouhg.If I want to delete items from the list view (a whole listview item) using onItemLongClick for example,how should I proceed?

    Thanks!

    ReplyDelete
    Replies
    1. you can use this
      lvCustomList.setOnItemLongClickListener(new OnItemLongClickListener() {

      @Override
      public boolean onItemLongClick(AdapterView arg0, View arg1,
      int arg2, long arg3) {

      ContactListItems contactListItems = (ContactListItems)arg0.getItemAtPosition(arg2);
      String slno = contactListItems.getSlno();
      String delQuery = "DELETE FROM PHONE_CONTACTS WHERE slno='"+slno+"' ";
      sqlHandler.executeQuery(delQuery);
      showlist();

      return false;
      }
      });

      Delete
    2. hello sir the code written above is not working ...i am unable to create data base and insert value in it plz do somthing...plz

      Delete
    3. hey hello there! did you solve this issue yet? if not I could help, just answer .. cheers!

      Delete
    4. Hello Andres. Can you pls tell me how you solve it?

      Delete
  3. Thanks for your post......
    Is there any way to display Listview
    from database's content
    by using "Custom Adapter" Without using "getter setter method"?

    ReplyDelete
  4. im getting the same row in the list view repeatedlly can you explain how this works?

    ReplyDelete
    Replies
    1. i think there is a problem with the do..while loop in MainActivity.java please recheck it.

      Delete
  5. This is my showList() method:


    private void showList() {

    dbUser = new DBHelper(firsttab.this);
    dbUser.open();
    ArrayList userlist = new ArrayList();
    userlist.clear();
    Cursor c1 = dbUser.getUsers();
    if (c1 != null & c1.getCount() != 0) {
    if (c1.moveToFirst()) {
    do {
    UserList contactListItems = new UserList();

    contactListItems.Setid(c1.getString(c1
    .getColumnIndex("usersId")));
    contactListItems.SetUsername(c1.getString(c1
    .getColumnIndex("username")));
    contactListItems.SetPassword(c1.getString(c1
    .getColumnIndex("password")));
    contactListItems.setName(c1.getString(c1
    .getColumnIndex("name")));
    userlist.add(contactListItems);

    } while (c1.moveToNext());
    }
    }
    c1.close();
    CustomListAdaptor contactListAdapter = new CustomListAdaptor(
    firsttab.this, userlist);
    lvCustomList.setAdapter(contactListAdapter);

    }



    I would be very happy if you could help me.
    Thx anyway for the response.

    ReplyDelete
    Replies
    1. this looks fine please check your customAdapter class (ContactListAdapter.java)

      Delete
    2. I've been stuck on this for 2 days now , i really cant see where is my mistake this is really starting to be annoying.

      Thank you for you're support. Here is my class ,I think everything is correct.

      public class CustomListAdaptor extends BaseAdapter {

      Context context;
      ArrayList userlist;

      public CustomListAdaptor(Context context, ArrayList list) {

      this.context = context;
      userlist = list;
      }

      @Override
      public int getCount() {

      return userlist.size();
      }

      @Override
      public Object getItem(int position) {

      return userlist.get(position);
      }

      @Override
      public long getItemId(int position) {

      return position;
      }

      @Override
      public View getView(int position, View convertView, ViewGroup arg2)
      {
      UserList usetlists = userlist.get(position);



      LayoutInflater inflater = (LayoutInflater) context
      .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
      convertView = inflater.inflate(R.layout.userlistrow, null);

      TextView tvSlNo = (TextView) convertView.findViewById(R.id.tv_slno);
      tvSlNo.setText(usetlists.Getid());
      TextView tvName = (TextView) convertView.findViewById(R.id.tv_name);
      tvName.setText(usetlists.GetUsername());
      TextView tvPhone = (TextView) convertView.findViewById(R.id.tv_phone);
      tvPhone.setText(usetlists.GetPassword());
      TextView tvpassword = (TextView) convertView.findViewById(R.id.tv_password);
      tvpassword.setText(usetlists.getName());


      return convertView;
      }

      }

      Delete
    3. This also looks fine.give me ur email i will send you the full source code of my demo application

      Delete
    4. alexi1991@yahoo.com , thx for you're help and support

      Delete
    5. i have same problem, when i debug and run it in my android it suddenly stopped. there no error display in my android studio but i cant launch it in my phone. what error do you suggest?

      Delete
    6. The first item is not getting displayed in the listview....it is correctly displaying from the second item onwards

      Delete
  6. Thank you very much. Please send your code to email: tvanluu1990@gmail.com.

    ReplyDelete
  7. More and more tutorial. Thank you for all.

    ReplyDelete
  8. Thank you so much your tutorial very useful to me

    ReplyDelete
  9. Hi Arun,

    Thank you so much for this tutorial.. It more clear compared to the other tutorial I have tried.

    I am a beginner and just started to program android java. I know already how to receive an SMS and toast it.. I implemented it on another class. My problem now is where to actually write the function to add the SMS phone number and its message same as your tutorial above.. been trying to do it with your example but got a lot of errors

    ReplyDelete
  10. Great buddy !!! Works nice !!! Tks a lot bruh.

    ReplyDelete
  11. This comment has been removed by the author.

    ReplyDelete
  12. hei nice works i want your code plz send ur code to geomobapk@gmail.com

    ReplyDelete
  13. This comment has been removed by the author.

    ReplyDelete
  14. This comment has been removed by the author.

    ReplyDelete
  15. Can you send me project files please? erhan5229@gmail.com

    ReplyDelete
  16. Much good works, i want your code, please send your code to wisir59@gmail.com

    ReplyDelete
  17. can you send me source code please? mohamed.heikal99@yahoo.com

    ReplyDelete
  18. please send your code to hoanganhcxgl@gmail.com

    ReplyDelete
  19. Can you send me project files please? adhadimas91@gmail.com

    i try and error

    in this code
    ArrayList contactList = new ArrayList();
    contactList.clear();
    String query = "SELECT * FROM PHONE_CONTACTS ";
    Cursor c1 = sqlHandler.selectQuery(query);
    Object amp;
    if (c1 != (null c1.getCount() != 0)) {
    if (c1.moveToFirst()) {
    do {

    ReplyDelete
  20. This comment has been removed by the author.

    ReplyDelete
  21. Dear arun krishna
    Please send me the source code as i am having a problem in the MainActivity at the if statment. best regards.

    imagegrgr@yahoo.com

    ReplyDelete
  22. This is the Line error i have:
    if (c1 != null && c1.getCount() != 0) {

    the error under line under &&
    please look at it. regards.

    ReplyDelete
  23. now it is working i fix it, but when i press the button it only show the contacts below, not on the custom list activity how can i do that, becouse i want to show image too. please help me... and send the complate code project on my email imagegrgr@yahoo.com

    ReplyDelete
  24. hey can u send me zip file of this code

    ReplyDelete
  25. can you please mail me the zip file of phone contacts project?
    my email id is mpe797@gmail.com and how can i add more columns to your database? please reply soon...

    ReplyDelete
  26. This comment has been removed by the author.

    ReplyDelete
  27. hello..ur tuto r gr8..do u knw the codes for deleting data?thnks

    ReplyDelete
  28. Thaks for this tutorial ...plz can you send the full source code to my mail id : jalpa39@gmail.com

    ReplyDelete
  29. It was okay when I tried copy all codes and follow the tutorial.
    But stuck when I changed for my app. In a customAdapter I couldn't setText, there is a nullPointerException always comes. Any idea how to fix it?

    ReplyDelete
  30. Hello, first of all congrats for this tutorial. The only thing is that I'm new in Android Development and I'm having some troubles with my Adapter class. Could you please send your code for me to check it better? my email is rafaela.pira@gmail.com
    Thanks in advance;

    ReplyDelete
  31. Can you tell me how to display sqlite value to activity_main page..
    plz give code..

    ReplyDelete
  32. Thank you for your nice tutorial,
    may I ask you the source code of your demo, my email is: luxjim3763@gmail.com

    ReplyDelete
  33. i tried many time this code.inserted values in sqlitdatabase that values not display on listview my email id is:suajta.waghmare798@gmail.com

    ReplyDelete
  34. public class showList extends Activity{

    ListView lv;
    sql1 obj;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main2);
    lv=(ListView) findViewById(R.id.lv_custom_list);
    obj=new sql1(getApplicationContext(), sql1.DB_NAME, null, sql1.DB_VERSION);
    obj.getDetail();
    Intent in=getIntent();
    Toast.makeText(getApplicationContext(), "secondactivity", 5000).show();

    ArrayList contactList = new ArrayList();

    String query="select doctorname,doctoraddress,doctorno from Hospital";
    Cursor c1 = obj.selectQuery(query);

    if (c1 != null && c1.getCount() != 0) {
    if (c1.moveToFirst()) {
    do {
    hospital stu = new hospital();

    stu.setDoctorName(c1.getString(c1
    .getColumnIndex("doctorname")));
    stu.setDoctorAddress(c1.getString(c1
    .getColumnIndex("doctoraddress")));

    stu.setDoctorNo(c1.getString(c1
    .getColumnIndex("doctorno")));


    } while (c1.moveToNext());
    }
    }
    c1.close();

    ContactListAdapter1 contactListAdapter = new ContactListAdapter1(
    showList.this, contactList);
    lv.setAdapter(contactListAdapter);

    }

    }











    class ContactListAdapter1 extends BaseAdapter{


    Context context;

    ArrayList contactList;



    public ContactListAdapter1(Context context, ArrayList list) {

    this.context = context;
    contactList = list;
    }




    public int getCount() {

    return contactList.size();
    }

    public Object getItem(int position) {

    return contactList.get(position);
    }

    public long getItemId(int position) {

    return position;
    }

    public View getView(int position, View convertView, ViewGroup arg2) {
    hospital stu = contactList.get(position);

    if (convertView == null) {
    LayoutInflater inflater = (LayoutInflater) context
    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    convertView = inflater.inflate(R.layout.contact_list_row, null);

    }



    TextView tvSlNo = (TextView) convertView.findViewById(R.id.tv_slno);
    tvSlNo.setText(stu.getDoctorName());
    TextView tvName = (TextView) convertView.findViewById(R.id.tv_name);
    tvName.setText(stu.getDoctorAddress());
    TextView tvPhone = (TextView) convertView.findViewById(R.id.tv_phone);
    tvPhone.setText(stu.getDoctorNo());


    return convertView;
    }


    }

    ReplyDelete
  35. get values from sqlitedatabase this values display on listview

    ReplyDelete
  36. This comment has been removed by the author.

    ReplyDelete
  37. Can you send me your source code, please? :)

    ReplyDelete
  38. Can you send me your source code, please? :) lpaskvan@gmail.com

    ReplyDelete
  39. Please send me the source code, if possible.
    minadakis.manolis@gmail.com

    ReplyDelete
  40. excellent tutorial, thank you was a great help!

    ReplyDelete
  41. Excellent tutorial...how to delete a single from database and listview based on listview position click..

    ReplyDelete
  42. Instead of inserting data into the database ....do you know how to list data from a prepopulated database into a list view ?

    ReplyDelete
  43. Excellent tutorial, thank you.

    I am receiving an error from the following line:

    if (c1 != null && c1.getCount() != 0) {

    The error reads:

    Multiple markers at this line
    - amp cannot be resolved to a
    variable
    - Syntax error on token ";", .
    expected
    - amp cannot be resolved
    - Syntax error on token ";", delete
    this token

    Here's the class, which is exactly as you have it:

    package com.arun.democustomadapter;

    import java.util.ArrayList;

    import android.app.Activity;
    import android.database.Cursor;
    import android.os.Bundle;
    import android.view.Menu;
    import android.view.View;
    import android.view.View.OnClickListener;
    import android.widget.Button;
    import android.widget.EditText;
    import android.widget.ListView;

    public class MainActivity extends Activity {

    SqlHandler sqlHandler;
    ListView lvCustomList;
    EditText etName, etPhone;
    Button btnsubmit;

    @Override
    public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    lvCustomList = (ListView) findViewById(R.id.lv_custom_list);
    etName = (EditText) findViewById(R.id.et_name);
    etPhone = (EditText) findViewById(R.id.et_phone);
    btnsubmit = (Button) findViewById(R.id.btn_submit);
    sqlHandler = new SqlHandler(this);
    showList();
    btnsubmit.setOnClickListener(new OnClickListener() {

    @Override
    public void onClick(View v) {

    String name = etName.getText().toString();
    String phoneNo = etPhone.getText().toString();

    String query = "INSERT INTO PHONE_CONTACTS(name,phone) values ('"
    + name + "','" + phoneNo + "')";
    sqlHandler.executeQuery(query);
    showList();
    etName.setText("");
    etPhone.setText("");

    }
    });

    }

    private void showList() {

    ArrayList contactList = new ArrayList();
    contactList.clear();
    String query = "SELECT * FROM PHONE_CONTACTS ";
    Cursor c1 = sqlHandler.selectQuery(query);
    if (c1 != null && c1.getCount() != 0) {
    if (c1.moveToFirst()) {
    do {
    ContactListItems contactListItems = new ContactListItems();

    contactListItems.setSlno(c1.getString(c1
    .getColumnIndex("slno")));
    contactListItems.setName(c1.getString(c1
    .getColumnIndex("name")));
    contactListItems.setPhone(c1.getString(c1
    .getColumnIndex("phone")));
    contactList.add(contactListItems);

    } while (c1.moveToNext());
    }
    }
    c1.close();

    ContactListAdapter contactListAdapter = new ContactListAdapter(
    MainActivity.this, contactList);
    lvCustomList.setAdapter(contactListAdapter);

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
    }
    }

    Thank you again!

    ReplyDelete
    Replies
    1. I figured it out. They were ampersands.

      Delete
  44. hello helper...
    i can use sd card to stor my data long time??? and aftar i will re install my app i can backup my al data plz send me code...

    ReplyDelete
  45. how add checkbox in listview give me source code plz??

    ReplyDelete
  46. private void showList() {

    ArrayList contactList = new ArrayList();
    contactList.clear();
    String query = "SELECT * FROM PHONE_CONTACTS";

    Cursor c1 = sqlHandler.selectQuery(query);
    if (c1 != null) {
    if (c1.moveToFirst()) {
    do {
    ContactListItems contactListItems = new ContactListItems();

    contactListItems.setSlno(c1.getString(c1
    .getColumnIndex("slno")));
    contactListItems.setName(c1.getString(c1
    .getColumnIndex("name")));
    contactListItems.setAge(c1.getString(c1
    .getColumnIndex("age")));
    contactListItems.setPhone(c1.getString(c1
    .getColumnIndex("phone")));

    contactList.add(contactListItems);

    } while (c1.moveToNext());
    }
    }
    c1.close();

    ContactListAdapter contactListAdapter = new ContactListAdapter(
    MainActivity.this, contactList);
    lvCustomList.setAdapter(contactListAdapter);

    }
    Here i strucked how to add more values in contact list item

    ReplyDelete
  47. hi please find the error this is my custom adapter class

    public class ContactListAdapter extends BaseAdapter {

    TextView sno,name,age,phone,caps,tcps,mbf,maf,abf,aaf,ebf,eaf,nbf,naf;
    Context context;

    ArrayList contactList;

    public ContactListAdapter(Context context, ArrayList list) {

    this.context = context;
    contactList = list;
    }

    @Override
    public int getCount() {

    return contactList.size();
    }

    @Override
    public Object getItem(int position) {

    return contactList.get(position);
    }

    @Override
    public long getItemId(int position) {

    return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup viewGroup) {
    ContactListItems contactListItems = contactList.get(position);

    if (convertView == null) {
    LayoutInflater inflater = (LayoutInflater) context
    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    convertView = inflater.inflate(R.layout.list_land, null);

    }
    sno=(TextView)convertView.findViewById(R.id.lblsno);
    sno.setText(contactListItems.getSlno());
    name=(TextView)convertView.findViewById(R.id.lblname);
    name.setText(contactListItems.getSlno());
    age=(TextView)convertView.findViewById(R.id.lblage);
    age.setText(contactListItems.getSlno());
    phone=(TextView)convertView.findViewById(R.id.lblmobile);
    phone.setText(contactListItems.getSlno());

    /*TextView tvSlNo = (TextView) convertView.findViewById(R.id.lblsno);
    tvSlNo.setText(contactListItems.getSlno());
    TextView tvName = (TextView) convertView.findViewById(R.id.lblname);
    tvName.setText(contactListItems.getName());
    TextView tvAge = (TextView) convertView.findViewById(R.id.lblage);
    tvAge.setText(contactListItems.getAge());
    TextView tvPhone = (TextView) convertView.findViewById(R.id.lblmobile);
    tvPhone.setText(contactListItems.getPhone());*/


    return convertView;
    }

    }

    ReplyDelete
  48. sir I am unable to create database and insert data in table by using your code given above so plz sir do somthing i am using android studio

    ReplyDelete
  49. how to edit listview item ?? Plz rply asap

    ReplyDelete
  50. This tutorial helped me a lot. It explain me the details of sqlite and listview both. Just instead of using raw query I implemented my own method since I read somewhere that it is not a good practise to use raw queries.
    Thank you very much.

    ReplyDelete
  51. hi I am Tarun sharma.I also have a query that is i am able to insert data but i want to show inserted data into a list which is in anothe class.How can i do this.
    please send me source code on tarun_9689@yahoo.com

    ReplyDelete
  52. Thanks a lot. You example worked well for my new app.

    ReplyDelete
  53. Thanks a lot. You example worked well for my new app.

    ReplyDelete
  54. Hey Arun, thanks a lot for this tutorial! It's really helpful.
    I have a doubt, if you could help me with that I would be really grateful.

    I have three columns in my listview. I can access any value in any column. I want to change value of the selected item in sql database. But I am not sure how to retrieve the rowID for that item. I suppose I need rowID which is primary key in my database in UPDATE query.

    ReplyDelete
  55. create a Application to list your favorite book writers name and when select one author their book should be list i another activity and when select one book the details of book should be displayed on the third activity? any one can please its an urgent work please help

    ReplyDelete
  56. hi in the above code, how do i insert data based on user registration?
    suppose if i login with another account, i should be able to insert new data and clear others.

    ReplyDelete
  57. Can i export these sqlite data details into mail or excel

    ReplyDelete
  58. Nice blog..! I really loved reading through this article. Thanks for sharing.You done a great job. Interesting.

    ReplyDelete

Post a Comment

Popular posts

Controlling Back button Behavior in Fragment-- kotlin

when user navigates in an application android maintains back stack of destinations . This allows android to go back to previous destination when user clicks back button . some  times we  need to implement our own back button behavior  for best user experience . For example  if we are in a timer based quiz  application . when the user clicks on the back button if we go back to the previous destination without stopping  the counter , it will crash  the application . So first we need to know whether the  user  pressed the back button accidentally or not by  using a dialogue box . If the user want to go back to previous destination  we need to stop the counter and  then go back to the previous destination. We can control the back button hahavior byusing OnBackPressedDispatcher  . This controls how back button events are dispatched to one or more onBackPressedCallback objects . callbacks are added using addCallback methods. e...

Android Card View And RecyclerView Example

CardView Cardview lets you show information inside cards that have consistent look across the platform . CardView is introduced with material design through support v7 library. CardView extends frame layout and It can have shadows and round corners.     Cards can be used as independent views that serves as an entry point to more detailed information. CardView can also  be used with RecyclerView to display cards as list. In this example we are using Cardview with Recyclerview to show data as list of cards. Our Demo application contains vertical list of cards . Each card contain Movie name, movie poster and director name. screenshot of demo app 1. CardView and RecyclerView are supportV7 library widget . so we need to add dependency for both in app level build.gradle file . which is in the app folder compile 'com.android.support:cardview-v7:26.+' compile 'com.android.support:recyclerview-v7:26.+' build.gradle file is apply plugin: 'com.android.applicat...

Keytool is not recognized as internal or extenal command / Adding PATH in system variable

If you are running a keytool command  keytool -list -v -keystore C:\Users\arun\.android\debug.keystore -alias androiddebugkey -storepass android    and getting an error   'keytool' is not recognized as an internal or external command  If you are using any other commad like java,javac , etc.. and getting an error " is not recognized as an internal or external command"  you can also use this same steps  you are getting this error because keytool.exe , executable file which exists in the bin directory of your JDK  is not added to Path in your Environmental variables. To resolve this issue 1 .first we need to find the bin Directory of our jdk    Usually this will be in  C:\Program Files\Java\jre1.8.0_221\bin (jre1.8.0_221 - change this to your latest version , ). you can see keytool.exe file in the bin directory . (If you installed jdk in a different directory Find your Jdk installation folder and  use that path....