0

Hae stackoverflow gurus,

I'm looking for an assistance. i have researched all over the internet but in vain. I would like to add all values fetched to listview. I have managed to insert values to the database and managed to fetch all of them however, i'm unable to add them to listview. The function below works perfect and returns the data as list.

 public List<Contact> getAllContacts() {
        List<Contact> contactList = new ArrayList<Contact>();
        // Select All Query
        String selectQuery = "SELECT  * FROM " + TABLE_CONTACTS;

        SQLiteDatabase db = this.getWritableDatabase();
        Cursor cursor = db.rawQuery(selectQuery, null);

        // looping through all rows and adding to list
        if (cursor.moveToFirst()) {
            do {
                Contact contact = new Contact();
                contact.setID(Integer.parseInt(cursor.getString(0)));
                contact.setName(cursor.getString(1));
                contact.setPhoneNumber(cursor.getString(2));
                // Adding contact to list
                contactList.add(contact);
            } while (cursor.moveToNext());
        }

        // return contact list
        return contactList;
    }

Also, the function below works perfect and prints out all the retrieved values using log

}


 private void showRecords() {

        List<Contact> contacts = db.getAllContacts();

        for (Contact cn : contacts) {

            //lv.setAdapter(new dataAdapter(this, cn.getID(), cn.getName(), cn.getPhoneNumber()));
            String log = "Id: " + cn.getID() + " ,Name: " + cn.getName() + " ,Phone: " + cn.getPhoneNumber();
            // Writing Contacts to log
            //Log.d("Name: ", log);
            Toast.makeText(getApplicationContext(),log, Toast.LENGTH_SHORT).show();
        }
    }

Now, i have created a listview for which is working however, i'm unable to add data to the listview as shown.

 private void showRecords() {

            List<Contact> contacts = db.getAllContacts();

           for(int i=0; i < contacts.size();i++){
                lv.setAdapter(new dataAdapter(this, cn.getID(),cn.getName(), cn.getPhoneNumber()));
          }         
    }

My question is, how can i populate List<Contact> contacts = db.getAllContacts(); to the listview lv?

This is the entire dataAdapter class

public class dataAdapter extends BaseAdapter {

    Context context;
    String [] name;
    String [] phone;
    int [] dataId;
    private static LayoutInflater inflater=null;
    public dataAdapter(Context context, int[] dataId, String[] name, String[] phone){

        this.context=context;
        this.dataId=dataId;
        this.name=name;
        this.phone=phone;

        inflater =(LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

    }

    public int getCount() {
        return dataId.length;
    }

    public Object getItem(int position) {
        return position;
    }

    public long getItemId(int position) {
        return position;
    }

    public  class  Holder{
        TextView nameV;
        TextView phoneV;
    }

    public  View getView(final  int position, View convertView, ViewGroup parent){
        Holder holder=new Holder();
        View rowView;
        rowView=inflater.inflate(R.layout.thelist, null);

        holder.nameV=(TextView) rowView.findViewById(R.id.txt1);
        holder.phoneV=(TextView) rowView.findViewById(R.id.txt2);


        holder.nameV.setText(name[position]);
        holder.phoneV.setText(phone[position]);

        rowView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                Toast.makeText(context,name[position],Toast.LENGTH_SHORT).show();

            }
        });
        return  rowView;
    }
}
4
  • journaldev.com/10416/… follow this tutorial for custom adapter Commented Jan 21, 2017 at 9:52
  • Your showRecords method is wrong. You don't loop through the records and set the adapter for each one. You should create a single instance of an Adapter backed by your List<Contact> and then set it once Commented Jan 21, 2017 at 10:02
  • Please David, can you do it for me because i'm totally confused Commented Jan 21, 2017 at 10:15
  • jhamas, thanks for the link however i want to populate the data in list to the listview. The listview works perfect, big problem is how to add the data to the listview Commented Jan 21, 2017 at 10:16

1 Answer 1

1

Do not set the adapter for every new item, instead pass the list of contacts to list view adapter only once. And if you want to add new item add the add to existing adapter.

You can do like this

private void showRecords() {
   List<Contact> contacts = db.getAllContacts();
   lv.setAdapter(new dataAdapter(this, contacts));       
}

Or you follow the tutorial provided in comment above for better understanding.

Edit 1 Instead of taking array of every field of your contact class, take a list of contact, which you have from List<Contact> contacts = db.getAllContacts()

.....
.....
List<Contact> mContacts;

DataAdapter(Context context,List<Contact> contact) {
    this.context=context;
    this.mContacts=contacts;  
    .....
    .....  
}

Your getCount method should be

public int getCount() {
    return mContact.size();
}

And your getView() method should be

public  View getView(final  int position, View convertView, ViewGroup parent) {
    Contact contact = mContact.get(position);
    ....
    ....
    holder.nameV.setText(contact.getName());
    holder.phoneV.setText(contact.getPhone());
    ....
    ....
    return view;
}

And if you add to this existing adapter, add a custom method like this

public void add(Contact contact) {
    if(mContact != null) {
        mContact.add(contact);
        // This will refresh the list.
        notifyDataSetChanged();
    }
}

I would still suggest you to go through the tutorial mention in the link above, your adapter class needs lot of changes for better implmentation.

Sign up to request clarification or add additional context in comments.

7 Comments

Still not working, the setAdapter() class has four params
three of the four param makes Contact object, so you can modify the adapter to take a list of contact instead. Like DataAdapter(Context context, List<Contact> contacts)
I see you have a clue, can i post the entire listAdapter ?
I have posted the entire dataAdapter class. See the edits
it has worked however, it is returning a list with data info.example.androidsqlitedb.Contacts@32c445a7
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.