I am currently trying to implement a Bluetooth connection in an Android application using a few different tutorials and am running into issues trying to add detected paired devices to a ListView for the user to choose from.
It is currently throwing the error "Cannot resolve symbol items" in the line below, but I'm not sure what to replace items with or if that's the only issue.
itemsAdapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, items);
I would really appreciate it if someone could correct my syntax in the Java code.
Thanks!
Java Code
package com.example.khite.wheelnav;
import android.content.Intent;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.MenuItem;
import android.view.View;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import java.util.Set;
public class ConnectActivity extends ActionBarActivity {
private static final int REQUEST_ENABLE_BT = 1234;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_connect);
// Create Bluetooth Adapter
BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (mBluetoothAdapter == null) {
Intent intent;
intent = new Intent(this, NoBluetoothActivity.class);
startActivity(intent);
}
// Enable Bluetooth
if (!mBluetoothAdapter.isEnabled()) {
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
}
// Create an Array Adapter to Add Devices to
ArrayAdapter<String> itemsAdapter;
itemsAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, items);
//Query Paired Devices
Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
// If there are paired devices
if (pairedDevices.size() > 0) {
// Loop through paired devices
for (BluetoothDevice device : pairedDevices) {
// Add the name and address to an array adapter to show in a ListView
itemsAdapter.add(device.getName() + "\n" + device.getAddress());
}
}
// Add Paired Devices to a List View
ListView listView = (ListView) findViewById(R.id.listView);
listView.setAdapter(itemsAdapter);
}
public void openChooseFunctionActivity(View view){
//open choose function activity
Intent intent;
intent = new Intent(this, ChooseFunctionActivity.class);
startActivity(intent);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
XML Code
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
tools:context="com.example.khite.wheelnav.ConnectActivity">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Continue"
android:id="#+id/button2"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:onClick="openChooseFunctionActivity"
android:background="#ff8180fd"
android:textColor="#ff000000" />
<ListView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/listView"
android:layout_centerHorizontal="true" />
</RelativeLayout>
initialized first your items collection, then an adapter
//Query Paired Devices
Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
// If there are paired devices
List<String> items = new ArrayList<String>();
if (pairedDevices.size() > 0) {
// Loop through paired devices
for (BluetoothDevice device : pairedDevices) {
// Add the name and address to an array adapter to show in a ListView
items.add(device.getName() + "\n" + device.getAddress());
}
}
// Create an Array Adapter to Add Devices to
ArrayAdapter<String> itemsAdapter;
itemsAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, items);
"items" in your code is not initalized at all. You have to pass a String[] or List<String> object as the last parameter of the ArrayAdapter constructor.
"Cannot resolve symbol x" generally means variable x cannot be found.
Related
I've made an app, that is discovering nearby bluetooth devices and etc. I can get bluetooth adapter, open-close processes, get paired devices, discovering process. Everthing is fine but discovery process isn't working properly.
I tested my app on 5 different real devices. At the moment I realized I have a problem on Android version but I'm not sure about that.
My app's discovery process is working on,
Huawei P7 - Android Version: 4.4.2
Sony Xperia Z - Android Version: 5.1.1
Samsung Galaxy J3 - Android Version: 5.1.1
My app's discovery process isn't working on,
Samsung Galaxy S7 - Android Version: 6.0.1
Samsung Galaxy J7 - Android Version: 6.0.1
MainActivity.java
package com.sphinxlike.bluetoothexample;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Handler;
import android.os.Parcelable;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Set;
import static java.lang.System.out;
public class MainActivity extends AppCompatActivity implements View.OnClickListener{
/* DECLERATIONS */
// Button
Button openBtn = null; // Open button
Button closeBtn = null; // Close button
Button listBtn = null; // Paired devices list button
Button searchBtn = null; // Discovery new devices button
// Bluetooth
private BluetoothAdapter mBluetoothAdapter = null; // Local bluetooth adapter variable
private static final int REQUEST_ENABLE_BT = 1; // Bluetooth open intent variable
String mDeviceName = null;
String mDeviceAddress = null;
public static String EXTRA_ADDRESS = "device_address";
// XML
TextView tvDeviceName = null; // To show local bluetooth device's name
TextView tvBluetoothState = null; // To show bluetooth state
ListView lvDeviceList = null; // To list paired devices or discovered devices
// Set, List, Array Adapter
private Set<BluetoothDevice> mPairedDevicesSet = null; // Paired devices Set
private Set<BluetoothDevice> mNewDevicesSet = null; // New devices Set
ArrayAdapter mPairedDevicesAdapter = null; // Paired devices array adapter
ArrayAdapter mNewDevicesAdapter = null; // New devices array adapter
ArrayList bluetoothDeviceList = null; // Listing bluetooth devices
private ArrayList<BluetoothDevice> btDeviceList = new ArrayList<BluetoothDevice>();
// Bluetooth State Updater
private Handler mHandler; // Loop in UI
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Initializes UI elements
tvDeviceName = (TextView)findViewById(R.id.deviceName);
tvBluetoothState = (TextView)findViewById(R.id.bluetoothState);
openBtn = (Button)findViewById(R.id.openBluetooth);
closeBtn = (Button)findViewById(R.id.closeBluetooth);
listBtn = (Button)findViewById(R.id.listBluetooth);
searchBtn = (Button)findViewById(R.id.searchBluetooth);
lvDeviceList = (ListView)findViewById(R.id.deviceList);
// Bluetooth adapter
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
// Button checks
openBtn.setOnClickListener((View.OnClickListener) this);
closeBtn.setOnClickListener((View.OnClickListener) this);
listBtn.setOnClickListener((View.OnClickListener) this);
searchBtn.setOnClickListener((View.OnClickListener) this);
// To update bluetooth state text view
tvBluetoothState.setText(String.valueOf(mBluetoothAdapter.getState()));
// If the phone does not support bluetooth adapter
if (mBluetoothAdapter == null) {
tvBluetoothState.setText("Your phone has not Bluetooth Adapter");
openBtn.setEnabled(false);
closeBtn.setEnabled(false);
listBtn.setEnabled(false);
searchBtn.setEnabled(false);
}
// Updater loop
mHandler = new Handler();
mHandler.post(mUpdate);
}
// Updater Loop
private Runnable mUpdate = new Runnable() {
public void run() {
getBluetoothState();
mHandler.postDelayed(this, 500);
}
};
// Button onClick method
public void onClick(View v) {
switch (v.getId()) {
case R.id.openBluetooth:
if (!mBluetoothAdapter.isEnabled()) {
Intent bluetoothAcIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(bluetoothAcIntent, REQUEST_ENABLE_BT);
} else {
Toast.makeText(getApplicationContext(), "Bluetooth is already open", Toast.LENGTH_SHORT).show();
}
break;
case R.id.closeBluetooth:
if (mBluetoothAdapter.isEnabled()) {
mBluetoothAdapter.disable();
} else {
Toast.makeText(getApplicationContext(), "Bluetooth is already close", Toast.LENGTH_SHORT).show();
}
break;
case R.id.listBluetooth:
pairedDevicesList();
break;
case R.id.searchBluetooth:
IntentFilter filter = new IntentFilter();
filter.addAction(BluetoothDevice.ACTION_FOUND);
filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED);
filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
registerReceiver(mBroadcastReceiver, filter);
mBluetoothAdapter.startDiscovery();
break;
}
};
#Override
public void onDestroy() {
unregisterReceiver(mBroadcastReceiver);
super.onDestroy();
}
private final BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
// Whenever a remote Bluetooth device is found
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
// Get the BluetoothDevice object from the Intent
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
Toast.makeText(getApplicationContext(), device.getName() + ":" + device.getAddress(), Toast.LENGTH_LONG).show();
// lvDeviceList.setAdapter(mPairedDevicesAdapter); // Set list view elements with adapter elements
}
}
};
// Show bluetooth state on UI
public void getBluetoothState() {
tvDeviceName.setText("Device Name: " + mBluetoothAdapter.getName());
switch(mBluetoothAdapter.getState()) { // Set bluetooth state text view
case 10: // STATE_OFF
tvBluetoothState.setText("Bluetooth is closed");
bluetoothDeviceList = new ArrayList(); // Initialize global array list variable that is declared
mPairedDevicesAdapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, bluetoothDeviceList); // Get array list and use in array adapter
lvDeviceList.setAdapter(mPairedDevicesAdapter); // Set list view elements with adapter elements
break;
case 11: // STATE_TURNING_ON
tvBluetoothState.setText("Bluetooth is opening");
break;
case 12: // STATE_ON
tvBluetoothState.setText("Bluetooth is opened");
break;
case 13: // STATE_TURNING_OFF
tvBluetoothState.setText("Bluetooth is closing");
break;
}
// If bluetooth adapter -> Set buttons
if (mBluetoothAdapter.isEnabled()) {
// Enable listing button
listBtn.setEnabled(true);
searchBtn.setEnabled(true);
} else {
// Disable listing button
listBtn.setEnabled(false);
searchBtn.setEnabled(false);
}
}
// Get paired device list and adapt to list view
public void pairedDevicesList()
{
if (!mBluetoothAdapter.isEnabled()) {
Toast.makeText(getApplicationContext(), "Open the Bluetooth", Toast.LENGTH_SHORT).show();
} else {
mPairedDevicesSet = mBluetoothAdapter.getBondedDevices(); // Get paired devices
bluetoothDeviceList = new ArrayList(); // Initialize global array list variable that is declared
if (mPairedDevicesSet.size()>0) {
for (BluetoothDevice bt : mPairedDevicesSet) { // for-each loop
mDeviceName = bt.getName();
mDeviceAddress = bt.getAddress();
bluetoothDeviceList.add(mDeviceName + "\n" + mDeviceAddress); // get the device name and add to array list object
}
} else if (mPairedDevicesSet.size()<=0){
Toast.makeText(getApplicationContext(), "No paired devices", Toast.LENGTH_SHORT).show();
}
mPairedDevicesAdapter = new ArrayAdapter(this,android.R.layout.simple_list_item_1, bluetoothDeviceList); // Get array list and use in array adapter
lvDeviceList.setAdapter(mPairedDevicesAdapter); // Set list view elements with adapter elements
}
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.sphinxlike.bluetoothexample.MainActivity"
android:orientation="vertical">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Device Name"
android:id="#+id/deviceName"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_marginTop="20dp">
<Button
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="wrap_content"
android:id="#+id/openBluetooth"
android:text="B. Open"
android:textAllCaps="false"
android:layout_gravity="center"
android:gravity="center"/>
<Button
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="wrap_content"
android:id="#+id/closeBluetooth"
android:text="B. Close"
android:textAllCaps="false"
android:layout_gravity="center"
android:gravity="center"/>
<Button
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="wrap_content"
android:id="#+id/listBluetooth"
android:text="List Paired"
android:textAllCaps="false"
android:layout_gravity="center"
android:gravity="center"/>
<Button
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="wrap_content"
android:id="#+id/searchBluetooth"
android:text="Search"
android:textAllCaps="false"
android:layout_gravity="center"
android:gravity="center"/>
</LinearLayout>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:hint="Bluetooth State"
android:id="#+id/bluetoothState"
android:layout_gravity="center"
android:gravity="center"/>
<ListView
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:id="#+id/deviceList">
</ListView>
</LinearLayout>
Firstly, thanks #Tomasz Czura. I solved problem with multiple runtime permission request.
Android Developer 6.0 Changes page says:
To access the hardware identifiers of nearby external devices via Bluetooth and Wi-Fi scans, your app must now have the ACCESS_FINE_LOCATION or ACCESS_COARSE_LOCATION permissions:
So, I added permission to AndroidManifest.XML:
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
then I rearranged my activity like this:
public class MainActivity extends AppCompatActivity {
...
int ACTION_REQUEST_MULTIPLE_PERMISSION = 1; // Any number
#Override
protected void onCreate(Bundle savedInstanceState) {
...
int pCheck = this.checkSelfPermission("Manifest.permission.ACCESS_FINE_LOCATION");
pCheck += this.checkSelfPermission("Manifest.permission.ACCESS_COARSE_LOCATION");
pCheck += this.checkSelfPermission("Manifest.permission.BLUETOOTH_ADMIN");
pCheck += this.checkSelfPermission("Manifest.permission.BLUETOOTH");
if (pCheck != 0) {
this.requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION,
Manifest.permission.BLUETOOTH_ADMIN, Manifest.permission.BLUETOOTH}, ACTION_REQUEST_MULTIPLE_PERMISSION);
}
}
}
It worked.
You have to ask for Bluetooth permissions at run time in Android 6.0 -
ActivityCompat.requestPermissions(..)
This is a my .java file:
package com.example.rohitkulkarni.readingfile;
import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ListView listView= (ListView) findViewById(R.id.listView);
try{
InputStream inputreader = getAssets().open("myaddress.txt");
BufferedReader buffreader = new BufferedReader(new InputStreamReader(inputreader));
ArrayList<String> lines = new ArrayList<String>();
boolean hasNextLine =true;
while (hasNextLine){
String line = buffreader.readLine();
lines.add(line);
hasNextLine = line != null;
}
tv.setText((CharSequence) lines);
//exception here:
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getApplicationContext(),R.id.listView,lines);
listView.setAdapter(adapter);
inputreader.close();
}
catch(FileNotFoundException e){
}catch(IOException e){
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
This is my xml file:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin" tools:context=".MainActivity">
<ListView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/listView"
android:layout_alignParentTop="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" />
</RelativeLayout>
I am working with getAsset all working fine but only ArrayAdaptor is not working I tried all possible combinations but it is not working. It is working with simple string array.
String line = buffreader.readLine();
//i found that he was taking null value so checking for it
if(line != null);
lines.add(line);
hasNextLine = line != null;
//not it is working fine thanks
The middle argument is wrong, from here:
The resource ID for a layout file containing a TextView to use when instantiating views.
But you are passing an id:
new ArrayAdapter<String>(getApplicationContext(), R.id.listView, lines);
This should be a layout:
new ArrayAdapter<String>(getApplicationContext(), R.layout.???, lines);
try to use..
adapter = new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_list_item_1 , lines);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getApplicationContext(),R.id.listView,lines);
In this line you have passed a ListView id.
But the constructor expecting a Layout to inflate. So pass in a Layout.
Like this
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getApplicationContext(),android.R.layout.simple_list_item_1,lines);
EDIT
Also in this line.
tv.setText((CharSequence) lines);
tv is not defined in your activity. And if its a TextView you are setting an ArrayList to it. try tv.setText(lines.toString())
When the app first starts it immediately crashes on startup. I have narrowed down the problem to one line but not really sure what to do =/ here are the two classes in the app so far:
package com.example.bluetooth_app;
import java.util.Set;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
public class Bluetooth {
private BluetoothAdapter mBluetoothAdapter;
private Activity activity; //Activity to store main window's activity
private ArrayAdapter<String> pDevices; //Array adapter for storing already paired devices
private ArrayAdapter<String> nDevices; //Array adapter for storing newly discovered devices
private IntentFilter filter; //Filter for catching bluetooth device actions
private Button sButton; //Scan button
private ListView lvBox; //listview box
/**
* default constructor, basic initializations
*/
public Bluetooth(Activity activity) {
this.activity = activity; //Set class activity to the activity passed to it by the main activity window
pDevices = new ArrayAdapter<String>(activity, R.layout.activity_bluetooth__app);
nDevices = new ArrayAdapter<String>(activity, R.layout.activity_bluetooth__app);
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
sButton = (Button) activity.findViewById(R.id.scanButton); //sButton = scan button
sButton.setOnClickListener(new View.OnClickListener() { //Listener to check if button is pressed
public void onClick(View v) { //If button is pressed start discovering and hide button
startDiscovering();
sButton.setVisibility(4); //Make button invisible
}
});
lvBox = (ListView) activity.findViewById(R.id.deviceList); // lvBox = deviceList listview
lvBox.setAdapter(pDevices);
// Register for broadcasts when a device is discovered
filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
activity.registerReceiver(mReceiver, filter);
// Register for broadcasts when discovery has finished
filter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
activity.registerReceiver(mReceiver, filter);
}
/**
* Check if bluetooth is enabled, if not enable it
*/
public void getAdapter() {
if (!mBluetoothAdapter.isEnabled()) {
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
activity.startActivityForResult(enableBtIntent, 1);
}
}
/**
* Check if device is bluetooth compatible
*/
public boolean isCompat() {
if(mBluetoothAdapter == null) {
return false; //TODO: better error handling
} else {
return true;
}
}
/**
* Close some shit so we do not eat up resources
*/
public void destroy() {
if(mBluetoothAdapter != null) {
mBluetoothAdapter.cancelDiscovery(); //cancel discovering devices
}
activity.unregisterReceiver(mReceiver);
}
/**
* Start discovering devices with bluetooth adapter
*/
public void startDiscovering() {
if(mBluetoothAdapter.isDiscovering()) {
mBluetoothAdapter.cancelDiscovery();
}
mBluetoothAdapter.startDiscovery();
}
public void pairedDevices() {
Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
// If there are paired devices
if (pairedDevices.size() > 0) {
sButton.setText("found some");
// Loop through paired devices
for (BluetoothDevice device : pairedDevices) {
// Add the name and address to an array adapter to show in a ListView
pDevices.add(device.getName() + "\n" + device.getAddress());
}
}
}
/**
* The BroadcastReceiver that listens for discovered devices and changes the title when
* discovery is finished
*/
private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
// When discovery finds a device
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
// Get the BluetoothDevice object from the Intent
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
// If it's already paired, skip it, because it's been listed already
if (device.getBondState() != BluetoothDevice.BOND_BONDED) {
nDevices.add(device.getName() + "\n" + device.getAddress());
}
// When discovery is finished, change the Activity title
} else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
sButton.setVisibility(0); //Make button visible again
if (nDevices.getCount() == 0) {
sButton.setText("none");
//TODO: none found do something
}
}
}
};
}
and:
package com.example.bluetooth_app;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import com.example.bluetooth_app.Bluetooth;
public class Bluetooth_App extends ActionBarActivity {
private Bluetooth bT;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_bluetooth__app);
bT = new Bluetooth(this);
bT.isCompat();
bT.getAdapter();
bT.pairedDevices();
}
#Override
protected void onDestroy() {
super.onDestroy();
bT.destroy();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.bluetooth__app, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
The problem is in the first class, this line: lvBox.setAdapter(pDevices);,if I comment it out it runs just fine, if not it crashes on startup. Any help would be appreciated - thanks.
EDIT1 - no it has a listview called deviceList, XML file:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.example.bluetooth_app.Bluetooth_App" >
<Button
android:id="#+id/scanButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:layout_marginRight="28dp"
android:layout_marginTop="21dp"
android:text="Scan" />
<ListView
android:id="#+id/deviceList"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignRight="#+id/button1"
android:layout_below="#+id/button1"
android:layout_marginRight="26dp"
android:layout_marginTop="48dp" >
</ListView>
</RelativeLayout>
Note that you seem to be reusing your activity's layout file R.layout.activity_bluetooth__app when initializing your ArrayAdapters in Bluetooth_App. This is probably not what you meant to do. The resource passed to the ArrayAdapter constructors should represent the layout of a single AdapterView row, and must contain a TextView with id text1 (to use a more customized row layout, you would need to subclass ArrayAdapter and override getView).
So i have a simple app, just a menu with a few buttons, when a button is clicked you are brought to a new page. The page has a button, which when clicked, keeps changing its background image until it runs out of images (list of image names stored in strings), then you are brought back to the main menu. I can do this twice, then on the third attempt, if i click a button on the menu the app crashes. This doesnt happen on the emulator, only when i run it on my phone. I dont know why this is happening
package com.example.otapp;
import com.example.otapp.R.raw;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.util.DisplayMetrics;
import android.view.Display;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.media.MediaPlayer;
public class MainActivity extends ActionBarActivity {
public static String DPExtension;//Holds the letters dp
public String list;
public static int Screen_Height;//holds screen height
public static int Screen_Width;//holds screen width
public Intent intent;
public MediaPlayer audio;
public final static String EXTRA_MESSAGE = "com.example.otapp.MESSAGE";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//this code block is for getting the screen proportions
Display getdisplay = getWindowManager().getDefaultDisplay();
DisplayMetrics dispMetrics = new DisplayMetrics();
getdisplay.getMetrics(dispMetrics);
float densitydp = getResources().getDisplayMetrics().density;
float ScreenHeightdp = dispMetrics.heightPixels / densitydp;
float ScreenWidthdp = dispMetrics.widthPixels / densitydp;
//Below dimension value holders do not use pixel density
float ScreenHeightCheck = dispMetrics.heightPixels;
float ScreenWidthCheck = dispMetrics.heightPixels;
DPExtension = "dp";
Screen_Height = (int) ScreenHeightCheck;
Screen_Width = (int) ScreenWidthCheck;
//The printlns are so I can discern the outputs in LogCat
//System.out.println("Screen Height:" + Screen_Height);
//System.out.println("Screen Width:" + Screen_Width);
View Button1 = findViewById(R.id.Button01);
LinearLayout.LayoutParams params = (LayoutParams) Button1.getLayoutParams();
params.height = Screen_Height/3;
Button1.setLayoutParams(params);
View Button2 = findViewById(R.id.Button02);
Button2.setLayoutParams(params);
View Button3 = findViewById(R.id.Button03);
Button3.setLayoutParams(params);
View Button4 = findViewById(R.id.Button04);
Button4.setLayoutParams(params);
Button1.setOnClickListener(onClickListener);
Button2.setOnClickListener(onClickListener);
Button3.setOnClickListener(onClickListener);
Button4.setOnClickListener(onClickListener);
Button1.setBackgroundResource(getResources().getIdentifier("gettingup", "drawable", getPackageName()));
intent = new Intent(this, DisplayMessageActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
audio = MediaPlayer.create(MainActivity.this, raw.buttonsound);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
private OnClickListener onClickListener = new OnClickListener() {
#Override
public void onClick(View v) {
// play sound
audio.start();
// do different things for each different button
switch(v.getId()) {
case R.id.Button01:
list = "Get Up";
intent.putExtra(EXTRA_MESSAGE, list);
startActivity(intent);
break;
case R.id.Button02:
list = "Get Dressed";
intent.putExtra(EXTRA_MESSAGE, list);
startActivity(intent);
break;
case R.id.Button03:
list = "Get Dressed";
intent.putExtra(EXTRA_MESSAGE, list);
startActivity(intent);
break;
case R.id.Button04:
list = "Get Dressed";
intent.putExtra(EXTRA_MESSAGE, list);
startActivity(intent);
break;
}
}
};
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent" android:background="#1E90FF">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<Button
android:id="#+id/Button01"
android:layout_width="match_parent"
android:layout_height="125dp"
android:text="#string/button_send"/>
<Button
android:id="#+id/Button03"
android:layout_width="match_parent"
android:layout_height="125dp"
android:text="#string/button2_send" />
<Button
android:id="#+id/Button04"
android:layout_width="match_parent"
android:layout_height="125dp"
android:text="#string/button3_send" />
<Button
android:id="#+id/Button02"
android:layout_width="match_parent"
android:layout_height="125dp"
android:text="#string/button4_send" />
</LinearLayout>
</ScrollView>
If the source above is formatted correctly, line 99, which is where the NullPointerException is thrown, is:
audio.start();
This means that audio is null. It is declared on line 83:
audio = MediaPlayer.create(MainActivity.this, raw.buttonsound);
Most likely what's happening is that the MediaPlayer.create is unable to located the raw.buttonsound. I'd debug at this line and verify that the MediaPlayer is failing to create the audio.
Try moving the definition of the onClickListener object into the onCreate method.
You can declare it as a member variable, but you should create the object and assign it to the field in onCreate()
I have this mainactivity:
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.widget.ArrayAdapter;
import android.widget.ListView;
//Array of options --> ArrayAdapter --> ListView
//List view: {views: list_items.xml}
public class MainActivity extends FragmentActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
populateListView();
}
private void populateListView() {
//Create list of items
String[] myItems = {"Blue", "Green", "Purple", "Red"};
//Build Adapter
ArrayAdapter<String> adapter = new ArrayAdapter<String>(
this //Context for the activity
R.layout.list_items, //Layout to use (Create)
myItems); //Items to be displayed
//Configure the ListView
ListView list = (ListView) findViewById(R.id.listViewMain);
list.setAdapter(adapter);
ViewPager myViewPager = (ViewPager) findViewById(R.id.viewPager);
myViewPager.setAdapter(new MyPagerAdapter(getSupportFragmentManager()));
myViewPager.setCurrentItem(1, false);
}
private class MyPagerAdapter extends FragmentPagerAdapter {
public MyPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int pos) {
switch(pos) {
case 2: return FirstFragment.newInstance("FirstFragment, Instance 1");
case 1: return SecondFragment.newInstance("SecondFragment, Instance 1");
case 0: return ThirdFragment.newInstance("ThirdFragment, Instance 1");
default: return ThirdFragment.newInstance("ThirdFragment, Default");
}
}
#Override
public int getCount() {
return 3;
}
{}}}
I am trying to add a listview, i have created a xml file called: list_items.xml, but on this line: "R.layout.list_items," i get an error: "layout cannot be resolved or is not a field" and i also get "syntax error on token "R", delete this token". Why is that?
The list_items.xml
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
</TextView>
I believe that you misunderstood the constructor for ArrayAdapter.
What you basically need to do is change the R.layout.list_items to a single element layout, just like one you would find in android.R.
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, android.R.id.text1, values);
Here you can see that first parameter is context, second one is single item layout, third (optional) is the ID of the text view you want to target with your collection of strings and the last one is the collection.
You can use your own layouts just like you tried earlier.
If you have any questions I will be happy to answer them, and also supply some code if needed.
It look error in your xml.You can also use the simple list item if you need to display only myItems strings.
String[] myItems = {"Blue", "Green", "Purple", "Red"};
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, myItems);