2015-02-25 2 views
1

Я использую фрагмент для отображения всех моих сверстников, которые я обнаруживаю, он успешно достигает фрагмента, но сбой при попытке отобразить сверстников.Андроид Custom Adapter не отображает элементы

фрагмент

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(); 
     } 

вопрос атм, когда я называю его, используя следующий код, когда вызывается из основного класса ...

  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(); 

действительно странно, как это все берется из образца Google, не знаю, почему он выходит из строя ..

Пожалуйста, обратите внимание, что этот фрагмент имеет ListView названный список, как не было предложено Google (не проблема существует) ,

найти его очень сложно, чтобы увидеть, где он поступил не так? может ли быть, что адаптера нет?

EDIT -------------------------------------------- --------------------------

вызов фрагмента от активности

 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); 

} 

фрагмент после EDIT

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. Чтобы исправить это, вы можете добавить свой peerList, в bundle (WifiP2pDevice являются parcelable), и установить этот как 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

0

В вашем журнале говорится:

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

Что на этой линии?

+0

что я поставил в questio n следующая строка: '((WiFiPeerListAdapter) getListAdapter()). notifyDataSetChanged();' –

+0

Затем 'getListAdapter' возвращает' null'. Проверьте, почему. –