Unable to complete R.java file - java

My DeviceList.java code is as below :-
import com.technomentis.led.R;
public class DeviceList extends ActionBarActivity
{
//widgets
Button btnPaired;
ListView devicelist;
//Bluetooth
private BluetoothAdapter myBluetooth = null;
private Set<BluetoothDevice> pairedDevices;
public static String EXTRA_ADDRESS = "device_address";
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_device_list);
//Calling widgets
btnPaired = (Button)findViewById(R.id.btnOn);
devicelist = (ListView)findViewById(R.id.listView);
//if the device has bluetooth
myBluetooth = BluetoothAdapter.getDefaultAdapter();
if(myBluetooth == null)
{
//Show a mensag. that the device has no bluetooth adapter
Toast.makeText(getApplicationContext(), "Bluetooth Device Not Available", Toast.LENGTH_LONG).show();
//finish apk
finish();
}
else if(!myBluetooth.isEnabled())
{
//Ask to the user turn the bluetooth on
Intent turnBTon = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(turnBTon,1);
}
btnPaired.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
pairedDevicesList();
}
});
}
private void pairedDevicesList()
{
pairedDevices = myBluetooth.getBondedDevices();
ArrayList list = new ArrayList();
if (pairedDevices.size()>0)
{
for(BluetoothDevice bt : pairedDevices)
{
list.add(bt.getName() + "\n" + bt.getAddress()); //Get the device's name and the address
}
}
else
{
Toast.makeText(getApplicationContext(), "No Paired Bluetooth Devices Found.", Toast.LENGTH_LONG).show();
}
final ArrayAdapter adapter = new ArrayAdapter(this,android.R.layout.simple_list_item_1, list);
devicelist.setAdapter(adapter);
devicelist.setOnItemClickListener(myListClickListener); //Method called when the device from the list is clicked
}
private AdapterView.OnItemClickListener myListClickListener = new AdapterView.OnItemClickListener()
{
public void onItemClick (AdapterView<?> av, View v, int arg2, long arg3)
{
// Get the device MAC address, the last 17 chars in the View
String info = ((TextView) v).getText().toString();
String address = info.substring(info.length() - 17);
// Make an intent to start next activity.
Intent i = new Intent(DeviceList.this, ledControl.class);
//Change the activity.
i.putExtra(EXTRA_ADDRESS, address); //this will be received at ledControl (class) Activity
startActivity(i);
}
};
#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_device_list, 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);
}
}
My ledcontrol.java is as follow
package com.technomentis.led;
public class ledControl extends ActionBarActivity {
Button btnOn, btnOff, btnDis;
SeekBar brightness;
TextView lumn;
String address = null;
private ProgressDialog progress;
BluetoothAdapter myBluetooth = null;
BluetoothSocket btSocket = null;
private boolean isBtConnected = false;
//SPP UUID. Look for it
static final UUID myUUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
Intent newint = getIntent();
address = newint.getStringExtra(DeviceList.EXTRA_ADDRESS); //receive the address of the bluetooth device
//view of the ledControl
setContentView(R.layout.activity_led_control);
//call the widgtes
btnOn = (Button)findViewById(R.id.button2);
btnOff = (Button)findViewById(R.id.button3);
btnDis = (Button)findViewById(R.id.button4);
brightness = (SeekBar)findViewById(R.id.seekBar);
lumn = (TextView)findViewById(R.id.lumn);
new ConnectBT().execute(); //Call the class to connect
//commands to be sent to bluetooth
btnOn.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
turnOnLed(); //method to turn on
}
});
btnOff.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
turnOffLed(); //method to turn off
}
});
btnDis.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
Disconnect(); //close connection
}
});
brightness.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
if (fromUser==true)
{
lumn.setText(String.valueOf(progress));
try
{
btSocket.getOutputStream().write(String.valueOf(progress).getBytes());
}
catch (IOException e)
{
}
}
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
}
private void Disconnect()
{
if (btSocket!=null) //If the btSocket is busy
{
try
{
btSocket.close(); //close connection
}
catch (IOException e)
{ msg("Error");}
}
finish(); //return to the first layout
}
private void turnOffLed()
{
if (btSocket!=null)
{
try
{
btSocket.getOutputStream().write("TF".toString().getBytes());
}
catch (IOException e)
{
msg("Error");
}
}
}
private void turnOnLed()
{
if (btSocket!=null)
{
try
{
btSocket.getOutputStream().write("TO".toString().getBytes());
}
catch (IOException e)
{
msg("Error");
}
}
}
// fast way to call Toast
private void msg(String s)
{
Toast.makeText(getApplicationContext(),s,Toast.LENGTH_LONG).show();
}
#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_led_control, 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);
}
private class ConnectBT extends AsyncTask<Void, Void, Void> // UI thread
{
private boolean ConnectSuccess = true; //if it's here, it's almost connected
#Override
protected void onPreExecute()
{
progress = ProgressDialog.show(ledControl.this, "Connecting...", "Please wait!!!"); //show a progress dialog
}
#Override
protected Void doInBackground(Void... devices) //while the progress dialog is shown, the connection is done in background
{
try
{
if (btSocket == null || !isBtConnected)
{
myBluetooth = BluetoothAdapter.getDefaultAdapter();//get the mobile bluetooth device
BluetoothDevice dispositivo = myBluetooth.getRemoteDevice(address);//connects to the device's address and checks if it's available
btSocket = dispositivo.createInsecureRfcommSocketToServiceRecord(myUUID);//create a RFCOMM (SPP) connection
BluetoothAdapter.getDefaultAdapter().cancelDiscovery();
btSocket.connect();//start connection
}
}
catch (IOException e)
{
ConnectSuccess = false;//if the try failed, you can check the exception here
}
return null;
}
#Override
protected void onPostExecute(Void result) //after the doInBackground, it checks if everything went fine
{
super.onPostExecute(result);
if (!ConnectSuccess)
{
msg("Connection Failed. Is it a SPP Bluetooth? Try again.");
finish();
}
else
{
msg("Connected.");
isBtConnected = true;
}
progress.dismiss();
}
}
}
My ongoing R.java is as below
package com.technomentis.led;
public final class R {
public static final class attr {
}
public static final class mipmap {
public static final int cxemnet_logo=0x7f020000;
public static final int ic_action_search=0x7f020001;
public static final int ic_launcher=0x7f020002;
}
public static final class id {
public static final int btnOff=0x7f060000;
public static final int btnOn=0x7f060001;
public static final int listView=0x7f060002;
}
public static final class layout {
public static final int activity_device_list=0x7f030000;
}
public static final class string {
public static final int app_name=0x7f040000;
public static final int btn_OFF=0x7f040003;
public static final int btn_ON=0x7f040002;
public static final int title_activity_main=0x7f040001;
}
public static final class style {
public static final int AppTheme=0x7f050000;
}
}
Can anybody help me in creating complete R.java file. I am unable to complete it.
Btw I am new to android studio.

I encounter this issue periodically. Build -> Rebuild Project and Build -> Clean Project always take care of the problem for me.

Thanks everyone,
Done with this problem. Simply create new project and copy pasted all files.
Rebuild done all the work.
Now need help in
Error:(53, 43) error: cannot find symbol variable lumn

Related

Calling a method upon completion of progress bar

I need to make an app that sends an SMS message after showing a progress bar in increments of 10. I have the action bar set up and I think I should use AsyncTask? The user is inputing number and message into the main activity, and that's where I have the SendSMS method set up, not sure how to make this work so that it forwards to AsyncTask and calls on that method there.
public class MainActivity extends AppCompatActivity {
private int MY_PERMISSIONS_REQUEST_SMS_RECEIVE = 10;
private static final String SMS_SENT = "SMS_SENT";
private static final String SMS_DELIVERED= "SMS_DELIVERED";
private EditText etPoruka;
private EditText etBroj;
private ProgressDialog progressDialog;
private Context context = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initWidgets();
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.RECEIVE_SMS},
MY_PERMISSIONS_REQUEST_SMS_RECEIVE);
}
private void initWidgets() {
etPoruka = findViewById(R.id.etPoruka);
etBroj = findViewById(R.id.etBroj);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_send:
MyAsyncTask<Void, Void, Void> updateTask = new MyAsyncTask<Void, Void, Void>(context);
updateTask.execute();
break;
case R.id.action_sent:
Toast.makeText(this, R.string.add_test, Toast.LENGTH_LONG).show();
// BROADCAST RECEIVER ??
break;
case R.id.action_received:
Toast.makeText(this, R.string.add_test, Toast.LENGTH_LONG).show();
//BROADCAST RECEIVER ??
//BOUND SERVICE
break;
case R.id.action_exit:
final AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle("Close app");
builder.setMessage("Are you sure?");
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
finish();
}
});
builder.setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.dismiss();
}
});
AlertDialog dialog = builder.create();
dialog.show();
}
return true;
}
public void sendSMS() {
try{
SmsManager smgr = SmsManager.getDefault();
smgr.sendTextMessage(etBroj.getText().toString(),null,etPoruka.getText().toString(),null,null);
Toast.makeText(MainActivity.this, "SMS sent successfully", Toast.LENGTH_SHORT).show();
}
catch (Exception e){
Toast.makeText(MainActivity.this, "Error", Toast.LENGTH_SHORT).show();
}
}
}
ASYNCTASK
public class MyAsyncTask extends
AsyncTask {
private final String DIALOG_MESSAGE = "Sending message";
private ProgressDialog mDialog = null;
private void setDialog(Context context) {
this.mDialog = new ProgressDialog(context);
this.mDialog.setMessage(DIALOG_MESSAGE);
this.mDialog.setCancelable(false);
}
public MyAsyncTask(Context context) {
this.setDialog(context);
}
#Override
protected void onPreExecute() {
this.mDialog.show();
}
#Override
protected Result doInBackground(Params... arg0) {
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Result result) {
if (this.mDialog.isShowing()) {
this.mDialog.dismiss();
}
} }
You can create an Interface and implement in your MainActivity.
For More Details Please check these answers:
how do i send data back from onPostExecute in an AsyncTask?
How to pass data from an asynchronous task to an activity that called it?

Android Bluetooth sends msg when breakpoint added, but not if program doesn't pause

I have the following code that talks to a C# program on a computer. When I add a breakpoint before the outputStream.write(bytes) code, it works fine when I restart the program. If I just let the program run, it doesn't send the message. I am thinking it has something to do with timing, but I have tried everything I can think of to make sure the BT is connected before it sends the message.
The message is being sent on a button click.
Here are the 2 classes:
MainActivity.java
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
public static BluetoothAdapter mBluetoothAdapter;
public static BluetoothDevice mBluetoothDevice;
private String scannedContents;
private Button scanBtn;
private TextView formatTxt, contentTxt;
public static int mState = 0;
private ConnectThread btThread;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
//Bottom Right Buttons
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(this);
//Setup BT
if (savedInstanceState == null) {
mBluetoothAdapter = ((BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE)).getAdapter();
if (mBluetoothAdapter != null) {
if (mBluetoothAdapter.isEnabled()) {
Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
if (pairedDevices.size() > 0) {
for (BluetoothDevice device : pairedDevices) {
if (device.getAddress().equalsIgnoreCase("00:1a:7d:da:71:11")) {
mBluetoothDevice = device;
ConnectThread btThread = new ConnectThread(mBluetoothDevice);
btThread.run();
}
}
} else
showErrorText(R.string.bt_not_paired);
} else {
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, Constants.REQUEST_ENABLE_BT);
}
} else {
showErrorText(R.string.bt_not_supported);
}
}
//Scanning Button Code
scanBtn = (Button) findViewById(R.id.scan_button);
formatTxt = (TextView) findViewById(R.id.scan_format);
contentTxt = (TextView) findViewById(R.id.scan_content);
scanBtn.setOnClickListener(this);
}
public void onClick(View v) {
//respond to clicks
if (v.getId() == R.id.scan_button) {
//scan
IntentIntegrator scanIntegrator = new IntentIntegrator(this);
scanIntegrator.initiateScan();
} else if (v.getId() == R.id.fab) {
btThread.write(scannedContents.getBytes());
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case Constants.REQUEST_ENABLE_BT:
if (resultCode == RESULT_OK) {
//TODO
} else {
Toast.makeText(this, R.string.bt_not_enabled_leaving, Toast.LENGTH_SHORT).show();
finish();
}
case Constants.REQUEST_SCANNED_DATA:
//Scanner Code
IntentResult scanningResult = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
if (scanningResult.getContents() != null) {
//we have a result
String scanContent = scanningResult.getContents();
String scanFormat = scanningResult.getFormatName();
//TODO Do something with data
this.scannedContents = scanContent;
formatTxt.setText("FORMAT: " + scanFormat);
contentTxt.setText("CONTENT: " + scanContent);
} else {
Toast toast = Toast.makeText(getApplicationContext(), "No scan data received!", Toast.LENGTH_SHORT);
toast.show();
}
default:
super.onActivityResult(requestCode, resultCode, data);
}
}
#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);
}
private void showErrorText(int messageId) {
TextView view = (TextView) findViewById(R.id.error_textview);
view.setText(getString(messageId));
}
public final Handler mHandler = new Handler() {
#Override
public void handleMessage(Message msg) {
//TODO
}
};
}
ConnectThread.java
public class ConnectThread extends Thread {
final BluetoothSocket mmSocket;
public ConnectThread(BluetoothDevice device) {
// Use a temporary object that is later assigned to mmSocket
// because mmSocket is final.
BluetoothSocket tmp = null;
try {
// Get a BluetoothSocket to connect with the given BluetoothDevice.
// MY_UUID is the app's UUID string, also used in the server code.
UUID uuid = UUID.fromString("F814E012-48FE-44F4-AF94-9D9C4CF7495A");
tmp = device.createRfcommSocketToServiceRecord(uuid);
} catch (IOException e) {
Log.e(TAG, "Socket's create() method failed", e);
}
mmSocket = tmp;
}
public void run() {
// Cancel discovery because it otherwise slows down the connection.
MainActivity.mBluetoothAdapter.cancelDiscovery();
try {
// Connect to the remote device through the socket. This call blocks
// until it succeeds or throws an exception.
mmSocket.connect();
} catch (IOException connectException) {
// Unable to connect; close the socket and return.
try {
mmSocket.close();
} catch (IOException closeException) {
Log.e(TAG, "Could not close the client socket", closeException);
}
return;
}
// The connection attempt succeeded. Perform work associated with
// the connection in a separate thread.
MainActivity.mState = 1;
}
public void write(byte[] bytes) {
try {
OutputStream outputStream = mmSocket.getOutputStream();
outputStream.write(bytes);
} catch (IOException e) {
e.printStackTrace();
}
}
// Closes the client socket and causes the thread to finish.
public void cancel() {
try {
mmSocket.close();
} catch (IOException e) {
Log.e(TAG, "Could not close the client socket", e);
}
}
}
Ok. This was me not understanding threads. The issue was I was using thread.run() instead of thread.start().

Android Bluetooth connection error

I'm developing a bluetooth app to control an Arduino board, but now I made some mistakes: when I try to make a connection from my phone, it displays an AlertDialog (it is OK) and a lot of Toasts (they're called from onSensorChanged).
The BT module connected to the board is OK (tested with other apps), so the problem is Java: I can't make a connection to my BT module. Unfortunately, Android Studio doesn't give me any logcat or errors.
This is my code:
/* imports... */
public class MainActivity extends AppCompatActivity implements SensorEventListener {
/* Bluetooth */
private static final int REQUEST_ENABLE_BT = 1;
private String selectedDevice = "";
static final UUID defaultUUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"); //This SPP UUID should work for most devices.
//private boolean isConnected = false;
BluetoothAdapter bluetoothAdapter;
BluetoothSocket bluetoothSocket;
/* Is in full screen = ? */
private boolean FullScreenState = true;
/* Views */
private SeekBar steeringWheel;
private SeekBar forwardsSpeed;
private SeekBar backwardsSpeed;
private Toolbar toolbar;
/* Dialogs */
AlertDialog.Builder errorDialog;
AlertDialog.Builder listDialog;
ProgressDialog progressDialog;
/* Accelerometer managers */
Sensor accelerometer;
SensorManager sensorManager;
float Y = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
(...)
/* Views */
steeringWheel = (SeekBar) findViewById(R.id.Steering_wheel);
forwardsSpeed = (SeekBar) findViewById(R.id.Forwards_speed);
backwardsSpeed = (SeekBar) findViewById(R.id.Backwards_speed);
/* listDialogs */
listDialog = new AlertDialog.Builder(this);
listDialog.setCancelable(true);
listDialog.setTitle(R.string.app_name);
//listDialog.setMessage("Select a device:");
listDialog.setIcon(R.drawable.launcher_icon);
//listDialog.setView(devicesListView);
listDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
/* errorDialog */
errorDialog = new AlertDialog.Builder(this);
errorDialog.setCancelable(false);
errorDialog.setTitle(R.string.app_name);
errorDialog.setIcon(R.drawable.error_material);
errorDialog.setPositiveButton("I got it", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
/* Set the full screen and keep the screen always on... */
/* Accelerometer initializer... */
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
...
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
...
if (id == R.id.toolbar_connect) {
initializeBT();
return true;
} else if (id == R.id.toolbar_settings) {
/* Settings activity. Coming soon. */
return true;
} else if (id == R.id.toolbar_disconnect) {
if (bluetoothSocket != null) {
try {
bluetoothSocket.close();
} catch (IOException e) {
errorDialog.setMessage("Disconnection error!");
errorDialog.show();
}
}
return true;
}
...
}
#Override
public void onSensorChanged(SensorEvent event) {
/* Get the axes */
Y = event.values[1];
/* Set the steering wheel position */
steeringWheel.setProgress((int)Y + 10);
send(String.valueOf(steeringWheel.getProgress()));
}
#Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
...
}
private class connect extends AsyncTask<Void, Void, Void> {
private boolean connectionSuccess = false;
#Override
protected void onPreExecute() {
progressDialog = ProgressDialog.show(MainActivity.this, "Connecting...", "Creating bluetooth connection");
}
#Override
protected Void doInBackground(Void... devices) {
try {
if (bluetoothSocket == null) {
//if ((bluetoothSocket == null) || (!isConnected)) {
bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
BluetoothDevice arduino = bluetoothAdapter.getRemoteDevice(selectedDevice);
bluetoothSocket = arduino.createInsecureRfcommSocketToServiceRecord(defaultUUID);
BluetoothAdapter.getDefaultAdapter().cancelDiscovery();
bluetoothSocket.connect();
connectionSuccess = true;
}
} catch (IOException e) {
connectionSuccess = false;
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
if (!connectionSuccess) {
errorDialog.setMessage("Connection error!");
errorDialog.show();
bluetoothSocket = null;
} else {
Toast.makeText(getApplicationContext(), "Successfully connected", Toast.LENGTH_LONG).show();
//isConnected = true;
}
progressDialog.dismiss();
}
}
void initializeBT() {
/* Check for Bluetooth support */
bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (bluetoothAdapter == null) {
errorDialog.setMessage("Unfortunately, Bluetooth connection isn't supported on your device.");
errorDialog.show();
} else if (!bluetoothAdapter.isEnabled()) {
/* Bluetooth disables -> enable it */
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
} else {
devicesPrompt();
}
}
void devicesPrompt() {
//final ArrayList<String> devicesList = new ArrayList()<String>;
Set<BluetoothDevice> pairedDevices;
final ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1);
pairedDevices = bluetoothAdapter.getBondedDevices();
if (pairedDevices.size() > 0) {
for(BluetoothDevice bluetoothDevice : pairedDevices) {
/* Get the device's name and the address */
//devicesList.add(bt.getName() + "\n" + bt.getAddress());
adapter.add(bluetoothDevice.getName() + "\n" + bluetoothDevice.getAddress());
}
} else {
Toast.makeText(getApplicationContext(), "No paired Bluetooth devices found!", Toast.LENGTH_LONG).show();
}
listDialog.setAdapter(adapter, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//Log.d("RoverBluetooth!!", String.valueOf(which));
//;
String info = adapter.getItem(which);
selectedDevice = info.substring(info.length() - 17);
new connect().execute();
dialog.dismiss();
}
});
listDialog.show();
}
public void send(String message) {
message = message + "/r";
if (bluetoothSocket != null) {
try {
bluetoothSocket.getOutputStream().write(message.getBytes());
} catch (IOException e) {
Toast.makeText(getApplicationContext(), "Error during sending", Toast.LENGTH_SHORT).show();
Log.d("RoverBluetooth errors", e.toString());
}
}
}
public void buttonsActions(View view) {
int viewId = view.getId();
if (viewId == R.id.Forwards_button) { //ON
send(String.valueOf(forwardsSpeed.getProgress() + 1000));
} else if (viewId == R.id.Stop_button) { //OFF
send("21");
} else if (viewId == R.id.Backwards_button) { //Backwards
send(String.valueOf(backwardsSpeed.getProgress() + 1500));
} else if (viewId == R.id.Light_ON) { //Light ON
send("22");
} else if (viewId == R.id.Light_OFF) { //Light OFF
send("23");
}
}
}
I already wrote a class to make a bluetooth connection between Android and Arduino. I suppose you're using a HC-06 (or -05 ?). My code is on github:
https://github.com/omaflak/Bluetooth-Android
I also wrote a tutorial on my blog, you may want to take a look at it:
https://causeyourestuck.io/2015/12/14/communication-between-android-and-hc-06-module/
Good luck!

How to transfer data via Bluetooth from two different activities?

I tried to send data from my app to my Arduino board to make the led light.
The problem is that if I send from my main activity it works but if I send it from a second activity (HolopickerColor), it doesn't work and I don't get any errors.
Thanks for your anwsers.
MainActivity :
public class MainActivity extends AppCompatActivity{
private Button mPairedBtn;
Button on, find;
public BluetoothAdapter BA;
private ProgressDialog mProgressDlg;
// public ConnectedThread mConnectedThread;
private ArrayList<BluetoothDevice> mDeviceList = new ArrayList<BluetoothDevice>();
private DrawerLayout mDrawerLayout;
private BluetoothSocket btSocket = null;
private OutputStream outStream = null;
Button btnOn, btnOff;
// SPP UUID service
private static final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
// MAC-address of Bluetooth module (you must edit this line)
private static String address ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
on = (Button) findViewById(R.id.btn_enable);
find = (Button) findViewById(R.id.btn_scan);
mPairedBtn = (Button) findViewById(R.id.btn_view_paired);
BA = BluetoothAdapter.getDefaultAdapter();
mProgressDlg = new ProgressDialog(this);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
ActionBar actionBar = getSupportActionBar();
actionBar.setHomeAsUpIndicator(R.drawable.ic_menu);
actionBar.setDisplayHomeAsUpEnabled(true);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
NavigationView navigationView = (NavigationView) findViewById(R.id.navigation_view);
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
menuItem.setChecked(true);
mDrawerLayout.closeDrawers();
Toast.makeText(MainActivity.this, menuItem.getTitle(), Toast.LENGTH_LONG).show();
switch (menuItem.getItemId()) {
case R.id.nav_item_colorlight:
Intent color = new Intent(MainActivity.this, HolopickerColor.class);
// color.putExtra("color", ConnectedThread.getInstance());
startActivity(color);
break;
case R.id.nav_item_effectlight:
Intent light = new Intent(MainActivity.this, LightEffect.class);
startActivity(light);
break;
case R.id.nav_item_music:
Intent music = new Intent(MainActivity.this, Music.class);
startActivity(music);
break;
case R.id.nav_item_about:
Intent about = new Intent(MainActivity.this, About.class);
startActivity(about);
break;
}
return true;
}
});
mProgressDlg.setMessage("Scanning...");
mProgressDlg.setCancelable(false);
mProgressDlg.setButton(DialogInterface.BUTTON_NEGATIVE, "Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
BA.cancelDiscovery();
}
});
if (BA == null) {
showUnsupported();
} else {
mPairedBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Set<BluetoothDevice> pairedDevices = BA.getBondedDevices();
if (pairedDevices == null || pairedDevices.size() == 0) {
showToast("No Paired Devices Found");
} else {
ArrayList<BluetoothDevice> list = new ArrayList<BluetoothDevice>();
list.addAll(pairedDevices);
Intent intent = new Intent(MainActivity.this, DeviceListActivity.class);
intent.putParcelableArrayListExtra("device.list", list);
startActivity(intent);
}
}
});
find.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
BA.startDiscovery();
}
});
on.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (BA.isEnabled()) {
BA.disable();
showDisabled();
try
{
btSocket.close();
} catch (IOException e2)
{
//insert code to deal with this
}
} else {
Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(intent, 1000);
}
}
});
if (BA.isEnabled()) {
showEnabled();
} else {
showDisabled();
}
}
IntentFilter filter = new IntentFilter();
filter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);
filter.addAction(BluetoothDevice.ACTION_FOUND);
filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED);
filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
registerReceiver(mReceiver, filter);
btnOn = (Button) findViewById(R.id.btnOn);
btnOff = (Button) findViewById(R.id.btnOff);
// Set up onClick listeners for buttons to send 1 or 0 to turn on/off LED
btnOff.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
/* r = 255;
g = 15;
b = 50;
mConnectedThread.write("r"+Integer.toString(r)+"\n"); // Send "0" via Bluetooth
mConnectedThread.write("g"+Integer.toString(g)+"\n");
mConnectedThread.write("b"+Integer.toString(b)+"\n");*/
ConnectedThread.getInstance().write("1");
Toast.makeText(getBaseContext(), "Turn off LED", Toast.LENGTH_SHORT).show();
}
});
btnOn.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
//cathode nen 1 la off, o la on
ConnectedThread.getInstance().write("0"); // Send "1" via Bluetooth //gui nhan ne
Toast.makeText(getBaseContext(), "Turn on LED", Toast.LENGTH_SHORT).show();
}
});
//Get MAC address from DeviceListActivity via intent
// Intent intent = getIntent();
//Get the MAC address from the DeviceListActivty via EXTRA
//address = intent.getStringExtra(DeviceListActivity.EXTRA_DEVICE_ADDRESS);
// MAC-address of Bluetooth module (you must edit this line)
address = "30:14:10:09:07:86";
//create device and set the MAC address
BluetoothDevice device = BA.getRemoteDevice(address);
try {
btSocket = createBluetoothSocket(device);
} catch (IOException e) {
Toast.makeText(getBaseContext(), "Socket creation failed", Toast.LENGTH_LONG).show();
}
// Establish the Bluetooth socket connection.
try
{
btSocket.connect();
} catch (IOException e) {
try
{
btSocket.close();
} catch (IOException e2)
{
//insert code to deal with this
}
}
ConnectedThread.createInstance(btSocket);
ConnectedThread.getInstance().start();
//I send a character when resuming.beginning transmission to check device is connected
//If it is not an exception will be thrown in the write method and finish() will be called
}
private BluetoothSocket createBluetoothSocket(BluetoothDevice device) throws IOException {
return device.createRfcommSocketToServiceRecord(MY_UUID);
//creates secure outgoing connecetion with BT device using UUID
}
#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();
switch (id) {
case android.R.id.home:
mDrawerLayout.openDrawer(GravityCompat.START);
return true;
}
return super.onOptionsItemSelected(item);
}
public void onPause() {
if (BA != null) {
if (BA.isDiscovering()) {
BA.cancelDiscovery();
}
}
try
{
//Don't leave Bluetooth sockets open when leaving activity
btSocket.close();
} catch (IOException e2) {
//insert code to deal with this
}
super.onPause();
}
#Override
public void onDestroy() {
unregisterReceiver(mReceiver);
super.onDestroy();
}
private void showEnabled() {
Toast.makeText(getApplicationContext(), "on", Toast.LENGTH_LONG).show();
on.setText("Disable");
on.setEnabled(true);
mPairedBtn.setEnabled(true);
find.setEnabled(true);
}
private void showDisabled() {
Toast.makeText(getApplicationContext(), "off", Toast.LENGTH_LONG).show();
on.setText("Enable");
on.setEnabled(true);
mPairedBtn.setEnabled(false);
find.setEnabled(false);
}
private void showUnsupported() {
Toast.makeText(getApplicationContext(), "Bluetooth is unsupported by this device", Toast.LENGTH_LONG).show();
on.setText("Enable");
on.setEnabled(false);
mPairedBtn.setEnabled(false);
find.setEnabled(false);
}
private void showToast(String message) {
Toast.makeText(getApplicationContext(), message, Toast.LENGTH_SHORT).show();
}
private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (BluetoothAdapter.ACTION_STATE_CHANGED.equals(action)) {
final int state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, BluetoothAdapter.ERROR);
if (state == BluetoothAdapter.STATE_ON) {
showToast("Enabled");
showEnabled();
}
} else if (BluetoothAdapter.ACTION_DISCOVERY_STARTED.equals(action)) {
mDeviceList = new ArrayList<BluetoothDevice>();
mProgressDlg.show();
} else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
mProgressDlg.dismiss();
Intent newIntent = new Intent(MainActivity.this, DeviceListActivity.class);
newIntent.putParcelableArrayListExtra("device.list", mDeviceList);
startActivity(newIntent);
} else if (BluetoothDevice.ACTION_FOUND.equals(action)) {
BluetoothDevice device = (BluetoothDevice) intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
mDeviceList.add(device);
showToast("Found device " + device.getName());
}
}
};
Second activity :
public class HolopickerColor extends AppCompatActivity implements ColorPicker.OnColorChangedListener {
private TextView text;
com.larswerkman.holocolorpicker.ColorPicker picker;
SVBar svBar ;
Button test;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_holopicker_color);
picker = (ColorPicker) findViewById(R.id.picker);
svBar = (SVBar) findViewById(R.id.svbar);
text = (TextView) findViewById(R.id.color1);
picker.addSVBar(svBar);
picker.getColor();
picker.setOnColorChangedListener(this);
picker.setShowOldCenterColor(false);// Tat mau cu
test = (Button)findViewById(R.id.test);
test.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
ConnectedThread.getInstance().write("r255\n");
Toast.makeText(getBaseContext(),"yes",Toast.LENGTH_LONG).show();
}
});
//ConnectedThread.getInstance().start();
}
public void onColorChanged(int color) {
// TODO Auto-generated method stub
text.setTextColor(color);//hien mau len chu
if (ConnectedThread.getInstance() != null) {
int r = (color >> 16) & 0xFF;//xuat kieu mau ra thanh chu
int g = (color >> 8) & 0xFF;
int b = (color >> 0) & 0xFF;
// mTcpClient.sendMessage(Integer.toHexString(picker.getColor()));
ConnectedThread.getInstance().write("r255");//gui ko nhan ne
Here is the ConnectedThread :
class ConnectedThread extends Thread {
private final BluetoothSocket mmSocket;
private final OutputStream mmOutStream; // cai nay e can implement Serializable nua
private static ConnectedThread instance = null;
private ConnectedThread(BluetoothSocket socket) {
mmSocket = socket;
OutputStream tmpOut = null;
// Get the input and output streams, using temp objects because
// member streams are final
try {
tmpOut = socket.getOutputStream();
} catch (IOException e) { }
mmOutStream = tmpOut;
}
public static void createInstance(BluetoothSocket socket) {
if (instance == null) {
instance = new ConnectedThread(socket);
}
}
public static ConnectedThread getInstance() {
return instance;
}
//write method
public void write(String input) {
byte[] msgBuffer = input.getBytes(); //converts entered String into bytes
try {
mmOutStream.write(msgBuffer); //write bytes over BT connection via outstream
} catch (IOException e) {
cancel();
}
}
/* Call this from the main activity to shutdown the connection */
public void cancel() {
try {
mmSocket.close();
} catch (IOException e) { }
}
}
The problem is that you are creating your ConnectedThread singleton instance using a BluetoothSocket, and then you close that same socket in the onPause method of your activity. So basically, after onPause has been called, the ConnectedThread instance cannot send anything anymore. Instead of this you should have ConnectedThread manage the socket, i.e. keep a reference to it and then close it when you no longer need it or have detected a problem.
By the way, each time you call write on ConnectedThread after the socket is closed, your cancel method is called. You would have been able to easily detect the problem if you were not silencing exceptions in this method. This is why you should never have an empty catch block.

Cannot Make Login Work in Smack and Openfire

I have been following this tutorial I found on GitHub to try and make a connection to an OpenFire server. I have used spark before and am now trying to use Smack api to create a simple android app to use on the go. I have followed a few tutorials and eventually stumbled upon this from Github:
https://github.com/axcl/SMACK-API-Android-Demo
The problem is when I click the login button, I do not see my presence online in the OpenFire administrator panel.
Here is the code:
Myxmpp.java
public class Myxmpp {
private static final String DOMAIN = "192.168.2.14";
private static final String HOST = "192.168.2.14";
private static final int PORT = 5222;
private String userName ="";
private String passWord = "";
AbstractXMPPConnection connection ;
ChatManager chatmanager ;
Chat newChat;
XMPPConnectionListener connectionListener = new XMPPConnectionListener();
private boolean connected;
private boolean isToasted;
private boolean chat_created;
private boolean loggedin;
//Initialize
public void init(String userId,String pwd ) {
Log.i("XMPP", "Initializing!");
this.userName = userId;
this.passWord = pwd;
XMPPTCPConnectionConfiguration.Builder configBuilder = XMPPTCPConnectionConfiguration.builder();
configBuilder.setUsernameAndPassword(userName, passWord);
configBuilder.setSecurityMode(ConnectionConfiguration.SecurityMode.disabled);
configBuilder.setResource("Android");
configBuilder.setServiceName(DOMAIN);
configBuilder.setHost(HOST);
configBuilder.setPort(PORT);
//configBuilder.setDebuggerEnabled(true);
connection = new XMPPTCPConnection(configBuilder.build());
connection.addConnectionListener(connectionListener);
}
// Disconnect Function
public void disconnectConnection(){
new Thread(new Runnable() {
#Override
public void run() {
connection.disconnect();
}
}).start();
}
public void connectConnection()
{
AsyncTask<Void, Void, Boolean> connectionThread = new AsyncTask<Void, Void, Boolean>() {
#Override
protected Boolean doInBackground(Void... arg0) {
// Create a connection
try {
connection.connect();
login();
connected = true;
} catch (IOException e) {
} catch (SmackException e) {
} catch (XMPPException e) {
}
return null;
}
};
connectionThread.execute();
}
public void sendMsg() {
if (connection.isConnected()== true) {
// Assume we've created an XMPPConnection name "connection"._
chatmanager = ChatManager.getInstanceFor(connection);
newChat = chatmanager.createChat("concurer#nimbuzz.com");
try {
newChat.sendMessage("Howdy!");
} catch (SmackException.NotConnectedException e) {
e.printStackTrace();
}
}
}
public void login() {
try {
connection.login(userName, passWord);
//Log.i("LOGIN", "Yey! We're connected to the Xmpp server!");
} catch (XMPPException | SmackException | IOException e) {
e.printStackTrace();
} catch (Exception e) {
}
}
//Connection Listener to check connection state
public class XMPPConnectionListener implements ConnectionListener {
#Override
public void connected(final XMPPConnection connection) {
Log.d("xmpp", "Connected!");
connected = true;
if (!connection.isAuthenticated()) {
login();
}
}
#Override
public void connectionClosed() {
if (isToasted)
new Handler(Looper.getMainLooper()).post(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
}
});
Log.d("xmpp", "ConnectionCLosed!");
connected = false;
chat_created = false;
loggedin = false;
}
#Override
public void connectionClosedOnError(Exception arg0) {
if (isToasted)
new Handler(Looper.getMainLooper()).post(new Runnable() {
#Override
public void run() {
}
});
Log.d("xmpp", "ConnectionClosedOn Error!");
connected = false;
chat_created = false;
loggedin = false;
}
#Override
public void reconnectingIn(int arg0) {
Log.d("xmpp", "Reconnectingin " + arg0);
loggedin = false;
}
#Override
public void reconnectionFailed(Exception arg0) {
if (isToasted)
new Handler(Looper.getMainLooper()).post(new Runnable() {
#Override
public void run() {
}
});
Log.d("xmpp", "ReconnectionFailed!");
connected = false;
chat_created = false;
loggedin = false;
}
#Override
public void reconnectionSuccessful() {
if (isToasted)
new Handler(Looper.getMainLooper()).post(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
}
});
Log.d("xmpp", "ReconnectionSuccessful");
connected = true;
chat_created = false;
loggedin = false;
}
#Override
public void authenticated(XMPPConnection arg0, boolean arg1) {
Log.d("xmpp", "Authenticated!");
loggedin = true;
chat_created = false;
new Thread(new Runnable() {
#Override
public void run() {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}).start();
if (isToasted)
new Handler(Looper.getMainLooper()).post(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
}
});
}
}
}
ConnectXmpp.java
public class ConnectXmpp extends Service {
private String userName;
private String passWord;
private Myxmpp xmpp = new Myxmpp();
public ConnectXmpp() {
}
#Override
public void onCreate() {
super.onCreate();
}
#Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
return new Localbinder<ConnectXmpp>(this);
}
#Override
public int onStartCommand(Intent intent, int flags, int startId)
{
if(intent != null){
userName = intent.getStringExtra("user");
passWord = intent.getStringExtra("pwd");
xmpp.init(userName, passWord);
xmpp.connectConnection();
}
return 0;
}
#Override
public void onDestroy() {
xmpp.disconnectConnection();
super.onDestroy();
}
Main Activity
public class MainActivity extends AppCompatActivity {
private static final String TAG = "MainActivity";
private ConnectXmpp mService;
private View view;
private boolean mBounded;
private final ServiceConnection mConnection = new ServiceConnection() {
#SuppressWarnings("unchecked")
#Override
public void onServiceConnected(final ComponentName name,
final IBinder service) {
mService = ((Localbinder<ConnectXmpp>) service).getService();
mBounded = true;
Log.d(TAG, "onServiceConnected");
}
#Override
public void onServiceDisconnected(final ComponentName name) {
mService = null;
mBounded = false;
Log.d(TAG, "onServiceDisconnected");
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#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);
}
//Click Handler for Login Button
public void onClickLoginBtn(View view)
{
try {
EditText userId = (EditText) findViewById(R.id.username);
EditText userPwd = (EditText) findViewById(R.id.password);
String userName = userId.getText().toString();
String passWord = userPwd.getText().toString();
Intent intent = new Intent(getBaseContext(),ConnectXmpp.class );
intent.putExtra("user",userName);
intent.putExtra("pwd",passWord);
startService(intent);
//mService.connectConnection(intent);
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
I know this is a lot but I am really confused with this whole XMPP stuff. Any help on how to connect an already registered user would be greatly appreciated. Thanks
hi i have checked your code and are you sure your domain name and host name is same. According to your issue, you are not able to login with xmpp using app.
Try this github example.This made my me.So if you got any issue i can help you.
https://github.com/saveendhiman/XMPPSample_Studio
Thank you hope this will help you.

Categories