Search code examples
androidlistviewbluetoothcustom-adapter

how to add a Custom adapter to listview in android


This is my code to scan a near by bluetooth device but when i add a custom adapter to it it throwing an error..

public class MainActivity extends Activity {
ListView listDevicesFound;
Button btnScanDevice;
BluetoothAdapter bluetoothAdapter;
int REQUEST_CODE = 1;
MyAdapter adapter;
@Override
protected void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    btnScanDevice = (Button)findViewById(R.id.scan);
    bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
    listDevicesFound = (ListView)findViewById(R.id.list);
    listDevicesFound.setAdapter(adapter);
    CheckBlueToothState();
    btnScanDevice.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View arg0) {
            adapter.clear();
            if(bluetoothAdapter.startDiscovery())
            {
                Toast.makeText(getBaseContext(),"Scanning",     Toast.LENGTH_LONG).show();
            }


        }
    });

    registerReceiver(ActionFoundReceiver,new IntentFilter(BluetoothDevice.ACTION_FOUND));



}


@Override
protected void onDestroy() {
    super.onDestroy();unregisterReceiver(ActionFoundReceiver);
}
private void CheckBlueToothState()
{
    if (bluetoothAdapter == null)
    {
        Toast.makeText(getBaseContext(),"Bluetooth Not Supported",Toast.LENGTH_LONG).show();

    }
    else
    {
        if (bluetoothAdapter.isEnabled())
        {
            if(bluetoothAdapter.isDiscovering())
            {
                Toast.makeText(getBaseContext(),"Bluetooth is currently in device discover process",Toast.LENGTH_LONG).show();
            }
            else
            {
                Toast.makeText(getBaseContext(),"Bluetooth is Enabled",Toast.LENGTH_LONG).show();
                btnScanDevice.setEnabled(true);
            }
        }
        else
        {

            Toast.makeText(getBaseContext(), "Bluetooth is not Enabled", Toast.LENGTH_LONG).show();
            Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(enableBtIntent, REQUEST_CODE);

        }
    }
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if(requestCode == REQUEST_CODE)
    {
        CheckBlueToothState();
    }
}
private final BroadcastReceiver ActionFoundReceiver = new BroadcastReceiver(){

    @Override
    public void onReceive(Context context, Intent intent) {

        String action = intent.getAction();
        if(BluetoothDevice.ACTION_FOUND.equals(action)) {
            BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
            adapter.add(device.getName() + "\n" + device.getAddress());
            adapter.notifyDataSetChanged();
        }
    }};
   }

Custom adapter

public class MyAdapter extends ArrayAdapter<BlueDevices>

{
   Context context;
    int resources;
      ArrayList<BlueDevices> Devices = null;

     public MyAdapter(Context context, int resource,ArrayList<BlueDevices>      Devices) {
    super(context, resource, Devices);
    this.context=context;
    this.resources=resource;
    this.Devices=Devices;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    TextView textView = new TextView(getContext());
    BlueDevices item = getItem(position);
    textView.setTextColor(Color.BLACK);
    textView.setText(item.Name+" : "+item.Mac +"  date :"+item.getDateFormatted());
    return textView;
}
public List<BlueDevices> getAllItem() {

    List<BlueDevices> result = new ArrayList<>();
    for (int i = 0; i < getCount(); i++) {
        Log.e("fef", "getAllItem: " );
        result.add(getItem(i));
    }
    return result;
}

}

BlueDevice:

public class BlueDevices {
public String Name;
public String Mac;
public Date date;

public BlueDevices(String Name)
{
    this.Name=Name;
    this.Mac=Mac;
    this.date=date;

}
private SimpleDateFormat format = new SimpleDateFormat("dd MMMM yyyy");

public String getDateFormatted() {
    if (date == null){
        return " no date ";
    }
    return format.format(date);
}
}

this line throwing an error adapter.add(device.getName() + "\n" + device.getAddress());


Solution

  • There are many problems in your code.

     Change in Bean file BlueDevices
    
    change constructor to take two arguments.
    
    public BlueDevices(String Name, String Mac)
    {
        this.Name=Name;
        this.Mac=Mac;
    }
    you no need to set data because you already created method to get data. 
    change in onCreate method in activity class
    
    In your adapter class constructor take three arguments.
    
    MyAdapter(Context context, int resource,ArrayList<BlueDevices> Devices);
    
    so you have context that get from getApplicationContext(), resource is your layout and Devices is arraylist of your bean class. for that you have to create one layout in your res/layout and one ArrayList with bean typecase.
    
            ArrayList<BlueDevices> list = new ArrayList<>();
    
    add your all devices in to this list using.
            list.add(new BlueDevices("Device1","ASDF234SDFSADF"));
            list.add(new BlueDevices("Device2","GSDFG34SAF32DF"));
    
    Now create object of adapter class
    
            MyAdapter adapter = new MyAdapter(getApplicationContext(),R.layout.list_items,list);
    
    set this adapter to your ListView using
    
            listview.setAdapter(adapter);
    
    Now create method in adapter class
    
            public BlueDevices getDevices(int position) {return Devices.get(position);}
    
    Add getter method in BlueDevices
    
            public String getName(){
                return Name;
            }
            public String getMac(){
                return Mac;
            }
    
    Get devices list from adapter in list onItemClickListener
    
            BlueDevices bean = adapter.getDevices(position);
            String name = bean.getName();
            String mac = bean.getMac();