duplicates in the ListView Bluetooth - android

First sorry for my English it is something bad.
Now i am currently programming an application and there is a problem with the list.
I always get duplicates in my list after searching for Devices, when i search again,I get the same devices again. I have to tried to use sets but i get still duplicates.
I don't know how to solve this problem.
Please help someone with Code.
Thank you advance.
Here is my Code:
`
public void Init(){
foundDevicesSet = new HashSet<String>();
tBtn = (ToggleButton)findViewById(R.id.toggleButton1);
availableDivce = (TextView)findViewById(R.id.textView2);
bluetoohOff =(TextView)findViewById(R.id.textView1);
DeviceList = (ListView)findViewById(R.id.listView1);
searchButton =(Button)findViewById(R.id.button1);
deviceNameAdapter = new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_list_item_1);
DeviceList.setAdapter(deviceNameAdapter);
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
registerReceiver(receiver, filter);
receiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
String action = intent.getAction();
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
BluetoothDevice newDevice = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
if (newDevice.getBondState() != BluetoothDevice.BOND_BONDED) {
foundDevicesSet.add(newDevice.getName() + "|" + newDevice.getAddress());
for(String one : foundDevicesSet){
deviceNameAdapter.add(one);
}
}
}
}
};
} `

I'm on a Bluetooth project too and I was facing this same problem 5 minutes ago, not with paired devices but with available devices around. Here is the code that made it work without any duplicate device. I must say I'm using a ListView to show them and an ArrayAdapter aswell:
if (mNewDevicesArrayAdapter.getPosition((device.getName()+ "\n" + device.getAddress())) == -1)
{
mNewDevicesArrayAdapter.add(device.getName() + "\n" + device.getAddress());
mNewDevicesArrayAdapter.notifyDataSetChanged();
}
This instruction looks for this device.getName() + "\n" + device.getAddress() in the ArrayAdapter because that's is the format I use to save it in. Hope it helps you.

Each time a new device is found, you're adding the entire devices set to the adapter again... So, either:
Call deviceNameAdapter.add(newDevice.getName() + "|" + newDevice.getAddress()); instead of adding it to the set.
Call deviceNameAdapter.clear() before adding the entire set to the adapter.

Related

android WiFi scanner, list only networks with specific SSID

I need to create WiFi scanner app on android device. I managed to do it, yet there is something I don't know how to deal with.
class WifiReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
sb = new StringBuilder();
Comparator<ScanResult> comparator = new Comparator<ScanResult>() {
#Override
public int compare(ScanResult o1, ScanResult o2) {
return (o1.level>o2.level ? -1 : (o1.level==o2.level ? 0 : 1));
}
};
lista = wifiManager.getScanResults();
Collections.sort(list, comparator);
for (int i = 0; i < list.size(); i++) {
scanResult = wifiManager.getScanResults().get(i);
sb.append(new Integer(i + 1).toString() + ". " + (list.get(i)).SSID + " " + (list.get(i)).BSSID + " " + (list.get(i)).level + "\n");
}
txt.setText(sb);
wifiManager.startScan();
}
}
There are several WiFi networks in the building with the same SSID, lets say ABCD. I want to save in list, which is List<ScanResult> type, only networks with this specific SSID ABCD without the need to create another field such as list if possible. I woukd be grateful for any help
I assume you mean you want a way to filter the scan and return only the specified ssid, there is no way that I know of on the back-end to do that. You can go through your existing list and pull out the ones you want and save to a new List.
You can also use your existing code and check to see if the ssid matches inside your loop and only build the string if it does.
Most of the time you will be showing a list of available networks in a list or recycler view so usually the secondary list is the way to go.

Cannot assign variable value to a string from extra.getString();

New to android, I'm currently trying to send a String value from one Activity to another. I have looked through several threads like How to use putExtra() and getExtra() for string data for an answer, but I cannot get it to work.
The string I want to send is:
public void golf(View view) {
Intent intent = new Intent(SearchSport.this, EventList.class);
intent.putExtra("type", "golf");
startActivity(intent);
and my receiver looks like
String type;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_event_list);
Intent intent = getIntent();
Bundle extras = intent.getExtras();
if ( extras != null)
type = extras.getString("type");
if (type == "golf"){
TextView eventName = (TextView) findViewById(R.id.EOName);
TextView eventTime = (TextView) findViewById(R.id.EOTime);
TextView eventLocation = (TextView) findViewById(R.id.EOLocation);
DatabaseOperations dop = new DatabaseOperations(ctx);
Cursor CR = dop.getInformation(1);
CR.moveToFirst();
eventName.setText(CR.getString(1));
eventTime.setText(CR.getString(7) + " " + CR.getString(8) + ". " + CR.getString(9) + " kl. " + CR.getString(10) + ":" + CR.getString(11));
eventLocation.setText(CR.getString(4));}
else {Toast toast = Toast.makeText(this, "Error in Type.", Toast.LENGTH_LONG);
toast.show();}
I have no Idea what's wrong here. The app displays the toast everytime I test it, instead of filling out the TextViews with the data from my database entry.
EDIT: Code has been changed based on answers, but the problem has not yet been solved. Writing if (type.equals("golf")){} instead of if (type == "golf"){} crashed the app.
EDIT 2: Problem solved! Fixed case sensitivity, used .equals instead of ==, and wrote the receiver as
if(getIntent().hasExtra("Type"))
type = getIntent().getStringExtra("Type");
In the end, it turns out is was the virtual device I used which crashed the app, for as of yet unknown reasons. When tested on an actual android phone, the app works as intented.
Thanks to everyone for their help!
try this
if(getIntent().hasExtra("Type"))
type = getIntent().getStringExtra("Type");
Change the key it is case sensitive :
type = extras.getString("Type");
Key is wrong when try to get String from Intent Extra :
type = extras.getString("type");
Replace with :
type = extras.getString("Type");
Note : Also use equals() instead == for comparing String
if (type.equals("golf")){
1) First keys are case sensitive
2) pass as
Bundle bundle = new Bundle()
bundle.putString("type","golf");
intent.putExtras(bundle);
after that get it using
Bundle received = i.getExtras();
received.getString("type");
As you are passing the value using Extra. You must have to catch that using getStringExtra(); and the Key must be case sensitive.
Intent i = getIntent();
type = i.getStringExtra("Type");

Data passing through intents with string returns null

I'm trying to pass a string and a few integers to another activity. The problem is that the integers can be passed successfully, but not the string value. I'm searched the forum for similar questions, but I was not able to find my problem.
Main Activity Class:
public void onClick(View v)
{
Intent debug = new Intent("bluetooth_4.pack.USBDebugMode");
if((port != null))
{
debug.putExtra("port", port.toString());
debug.putExtra("buadRate", buadRate);
debug.putExtra("dataBits", dataBits);
debug.putExtra("stopBits", stopBits);
debug.putExtra("parity", parity);
startActivity(debug);
Toast.makeText(MainActivity.this, "Switching to USB Debug Mode" , Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(MainActivity.this, "You haven't selected a device yet!" , Toast.LENGTH_SHORT).show();
}
}
New Activity Class:
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.usb_debug_main);
Button button1 = (Button) findViewById(R.id.button1);
Button button2 = (Button) findViewById(R.id.button2);
button1.setOnClickListener(myButtonListener1);
button2.setOnClickListener(myButtonListener2);
ActionBar actionBar = getActionBar();
actionBar.hide();
port = getIntent().getStringExtra(port);
buadRate = getIntent().getIntExtra("buadRate", 0);
dataBits = getIntent().getIntExtra("dataBits", 0);
stopBits = getIntent().getIntExtra("stopBits", 0);
parity = getIntent().getDoubleExtra("parity", 0);
mUsbManager = (UsbManager) getSystemService(Context.USB_SERVICE);
TextView text = (TextView) findViewById(R.id.textView2);
text.append("Port: " + port + "\r\n");
text.append("Buad Rate: " + buadRate + "\r\n");
text.append("Data Bits: " + dataBits + "\r\n");
text.append("Stop Bits: " + stopBits + "\r\n");
text.append("Parity: " + parity + "\r\n");
}
I have a text box, and all it does is that the displays some data, while parameters such as buad rate, data bits, stop bits, and parity has data, port always return null.
However, port must not be null in order to start the activity.
Change this line
port = getIntent().getStringExtra(port);
To
port = getIntent().getStringExtra("port");
You forget to pass the correct key in your NewActivityClass, i have a tip for you!
Always define public constants some where in your app. ( i usually create MyConstants.Java for that purpose. This is the only way in which you can be sure that you are passing the correct keys in both sending class and receiving class
Thanks.

Monodroid ListView get selected item typecast error

I have this problem with listview item and hoping that you guys can help me fix this.
My goal is to fill listview with list and when user touches one these items, i want to have another view loaded. Adding items works fine, but when i get the value from selected item and typecast it to the correct object, it comes with " ‘invalid cast’ cannot cast..." and crashes.
FYI, I use the Android 4.0 sim, and these are part of the code:
SetContentView(Resource.Layout.ArchiveList);
ListView lstArchiveList = FindViewById<ListView>(Resource.Id.lstArchive);
if (lstArchiveList != null) {
ArrayAdapter<MobileContracts.Archive> archivesAdapter = new
ArrayAdapter<MobileContracts.Archive>(this, Resource.Layout.ListItem, sessionData.Archives.Archive);
lstArchiveList.Adapter = archivesAdapter;
lstArchiveList.TextFilterEnabled = true;
lstArchiveList.ItemClick += new EventHandler<AdapterView.ItemClickEventArgs>(lstArchiveList_ItemClick);
archivesAdapter.NotifyDataSetChanged();
}
OnClick event handler:
void lstArchiveList_ItemClick(object sender, AdapterView.ItemClickEventArgs e) {
SetContentView(Resource.Layout.SearchDocuments);
ListView lstEditableIndexList = FindViewById<ListView>(Resource.Id.lstEditableIndexList);
if (lstEditableIndexList != null) {
Console.WriteLine("sender type: {0}", sender.GetType().FullName);
Object currentItem = e.Parent.GetItemAtPosition(e.Position);
MobileContracts.Archive selectedArchive = (MobileContracts.Archive) currentItem; //invalid cast?
Toast.MakeText(Application, selectedArchive.Name + " => " + selectedArchive.Id, ToastLength.Short).Show();
}
Any help appreciated. Thank's a lot in advance.
Cheers, Inoel
Never mind, I figure this out.
Replace this:
MobileContracts.Archive selectedArchive = (MobileContracts.Archive) currentItem; //invalid cast?
with this:
System.Reflection.PropertyInfo propertyInfo = currentItem.GetType().GetProperty("Instance");
MobileContracts.Archive selectedArchive = propertyInfo.GetValue(currentItem, null) as MobileContracts.Archive;

Replace entry in ArrayAdapter

Is there any way to replace a value in an ArrayAdapter
mPairedDevicesArrayAdapter = new ArrayAdapter<String>(this, R.layout.device_name);
..
..
for (BluetoothDevice device : pairedDevices) {
String name = MPGDeviceDetailsControl.getDeviceDetails(this, device.getAddress(), device.getName()).getDisplayName();
mPairedDevicesArrayAdapter.add(name + "\n" + device.getAddress());
}
If I wish to replace one of the entries is there any way of doing it without deleting and reinstering.
Problem with that is that it puts it at the bottom.
Something like this should work to replace items
int i = 0;
for (BluetoothDevice device : pairedDevices) {
String name = MPGDeviceDetailsControl.getDeviceDetails(this, device.getAddress(), device.getName()).getDisplayName();
mPairedDevicesArrayAdapter.remove(name); // has to copy all items back 1 position
mPairedDevicesArrayAdapter.insert(name + "\n" + device.getAddress(), i); // copy them +1 again
i++;
}
but it would be more efficient, if you have access to the List that is backing this ArrayAdapter and replace / modify that.
ArrayList<Strign> mList = new ArrayList<String>();
mPairedDevicesArrayAdapter = new ArrayAdapter<String>(this, R.layout.device_name, mList);
// setup
mList.add...
mPairedDevicesArrayAdapter.notifyDatasetChanged();
// change something
mList.set(i, newValue); // just a replace, no copy
mPairedDevicesArrayAdapter.notifyDatasetChanged();
It's possible to replace the display value without reinserting and using nested adapters. Simply change original collection and call adapter's notifyDatasetChanged()
//adapter initialization
MyClass[] someArray = ... ;
ArrayList<Strign> adapter = new ArrayList<String>(context, R.layout.item_layout, someArray);
//change something
someArray[i] = newValue;
adapter.notifyDatasetChanged();
It's pretty much the same as zapl's answer except it doesn't use nested adapters. It should work the same when the adapter is initialized with List but I haven't tested that.
No You can replace without deleting or reinserting.

Categories

Resources