2017-01-09 2 views
0

Список для этого диалога не обновляется. В большинстве других сообщений stackoverflow об этом проблема связана с привязкой привязки массива адаптера, но я не делал этого здесь. Есть ли еще одно объяснение невозможности обновления?listView не обновляется

/** 
    * This class represents a dialog fragment that appears on clicking the connect button of 
    * the main activity. The fragment displays a list of all discovered bluetooth devices. 
    */ 
public class DiscoveredDialogFragment extends DialogFragment { 


    public static DiscoveredDialogFragment newInstance() { 
     return new DiscoveredDialogFragment(); 
    } 

    public interface DiscoveredDialogListener { 
     public void onDeviceSelectedForConnection(String addressMac); 

     public void onScanClicked(); 
    } 

    @BindView(R.id.listview) 
    ListView mListView; 
    private SimpleAdapter mAdapter; 
    private ArrayList<HashMap<String, String>> mListDevice; 
    private DiscoveredDialogListener mDiscoveredDialogListener; 

    /** 
    * Display the view on on create. 
    * @param inflater 
    * @param container 
    * @param savedInstanceState 
    * @return 
    */ 
    @Override 
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { 
     View view = inflater.inflate(R.layout.dialog_fragment_devices_discovered, null); 
     getDialog().getWindow().requestFeature(Window.FEATURE_NO_TITLE); 
     getDialog().getWindow().setBackgroundDrawable(new ColorDrawable(0)); 
     getDialog().setCanceledOnTouchOutside(false); 
     ButterKnife.bind(this, view); 
     return view; 
    } 

    /** 
    * On activity being created, connect mListDevice arraylist with mListView. This will display 
    * the Name and MacAddress on each line of the listview. 
    * @param savedInstanceState 
    */ 
    @Override 
    public void onActivityCreated(Bundle savedInstanceState) { 
     super.onActivityCreated(savedInstanceState); 

     mListDevice = new ArrayList<HashMap<String, String>>(); 
     mAdapter = new SimpleAdapter(this.getActivity(), mListDevice, 
       android.R.layout.two_line_list_item, 
       new String[]{"Name", "AddressMac"}, 
       new int[]{android.R.id.text1, android.R.id.text2}); 
     mListView.setAdapter(mAdapter); 
     mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() { 
      @Override 
      public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) { 
       //create a new bluetooth client with the associated macaddress, and give this client 
       //its own thread 
       mDiscoveredDialogListener.onDeviceSelectedForConnection(mListDevice.get(position).get("AddressMac")); 
       dismiss(); 
      } 
     }); 
    } 

    public void setListener(DiscoveredDialogListener discoveredDialogListener) { 
     mDiscoveredDialogListener = discoveredDialogListener; 
    } 

    @Override 
    public void onDestroyView() { 
     super.onDestroyView(); 
    } 

    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     EventBus.getDefault().register(this); 
     Log.e("EventBus", "registered"); 
    } 

    @Override 
    public void onDestroy() { 
     super.onDestroy(); 
     EventBus.getDefault().unregister(this); 
    } 

    /** 
    * On clicking scan, discover all discoverable bluetooth devices 
    */ 
    @OnClick(R.id.scan) 
    public void scan() { 
     mDiscoveredDialogListener.onScanClicked(); 
    } 

    /** 
    * Update mListDevice with new bluetooth devices and their associated information. 
    * @param device 
    */ 
    @Subscribe 
    public void onEventMainThread(BluetoothDevice device) { 
     Log.e("BluetoothAdapter", "found a device"); 
     HashMap<String, String> item = new HashMap<String, String>(); 
     item.put("Name", device.getName()); 
     item.put("AddressMac", device.getAddress()); 
     if(!mListDevice.contains(item)){ 
      mListDevice.add(item); 
     } 

     mAdapter.notifyDataSetChanged(); 
    } 

EDIT

Оказывается, что все работает нормально, но ListView пишет в белый текст на белом фоне.

+0

Код выглядит хорошо, проблема может быть с высотой listView, поместить некоторый цвет фона в listview и проверить, отображается ли оно в представлении. –

+1

Оказывается, что цвет фона действительно был проблемой. В списке был белый текст на белом фоне :) – Chris

ответ

0

SimpleAdapater не предназначен для использования с данными, которые меняются; он обрабатывает только статические данные. Так что если вы хотите обновить ListView, то вы должны setAdapter каждый раз, как этот

@Subscribe 
public void onEventMainThread(BluetoothDevice device) { 

    HashMap<String, String> item = new HashMap<String, String>(); 
    item.put("Name", device.getName()); 
    item.put("AddressMac", device.getAddress()); 
    if(!mListDevice.contains(item)){ 
     mListDevice.add(item); 
    } 
    mAdapter = new SimpleAdapter(this.getActivity(), mListDevice, 
      android.R.layout.two_line_list_item, 
      new String[]{"Name", "AddressMac"}, 
      new int[]{android.R.id.text1, android.R.id.text2}); 
    mListView.setAdapter(mAdapter); 
    mAdapter.notifyDataSetChanged(); 
} 

Пожалуйста Примечание Поскольку ваши данные динамическое использование CustomAdapter что увеличивает ваши ListView выступления

0

адаптер

SimpleAdapter 
     { 

     mListDevice = new ArrayList<HashMap<String, String>>(); 
     ... 


    // adapter method to call 
     public void updateData(ArrayList<HashMap<String,String>> mListDevice) 
     { 
     this.mListDevice =mListDevice ; 
     notifyDataSetChanged(); 
     } 

     } 

Вызов метода из Фрагмент/деятельность

HashMap<String, String> item = new HashMap<String, String>(); 
    item.put("Name", device.getName()); 
    item.put("AddressMac", device.getAddress()); 
mListDevice.add(item); 
mAdapter.updateData(mListDevice); 
Смежные вопросы