ListFragment没有填充

时间:2014-05-21 01:10:53

标签: android android-arrayadapter android-listfragment

我仍然在处理将联系人加载到listfragment中的学习活动。整个应用程序构建,我没有强制关闭,但我的列表片段不显示联系人列表。我正在使用网络上的示例,所以我确信某处存在一些不兼容性。任何帮助都会受到赞赏,因为我正在学习并试图在旅途中解决问题。

以下是我的ContactListFragment,其中<​​em>应该显示联系人列表:

public class ContactListFragment extends ListFragment {
    private ContactAdapter mAdapter;
    private List<ContactItem> contactItemList = new LinkedList<ContactItem>();

    private LayoutInflater mInflater;
    public boolean taskRun = false;
    long currentID = 0;
    long currentContactID = 0;
    public ContactListFragment() {}
    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        mInflater = (LayoutInflater) getActivity().getSystemService(Activity.LAYOUT_INFLATER_SERVICE);  
        if(!taskRun){
            FragmentTransaction ft = getFragmentManager().beginTransaction();
            ListContactTask task= new ListContactTask(getActivity(),ft);
            task.execute(); 

        }
        taskRun = true;
        mAdapter = new ContactAdapter(getActivity(), R.layout.lvmain,R.id.key, contactItemList);
        mAdapter .setInflater(mInflater);
        mAdapter.setLayout(R.layout.contact_card);
        setListAdapter(mAdapter);
        ListView listView = getListView();
        getListView().invalidate();

    }

    public void setDataList( List<ContactItem> list) {  
        Activity act = getActivity();
        this.contactItemList = list;
        if(act != null) {
            mAdapter = new ContactAdapter(act, R.layout.lvmain,R.id.key, list);
            mAdapter .setInflater(mInflater);
            mAdapter.setLayout(R.layout.contact_card);
            setListAdapter(mAdapter );
            getListView().invalidate();

        }
    }
}
class ContactAdapter extends ArrayAdapter<ContactItem> {

       private static String TAG = ContactAdapter.class.getName();
       private LayoutInflater inflator = null;
       List<ContactItem> pairList = null;
       private int layout;
       public ContactAdapter(Context context, int resource,
                int textViewResourceId, List<ContactItem> objects) {
            super(context, resource, textViewResourceId, objects);
            this.pairList = objects;
        }

        public void setInflater(LayoutInflater mInflater) {
            this.inflator = mInflater;
        }
        public void setLayout(int layout){
            this.layout = layout;

        }

        /**
         * Make a view to hold each row.
         * 
         * @see android.widget.ListAdapter#getView(int, android.view.View,
         *      android.view.ViewGroup)
         */
        public View getView(final int position, View convertView,
                ViewGroup parent) {
            ViewHolder holder;
            try {
                if (convertView == null) {
                    convertView = this.inflator.inflate(
                            layout, null);
                    holder = new ViewHolder();
                    holder.key = (TextView) convertView
                            .findViewById(R.id.key);
                    holder.value = (TextView) convertView.findViewById(R.id.value);
                    convertView.setTag(holder);
                }else {
                     holder = (ViewHolder) convertView.getTag();
                }
                ContactItem pair = (ContactItem) getItem(position);
                String key = pair.mDisplayName;
                String value = pair.mPhone;

                holder.key.setText(key);
                holder.value.setText(value);
                Log.i("pairing", "happened");
            } catch (Exception e) {
                Log.e(TAG, e.toString(), e);
            }
            return convertView;
        }

        static class ViewHolder {
            TextView key;
            TextView value;
        }

        public Filter getFilter() {
            return null;
        }

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

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

        public ContactItem getItem(int position) {
            return (ContactItem) super.getItem(position);
        }

        @Override
        public int getItemViewType(int position) {
            return super.getItemViewType(position);
        }

        @Override
        public int getViewTypeCount() {
            return super.getViewTypeCount();
        }

        @Override
        public boolean isEmpty() {
            return super.isEmpty();
        }
    }

这是列表联系人任务(来自我正在使用的示例)。我注释掉了onPostExecute,因为它导致了我的错误,所以我猜这是我的问题。问题是我不知道如何在我的ContactListFragment中加入onPostExecute的接收器。

import android.app.Activity;
import android.support.v4.app.FragmentTransaction;
import android.database.Cursor;
import android.os.AsyncTask;
import android.provider.ContactsContract.Data;
import android.provider.ContactsContract.CommonDataKinds.Phone;
import android.util.Log;

public class ListContactTask extends AsyncTask<Void, Void, List<ContactItem>> {
    private FragmentTransaction ft;
    private Activity activity;
    public ListContactTask(Activity activity, FragmentTransaction ft) {
        this.activity = activity;
        this.ft = ft;
    }

    public ListContactTask() {
    }

    @SuppressWarnings("unused")
    protected List<ContactItem> doInBackground(Void... params) {
         Cursor c = activity.getContentResolver().query(Data.CONTENT_URI,
                  new String[] {Data._ID, Data.DISPLAY_NAME,Phone.NUMBER, Data.CONTACT_ID,Phone.TYPE, Phone.LABEL},
                  Data.MIMETYPE + "='" + Phone.CONTENT_ITEM_TYPE + "'",
                  null, 
                  Data.DISPLAY_NAME);

        int count = c.getCount();
        boolean b = c.moveToFirst();
        String[] columnNames = c.getColumnNames();
        int displayNameColIndex = c.getColumnIndex("display_name");
        int idColIndex = c.getColumnIndex("_id");
        //int contactIdColIndex = c.getColumnIndex("contact_id");
        int col2Index = c.getColumnIndex(columnNames[2]);
        int col3Index = c.getColumnIndex(columnNames[3]);
        int col4Index = c.getColumnIndex(columnNames[4]);

        List<ContactItem> contactItemList = new LinkedList<ContactItem>();
        for(int i = 0; i < count ; i ++) {
            String displayName = c.getString(displayNameColIndex);
            String phoneNumber = c.getString(col2Index);
            int contactId = c.getInt(col3Index);
            String phoneType = c.getString(col4Index);

            long _id = c.getLong(idColIndex);
            ContactItem contactItem = new ContactItem();
            contactItem.mId= _id;
            contactItem.mContactId = contactId;
            contactItem.mDisplayName = displayName;
            contactItem.mPhone = phoneNumber;
            contactItemList.add(contactItem);
            boolean b2 = c.moveToNext();
        }
        c.close();
        return contactItemList;
    }
/*
    protected void onPostExecute(List<ContactItem> result) {  
        ((MainActivity)activity).addContactListFragment(ft, result);

    } 
*/
}

这也是我的布局文件:

Contact_card.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:background="#ffe6e6e6" >

    <RelativeLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginBottom="4dp"
        android:layout_marginLeft="10dp"
        android:layout_marginRight="10dp"
        android:layout_marginTop="2dp"
        android:background="@drawable/card_background"
        android:orientation="horizontal" >

        <LinearLayout
            android:id="@+id/contactImage"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentLeft="true"
            android:layout_marginRight="5dip"
            android:background="@drawable/ic_contact"
            android:orientation="horizontal"
            android:padding="3dip" >
        </LinearLayout>

        <TextView
            android:id="@+id/key"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignTop="@+id/contactImage"
            android:layout_toRightOf="@+id/contactImage"
            android:text="TestNameHere"
            android:textColor="@color/card_text"
            android:textSize="@dimen/contact_name"
            android:textStyle="bold"
            android:typeface="sans"
            tools:ignore="HardcodedText" />

        <TextView
            android:id="@+id/value"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_below="@id/key"
            android:layout_marginTop="3dip"
            android:layout_toRightOf="@+id/contactImage"
            android:text="800-867-5309"
            android:textColor="@color/card_text"
            android:textSize="@dimen/contact_phone"
            tools:ignore="HardcodedText" />
    </RelativeLayout>

</LinearLayout>

lvmain.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="fill_parent"
    android:orientation="vertical" >

    <ListView
        android:id="@+id/list"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:cacheColorHint="#00000000"
        android:divider="#00000000" />

</RelativeLayout>

我希望这一切都有道理,而且我不只是漫无边际地走错路。

编辑:

也有助于包含我的MainActivity:

public class MainActivity extends FragmentActivity implements
        ActionBar.TabListener {

    private ViewPager viewPager;
    private TabsPagerAdapter mAdapter;
    private ActionBar actionBar;
    // Tab titles
    private String[] tabs = { "Quick Actions", "Contacts", "Apps" };


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu items for use in the action bar
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.main, menu);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.action_search) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // Initilization
        viewPager = (ViewPager) findViewById(R.id.pager);
        actionBar = getActionBar();
        mAdapter = new TabsPagerAdapter(getSupportFragmentManager());

        viewPager.setAdapter(mAdapter);
        actionBar.setHomeButtonEnabled(false);
        actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);        

        // Adding Tabs
        for (String tab_name : tabs) {
            actionBar.addTab(actionBar.newTab().setText(tab_name)
                    .setTabListener(this));
        }

        /**
         * on swiping the viewpager make respective tab selected
         * */
        viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {

            @Override
            public void onPageSelected(int position) {
                // on changing the page
                // make respected tab selected
                actionBar.setSelectedNavigationItem(position);
            }

            @Override
            public void onPageScrolled(int arg0, float arg1, int arg2) {
            }

            @Override
            public void onPageScrollStateChanged(int arg0) {
            }
        });
    }

    @Override
    public void onTabReselected(Tab tab, FragmentTransaction ft) {
    }

    @Override
    public void onTabSelected(Tab tab, FragmentTransaction ft) {
        // on tab selected
        // show respected fragment view
        viewPager.setCurrentItem(tab.getPosition());
    }

    @Override
    public void onTabUnselected(Tab tab, FragmentTransaction ft) {
    }

}

编辑2:  我已做出如下所述的修改,但现在收到此错误:

The method setDataList(List<ContactItem>) in the type ContactListFragment is not applicable for the arguments ()

这是我更新的ListContact.java:

import com.nmiltner.slidedialer.free.data.ContactItem;
import com.nmiltner.slidedialer.free.ContactListFragment;
import com.nmiltner.slidedialer.free.MainActivity;

public class ListContactTask extends AsyncTask<Void, Void, List<ContactItem>> {
    private FragmentTransaction ft;
    private Activity activity;
    public ListContactTask(Activity activity, FragmentTransaction ft) {
        this.activity = activity;
        this.ft = ft;
    }

    public ListContactTask() {
    }

    @SuppressWarnings("unused")
    protected List<ContactItem> doInBackground(Void... params) {
         Cursor c = activity.getContentResolver().query(Data.CONTENT_URI,
                  new String[] {Data._ID, Data.DISPLAY_NAME,Phone.NUMBER, Data.CONTACT_ID,Phone.TYPE, Phone.LABEL},
                  Data.MIMETYPE + "='" + Phone.CONTENT_ITEM_TYPE + "'",
                  null, 
                  Data.DISPLAY_NAME);

        int count = c.getCount();
        boolean b = c.moveToFirst();
        String[] columnNames = c.getColumnNames();
        int displayNameColIndex = c.getColumnIndex("display_name");
        int idColIndex = c.getColumnIndex("_id");
        //int contactIdColIndex = c.getColumnIndex("contact_id");
        int col2Index = c.getColumnIndex(columnNames[2]);
        int col3Index = c.getColumnIndex(columnNames[3]);
        int col4Index = c.getColumnIndex(columnNames[4]);

        List<ContactItem> contactItemList = new LinkedList<ContactItem>();
        for(int i = 0; i < count ; i ++) {
            String displayName = c.getString(displayNameColIndex);
            String phoneNumber = c.getString(col2Index);
            int contactId = c.getInt(col3Index);
            String phoneType = c.getString(col4Index);

            long _id = c.getLong(idColIndex);
            ContactItem contactItem = new ContactItem();
            contactItem.mId= _id;
            contactItem.mContactId = contactId;
            contactItem.mDisplayName = displayName;
            contactItem.mPhone = phoneNumber;
            contactItemList.add(contactItem);
            boolean b2 = c.moveToNext();
        }
        c.close();
        return contactItemList;
    }

    protected void onPostExecute(List<ContactItem> result) {  
        ContactListFragment.setDataList();

    } 

}

和我的ContactListFragment:

public class ContactListFragment extends ListFragment {
    private ContactAdapter mAdapter;
    private List<ContactItem> contactItemList = new LinkedList<ContactItem>();

    private LayoutInflater mInflater;
    public boolean taskRun = false;
    long currentID = 0;
    long currentContactID = 0;
    public ContactListFragment() {}
    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        mInflater = (LayoutInflater) getActivity().getSystemService(Activity.LAYOUT_INFLATER_SERVICE);  
        if(!taskRun){
            FragmentTransaction ft = getFragmentManager().beginTransaction();
            ListContactTask task= new ListContactTask(getActivity(),ft);
            task.execute(); 

        }
        taskRun = true;
        mAdapter = new ContactAdapter(getActivity(), R.layout.lvmain,R.id.key, contactItemList);
        mAdapter .setInflater(mInflater);
        mAdapter.setLayout(R.layout.contact_card);
        setListAdapter(mAdapter);
        ListView listView = getListView();
        getListView().invalidate();

    }

    public void setDataList( List<ContactItem> list) {  
        Activity act = getActivity();
        this.contactItemList = list;
        if(act != null) {
            mAdapter = new ContactAdapter(act, R.layout.lvmain,R.id.key, list);
            mAdapter .setInflater(mInflater);
            mAdapter.setLayout(R.layout.contact_card);
            setListAdapter(mAdapter );
            getListView().invalidate();

        }
    }
}
class ContactAdapter extends ArrayAdapter<ContactItem> {

       private static String TAG = ContactAdapter.class.getName();
       private LayoutInflater inflator = null;
       List<ContactItem> pairList = null;
       private int layout;
       public ContactAdapter(Context context, int resource,
                int textViewResourceId, List<ContactItem> objects) {
            super(context, resource, textViewResourceId, objects);
            this.pairList = objects;
        }

        public void setInflater(LayoutInflater mInflater) {
            this.inflator = mInflater;
        }
        public void setLayout(int layout){
            this.layout = layout;

        }

        /**
         * Make a view to hold each row.
         * 
         * @see android.widget.ListAdapter#getView(int, android.view.View,
         *      android.view.ViewGroup)
         */
        public View getView(final int position, View convertView,
                ViewGroup parent) {
            ViewHolder holder;
            try {
                if (convertView == null) {
                    convertView = this.inflator.inflate(
                            layout, null);
                    holder = new ViewHolder();
                    holder.key = (TextView) convertView
                            .findViewById(R.id.key);
                    holder.value = (TextView) convertView.findViewById(R.id.value);
                    convertView.setTag(holder);
                }else {
                     holder = (ViewHolder) convertView.getTag();
                }
                ContactItem pair = (ContactItem) getItem(position);
                String key = pair.mDisplayName;
                String value = pair.mPhone;

                holder.key.setText(key);
                holder.value.setText(value);
                Log.i("pairing", "happened");
            } catch (Exception e) {
                Log.e(TAG, e.toString(), e);
            }
            return convertView;
        }

        static class ViewHolder {
            TextView key;
            TextView value;
        }

        public Filter getFilter() {
            return null;
        }

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

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

        public ContactItem getItem(int position) {
            return (ContactItem) super.getItem(position);
        }

        @Override
        public int getItemViewType(int position) {
            return super.getItemViewType(position);
        }

        @Override
        public int getViewTypeCount() {
            return super.getViewTypeCount();
        }

        @Override
        public boolean isEmpty() {
            return super.isEmpty();
        }
    }

1 个答案:

答案 0 :(得分:0)

您的AsyncTask可能在您调用ContactListFragment.setListAdapter()之前尚未完成工作,因此它可能首先处于空白状态。在ContactListFragment.setDataList()方法中处理您的UI更改(调用AsyncTask.onPostExecute()),这样您就可以确保AsyncTask完成并填充适配器。

修改:如果您想要特定的AsyncTask.onPostExecute(),可以在ContactListFragment中覆盖它:

ListContactTask task = new ListContactTask () {
    protected void onPostExecute(List<ContactItem> result) {
        // do specific stuff here, eg:
        ContactListFragment.this.setDataList(result);
    }
};
// Do other stuff