android自定义列表适配器不显示项目

Posted

技术标签:

【中文标题】android自定义列表适配器不显示项目【英文标题】:android custom List Adapter not displaying items 【发布时间】:2015-04-27 22:10:08 【问题描述】:

我正在使用片段来显示我发现的所有对等点,它成功到达片段,但在尝试显示对等点时崩溃。

片段

    public class peerItemFragment extends ListFragment 

        private List<WifiP2pDevice> peers = new ArrayList<>();
        ProgressDialog progressDialog = null;
        View mContentView = null;
        private WifiP2pDevice device;

        @Override
        public void onActivityCreated(Bundle savedInstanceState) 
            super.onActivityCreated(savedInstanceState);
            this.setListAdapter(new WiFiPeerListAdapter(getActivity(), R.layout.row_devices, peers));
        

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) 
            mContentView = inflater.inflate(R.layout.fragment_item_grid, null);
            return mContentView;
        

        /**
         * @return this device
         */
        public WifiP2pDevice getDevice() 
            return device;
        

        private static String getDeviceStatus(int deviceStatus) 
            Log.d(sendActivity.TAG, "Peer status :" + deviceStatus);
            switch (deviceStatus) 
                case WifiP2pDevice.AVAILABLE:
                    return "Available";
                case WifiP2pDevice.INVITED:
                    return "Invited";
                case WifiP2pDevice.CONNECTED:
                    return "Connected";
                case WifiP2pDevice.FAILED:
                    return "Failed";
                case WifiP2pDevice.UNAVAILABLE:
                    return "Unavailable";
                default:
                    return "Unknown";
            
        

        /**
         * Initiate a connection with the peer.
         */
        @Override
        public void onListItemClick(ListView l, View v, int position, long id) 
            WifiP2pDevice device = (WifiP2pDevice) getListAdapter().getItem(position);
            ((DeviceActionListener) getActivity()).showDetails(device);
        

        /**
         * Array adapter for ListFragment that maintains WifiP2pDevice list.
         */
        private class WiFiPeerListAdapter extends ArrayAdapter<WifiP2pDevice> 

            private List<WifiP2pDevice> items;

            /**
             * @param context
             * @param textViewResourceId
             * @param objects
             */
            public WiFiPeerListAdapter(Context context, int textViewResourceId,
                                       List<WifiP2pDevice> objects) 
                super(context, textViewResourceId, objects);
                items = objects;

            

            @Override
            public View getView(int position, View convertView, ViewGroup parent) 
                View v = convertView;
                if (v == null) 
                    LayoutInflater vi = (LayoutInflater) getActivity().getSystemService(
                            Context.LAYOUT_INFLATER_SERVICE);
                    v = vi.inflate(R.layout.row_devices, parent, false);
                
                WifiP2pDevice device = items.get(position);
                if (device != null) 
                    TextView top = (TextView) v.findViewById(R.id.device_name);
                    TextView bottom = (TextView) v.findViewById(R.id.device_details);
                    if (top != null) 
                        top.setText(device.deviceName);
                    
                    if (bottom != null) 
                        bottom.setText(getDeviceStatus(device.status));
                    
                
                return v;
            
        

        /**
         * Update UI for this device.
         *
         * @param device WifiP2pDevice object
         */
        public void updateThisDevice(WifiP2pDevice device) 
            this.device = device;
            TextView view = (TextView) mContentView.findViewById(R.id.tvMyName);
            view.setText(device.deviceName);
            view = (TextView) mContentView.findViewById(R.id.tvMyStatus);
            view.setText(getDeviceStatus(device.status));
        


        public void addPeers(WifiP2pDeviceList peerList) 
            if (progressDialog != null && progressDialog.isShowing()) 
                progressDialog.dismiss();
            

            peers.clear();
            peers.addAll(peerList.getDeviceList());
            ((WiFiPeerListAdapter) getListAdapter()).notifyDataSetChanged();

            if (peers.size() == 0) 
                Log.d(sendActivity.TAG, "No devices found");
                return;
            
        

        public void clearPeers() 
            peers.clear();
            ((WiFiPeerListAdapter) getListAdapter()).notifyDataSetChanged();
        

问题 atm 是当我从主类调用时使用以下代码调用它...

            peerItemFragment peerFragment = new peerItemFragment();

        FragmentManager managerAuthenticate = getFragmentManager();

        FragmentTransaction transactionAuthen = managerAuthenticate.beginTransaction();

        // Replace whatever is in the fragment_container view with this fragment,
        // and add the transaction to the back stack so the user can navigate back
        transactionAuthen.replace(R.id.fragment_container, peerFragment);
        transactionAuthen.addToBackStack(null);


//***************************************************
        Bundle bundle = new Bundle();
        bundle.putParcelableArrayList("list", mService.peerList);
        peerFragment.setArguments(bundle);

        // Commit the transaction
        transactionAuthen.commit();

在查看并逐步运行它后,我发现它与以下行有问题?

    ((WiFiPeerListAdapter) getListAdapter()).notifyDataSetChanged();

真的很奇怪,因为这都是从谷歌样本中提取的,不知道为什么会崩溃..

另请注意,该片段有一个 listView 命名为 google 建议的列表(没有问题)。

很难看出哪里出了问题?会不会是适配器不在?

编辑 ------------------------------------------- ---------------------------------------

从活动中调用片段

        peerItemFragment peerFragment = new peerItemFragment();

    FragmentManager managerAuthenticate = getFragmentManager();

    Bundle bundle = new Bundle();
    ArrayList<WifiP2pDevice> list = new ArrayList<>(mService.peerList.getDeviceList());
    bundle.putParcelableArrayList("list", list);

    peerFragment.setArguments(bundle);

    FragmentTransaction transactionAuthen = managerAuthenticate.beginTransaction();

    // Replace whatever is in the fragment_container view with this fragment,
    // and add the transaction to the back stack so the user can navigate back
    transactionAuthen.replace(R.id.fragment_container, peerFragment);
    transactionAuthen.addToBackStack(null);

    // Commit the transaction
    transactionAuthen.commit();

    //pass peer list to fragment to display
    //peerFragment.addPeers(mService.peerList);


编辑后的片段

public class peerItemFragment extends ListFragment 

private List<WifiP2pDevice> peers = new ArrayList<>();
ProgressDialog progressDialog = null;
View mContentView = null;
private WifiP2pDevice device;

@Override
public void onActivityCreated(Bundle savedInstanceState) 
    super.onActivityCreated(savedInstanceState);
    this.setListAdapter(new WiFiPeerListAdapter(getActivity(), R.layout.row_devices, peers));

    Bundle bundle = getArguments();

    peers = bundle.getParcelableArrayList("list");

    ((WiFiPeerListAdapter) getListAdapter()).notifyDataSetChanged();



@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) 
    mContentView = inflater.inflate(R.layout.fragment_item_grid, null);
    return mContentView;


/**
 * @return this device
 */
public WifiP2pDevice getDevice() 
    return device;


private static String getDeviceStatus(int deviceStatus) 
    Log.d(sendActivity.TAG, "Peer status :" + deviceStatus);
    switch (deviceStatus) 
        case WifiP2pDevice.AVAILABLE:
            return "Available";
        case WifiP2pDevice.INVITED:
            return "Invited";
        case WifiP2pDevice.CONNECTED:
            return "Connected";
        case WifiP2pDevice.FAILED:
            return "Failed";
        case WifiP2pDevice.UNAVAILABLE:
            return "Unavailable";
        default:
            return "Unknown";
    


/**
 * Initiate a connection with the peer.
 */
@Override
public void onListItemClick(ListView l, View v, int position, long id) 
    WifiP2pDevice device = (WifiP2pDevice) getListAdapter().getItem(position);
    ((DeviceActionListener) getActivity()).showDetails(device);


/**
 * Array adapter for ListFragment that maintains WifiP2pDevice list.
 */
private class WiFiPeerListAdapter extends ArrayAdapter<WifiP2pDevice> 

    private List<WifiP2pDevice> items;

    /**
     * @param context
     * @param textViewResourceId
     * @param objects
     */
    public WiFiPeerListAdapter(Context context, int textViewResourceId,
                               List<WifiP2pDevice> objects) 
        super(context, textViewResourceId, objects);
        items = objects;

    

    @Override
    public View getView(int position, View convertView, ViewGroup parent) 
        View v = convertView;
        if (v == null) 
            LayoutInflater vi = (LayoutInflater) getActivity().getSystemService(
                    Context.LAYOUT_INFLATER_SERVICE);
            v = vi.inflate(R.layout.row_devices, parent, false);
        
        WifiP2pDevice device = items.get(position);
        if (device != null) 
            TextView top = (TextView) v.findViewById(R.id.device_name);
            TextView bottom = (TextView) v.findViewById(R.id.device_details);
            if (top != null) 
                top.setText(device.deviceName);
            
            if (bottom != null) 
                bottom.setText(getDeviceStatus(device.status));
            
        
        return v;
    

【问题讨论】:

【参考方案1】:

你的代码的问题是当你调用addPears时,onActivityCreated可能还没有被调用(事务没有以同步方式执行),导致getListAdapter返回null。要修复它,您可以在bundle 中添加您的peerList,(WifiP2pDeviceparcelable),并将此设置为arguments 为您的Fragment

Bundle bundle = new Bundle();
ArrayList<WifiP2pDevice> list = new ArrayList<>(mService.peerList.getDeviceList());
bundle.putParcelableArrayList("list", list);
peerFragmet.setArguments(bundle);

并摆脱

peerFragment.addPeers(mService.peerList);

onActivityCreated 被调用时,你可以用getArguments 读回包,检索你的peerList 对象并实例化你的adpater

【讨论】:

【参考方案2】:

您的目录显示:

at com.haswell.phoneduplicator.peerItemFragment.addPeers(peerItemFragment.java:137)

那一行是什么?

【讨论】:

我在以下行中提出的问题:'((WiFiPeerListAdapter) getListAdapter()).notifyDataSetChanged();' 然后getListAdapter 正在返回null。检查原因。

以上是关于android自定义列表适配器不显示项目的主要内容,如果未能解决你的问题,请参考以下文章

当按下 menuItem 以在 android 中显示用于列表视图的自定义适配器时,应用程序崩溃

列表项布局未将项目显示为全宽

带有适配器的 Android 列表视图仅显示第一项(多次)

获得 250 多个项目,但自定义列表视图不显示任何内容

自定义适配器不显示数据

Android listview 项目使用数组适配器在图像上显示文本