summaryrefslogtreecommitdiff
path: root/Defogger/src/no/mork/android/defogger/ScanListAdapter.java
blob: e38605652c7045196a1963cec356f18e51bf1edc (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
package no.mork.android.defogger;

import android.bluetooth.BluetoothDevice;
import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View.OnClickListener;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import java.util.ArrayList;
import no.mork.android.defogger.ScannerActivity;

// originally from https://developer.android.com/guide/topics/ui/layout/recyclerview
// but converted to simpler ArrayAdapter using https://developer.android.com/guide/topics/ui/declaring-layout.html#FillingTheLayout


public class ScanListAdapter extends BaseAdapter {
    private static String msg = "Defogger Adapter: ";
    private ArrayList<BluetoothDevice> mObjects;
    private Context mCtx;
    private LayoutInflater mInflater;
    private int mRes;
    private int mTxtId;
    
    public ScanListAdapter(Context context, int resource, int textViewResourceId)  {
	mCtx = context;
	mObjects = new ArrayList<BluetoothDevice>();
	mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
	mRes = resource;
	mTxtId = textViewResourceId;
    }

    @Override
    public int getCount() {
	return mObjects.size() ;
    }

    @Override
    public BluetoothDevice getItem(int position) {
	return mObjects.get(position);
    }

    @Override
    public long getItemId(int position) {
	return getItem(position).hashCode();
    }

    @Override
    public View getView(int position, View convertView, ViewGroup container) {
	BluetoothDevice device = getItem(position);

	if (convertView == null) {
	    convertView = mInflater.inflate(mRes, container, false);
	}
	
	((TextView) convertView.findViewById(mTxtId)).setText(device.getAddress() + " - " + device.getName());

	// react when selecting iteam
	convertView.setOnClickListener(new OnClickListener() {
		private BluetoothDevice ret = device;
		private ScannerActivity c = (ScannerActivity)mCtx;

		@Override
		public void onClick(View v) {
		    Log.d(msg, "ScanListAdapter: onClick() will return " + ret.getName());
		    c.returnScanResult(ret);
		}
	    });

	return convertView;
    }

    public void add(BluetoothDevice device) {

	// FIXME: Export methods to allow moving this test to the caller
	if (device.getName() != null && mObjects.indexOf(device) < 0) { // avoid duplicates and ignore nameless devices
	    mObjects.add(device);
	    notifyDataSetChanged();
	}
    }
}