Assinging the values of cursor to object

假装没事ソ 提交于 2019-12-13 05:07:58

问题


I'm working on showing list of contacts with checkbox. I tried implementing my own cursor adapter and it is checkable. But once I check that value I want the contacts to be stored in ContactPerson object. But when I tried it is showing null pointer exception(That's why I commented out that code). My CursorAdapter code goes like this.

ContactListAcitivity.java

import android.app.Activity;
import android.content.Context;
import android.database.Cursor;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.support.v4.widget.CursorAdapter;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.ListView;
import android.widget.TextView;


public class ContactListActivity extends Activity  {

    ListView list;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_contact_list);
        list = (ListView) findViewById(R.id.ListView2);
        Cursor cur= getContentResolver().query(ContactsContract.Contacts.CONTENT_URI, null,null,null,null);

        startManagingCursor(cur);

        String[] result=new String[cur.getCount()];

        for (boolean hasData = cur.moveToFirst(); hasData; hasData = cur.moveToNext())
        {
            ContactPerson contact = new ContactPerson(cur.getString(cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME)), String.valueOf(cur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)));
        }
        stopManagingCursor(cur);
        list.setAdapter(new contactAdapter(getApplicationContext(), cur));

    }

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

    private class ViewHolder{
        TextView ContactName;
        CheckBox contactCheck;
    }

    class contactAdapter extends CursorAdapter{

        private Cursor cursor;
        private Context ccontext;
        private LayoutInflater inflater;

        public contactAdapter(Context context, Cursor c) {
            super(context, c);
            // TODO Auto-generated constructor stub
            cursor = c;
            ccontext = context;
            inflater = LayoutInflater.from(context);
            inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        }

        @Override
        public void bindView(View view, Context arg1, Cursor arg2) {
            // TODO Auto-generated method stub

            ViewHolder holder = (ViewHolder) view.getTag();
            if (holder == null) {
                holder = new ViewHolder();
                holder.ContactName = (TextView) view.findViewById(R.id.contact_name);
                holder.contactCheck = (CheckBox) view.findViewById(R.id.contact_check);
                view.setTag(holder);
                holder.contactCheck.setOnClickListener(new View.OnClickListener() {

                    @Override
                    public void onClick(View v) {
                        // TODO Auto-generated method stub
                        CheckBox cb = (CheckBox) v;
                        cb.setSelected(true);
//                      ContactPerson contact = (ContactPerson) cb.getTag(); this is the place where it is showing null pointer exception
//                      Log.i("clicked users", contact.getName());
//                      contact.setSelected(true);
                    }
                }); 
            }else{
                holder = (ViewHolder) view.getTag();
            }
//          ContactPerson contacts = contactList.get(position);
            holder.ContactName.setText(cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME)));
//          holder.contactCheck.setChecked(contacts.isSelected());
//          holder.contactCheck.setTag(contacts);
//          holder.ContactName.setText(contacts.getName());
        }

        @Override
        public View newView(Context arg0, Cursor arg1, ViewGroup arg2) {
            // TODO Auto-generated method stub
            return inflater.inflate(R.layout.checkbox_item, arg2, false);
        }

    }

}

activity_contact_list.xml

<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:background="#000000">

    <ListView 
    android:id="@+id/ListView2"
    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=".GroupContactsActivity"
    android:layout_alignParentTop="true"
     />

    <Button
        android:id="@+id/selected_done_1"
        android:layout_width="160dp"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
        android:textColor="#FFFFFF"
        android:text="Done" />

</RelativeLayout>

checkbox_item.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    android:padding="6dip" 
    android:background="#000000">

    <TextView 
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/contact_name"
        android:layout_alignParentLeft="true"
        android:text="textview"
        android:textSize="15sp"
        android:textColor="#FFFFFF" 
        android:gravity="center_horizontal"/>
    <CheckBox 
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:focusable="false"
        android:focusableInTouchMode="false"
        android:layout_alignParentRight="true"
        android:layout_weight="1"
        android:id="@+id/contact_check"/>
</RelativeLayout>

Can anyone please suggest me how to use that Contact person class in this adapter.

public class ContactPerson {

    String name= null, number = null;
    boolean Selected = false;


    public ContactPerson(String PersonName, String PhoneNumber){
        this.name = PersonName;
        this.number= PhoneNumber;
    }

    public String getName(){
        return name;
    }

    public boolean isSelected(){
        return Selected;
    }

    public void setSelected(boolean selected){
        this.Selected = selected;
    }

    public String getPhoneNumber(){
        return number;
    }
}

回答1:


Check this code. It worked for me. Best of luck.

import java.util.ArrayList;
import java.util.Set;
import java.util.TreeSet;

import android.app.Activity;
import android.content.Context;
import android.database.Cursor;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.support.v4.widget.CursorAdapter;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;


public class ContactListActivity extends Activity  {

    ListView list;
    ArrayList<ContactPerson> selectedList;
    Set<String> phoneID= new TreeSet<String>();;
    Button doneButton;
    CheckBox cb;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_contact_list);

        selectedList = new ArrayList<ContactPerson>();
        list = (ListView) findViewById(R.id.ListView2);
        doneButton = (Button) findViewById(R.id.selected_done_1);

        Cursor cur= getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,null,null,null);
        list.setAdapter(new contactAdapter(getApplicationContext(), cur));
        doneButton.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                for (String ids : phoneID) {
                    Log.d("PhoneIds", ids);

                    Cursor cursorPhoneNumber = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
                            new String[]{ContactsContract.CommonDataKinds.Phone.NUMBER},

                            ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ? AND " +
                                    ContactsContract.CommonDataKinds.Phone.TYPE + " = " +
                                    ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE,

                            new String[]{ids},
                            null);
                    Log.d("Number cursor", String.valueOf(cursorPhoneNumber.getCount()));
                    if (cursorPhoneNumber.moveToFirst()) {
//                      phoneNumber = cursorPhoneNumber.getString(cursorPhoneNumber.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
                       Log.d("Phone number", cursorPhoneNumber.getString(cursorPhoneNumber.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)));
                    }

                    cursorPhoneNumber.close();

                    Cursor cursorName = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
                            new String[]{ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME_PRIMARY},

                            ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ? AND " +
                                    ContactsContract.CommonDataKinds.Phone.TYPE + " = " +
                                    ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE,

                            new String[]{ids},
                            null);
                    Log.d("Name cursor", String.valueOf(cursorName.getCount()));
                    if (cursorName.moveToFirst()) {
                       Log.d("Phone number", cursorName.getString(cursorName.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME_PRIMARY)));
//                     Name = cursorName.getString(cursorName.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME_PRIMARY));
                    }

                    cursorName.close();
//                  selectedList.add(new ContactPerson(Name,phoneNumber));
                }
            }
        });
    }

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

    private class ViewHolder{
        TextView ContactName;
        CheckBox contactCheck;
    }

    class contactAdapter extends CursorAdapter{

        String Name, phoneNumber;
        private Cursor cursor;
        private Context ccontext;
        private LayoutInflater inflater;

        public contactAdapter(Context context, Cursor c) {
            super(context, c);
            // TODO Auto-generated constructor stub
            cursor = c;
            ccontext = context;
            inflater = LayoutInflater.from(context);
            inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        }

        @Override
        public void bindView(View view, Context arg1, Cursor arg2) {
            // TODO Auto-generated method stub

            ViewHolder holder = (ViewHolder) view.getTag();
            if (holder == null) {
                holder = new ViewHolder();
                holder.ContactName = (TextView) view.findViewById(R.id.contact_name);
                holder.contactCheck = (CheckBox) view.findViewById(R.id.contact_check);
                view.setTag(holder);
                holder.contactCheck.setOnClickListener(new View.OnClickListener() {

                    @Override
                    public void onClick(View v) {
                        // TODO Auto-generated method stub
                        cb = (CheckBox) v;
                        cb.setChecked(cb.isChecked());
//                      ContactPerson selected = (ContactPerson)cb.getTag();
                        Log.d("selcted", cb.getTag().toString());
                        if(cb.isChecked()){

                            phoneID.add(cb.getTag().toString());


                        }
                    }

                }); 
            }else{
                holder = (ViewHolder) view.getTag();
            }

            holder.ContactName.setText(cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME)));
            holder.contactCheck.setTag(cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.CONTACT_ID)));
            holder.contactCheck.setChecked(false);

        }

        @Override
        public View newView(Context arg0, Cursor arg1, ViewGroup arg2) {
            // TODO Auto-generated method stub
            return inflater.inflate(R.layout.checkbox_item, arg2, false);
        }

        @Override
        public View getView(int arg0, View arg1, ViewGroup arg2) {
            // TODO Auto-generated method stub
//          Log.d("don't know", cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)));
            return super.getView(arg0, arg1, arg2);
        }

    }

}



回答2:


Here i changed little bit code of your adapter and activity. just look at it:

public class MainActivity extends Activity  {

      private ArrayList<ContactPerson> arr;
        private Context context;
        private ListView list;
        private ContactArrayAdapter adapter;
        private String strName,strNumber;
        private View view;  
        public static boolean[] arrBoolean = null;

        @Override
        public void onCreate(Bundle savedInstance) {
            super.onCreate(savedInstance);
            setContentView(R.layout.activity_main);
            ProgressDialog pd  = new ProgressDialog(this);
            list = (ListView)findViewById(R.id.ListView2);
            arr = new ArrayList<ContactPerson>();
            context = MainActivity.this;
            arr =  displayContacts();

            adapter = new ContactArrayAdapter(this, R.layout.checkbox_item, arr);
            list.setAdapter(adapter);
        }

        public ArrayList<ContactPerson> displayContacts() {

            ContentResolver cr = getContentResolver();
            Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI,null, null, null, null);
            ContactPerson contact;
            if (cur.getCount() > 0) {
                while (cur.moveToNext()) {
                    contact = new ContactPerson();

                    String id = cur.getString(cur.getColumnIndex(People._ID));
                    String name = cur.getString(cur.getColumnIndex(People.DISPLAY_NAME));
                    ContactPerson cp = new ContactPerson();
                    cp.setName(name);
                    cp.setNumber(id);
                    cp.setSelected(false);
                    arr.add(cp);
                }
            }
            return arr;
        }

    //********* Adapter *****

    public class ContactArrayAdapter extends ArrayAdapter<ContactPerson> {

    //  private final List<Contact> list;
        private Context context;    

        private LayoutInflater mInflater;
        private List<ContactPerson> list; 


         public ContactArrayAdapter(Context context, int textViewResourceId,

                 ArrayList<ContactPerson> stateList) {
                 super(context, textViewResourceId, stateList);
                 this.list = new ArrayList<ContactPerson>();
                 this.list.addAll(stateList);
                 }


        class ViewHolder {
             TextView text;
             CheckBox checkbox;
        }

        public View getView(int position, View convertView, ViewGroup parent) {
            View view = convertView;
            ViewHolder viewHolder = null;
            if (view == null) {      
                LayoutInflater vi = (LayoutInflater)getSystemService(
                         Context.LAYOUT_INFLATER_SERVICE);
                view = vi.inflate(R.layout.checkbox_item, null);

                viewHolder = new ViewHolder();
                viewHolder.text = (TextView) view.findViewById(R.id.contact_name);
                viewHolder.checkbox = (CheckBox) view.findViewById(R.id.contact_check);
                view.setTag(viewHolder);


            } else {
                viewHolder = (ViewHolder) view.getTag();
            }

            final int pos = position;

            ContactPerson cp = list.get(position);
            viewHolder.text.setText(cp.getName());
            viewHolder.checkbox.setChecked(cp.isSelected());    


            viewHolder.checkbox.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View arg0) {
                    // TODO Auto-generated method stub
                    CheckBox cb = (CheckBox) arg0 ;
                    list.get(pos).setSelected(cb.isChecked());
                    System.out.println(cb.isChecked());
                    System.out.println(list.get(pos).getName());
                }
            });

            //viewHolder.text.setTag(cp);
            return view;
        }



    }

}


来源:https://stackoverflow.com/questions/20699062/assinging-the-values-of-cursor-to-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!