Calling an activity inside another one and getting methods - android

I'm working on an android app and I have a problem that i wish you could help me solve it.
So i have an activity1 called MainActivity and activity2 called myown. In myown i have a public class that i want to call in an onItemClick() in MainActivity . Here's the code of both activities below :
MainActivity.java
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.Set;
import java.util.UUID;
public class MainActivity extends ActionBarActivity {
class Active extends myown {
}
private BluetoothAdapter btadapter;
private Set<BluetoothDevice> pairedDevices;
private SeekBar redcontrol = null;
private SeekBar greencontrol = null;
private SeekBar bluecontrol = null;
private TextView redv;
private TextView greenv;
private TextView bluev;
private ListView lv;
LinearLayout linearLayout;
Button on, off, button;
private static final UUID MY_UUID =
UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
// Insert bluetooth devices MAC address
private static String address = "00:14:02:13:08:21";
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_CANCELED) {
finish();
System.exit(10);
}
}
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btadapter = (BluetoothAdapter.getDefaultAdapter());
button = (Button)findViewById(R.id.button);
lv = (ListView)findViewById(R.id.listView1);
btadapter = BluetoothAdapter.getDefaultAdapter();
button = (Button) findViewById(R.id.button);
redv = (TextView) findViewById(R.id.redv);
greenv = (TextView) findViewById(R.id.greenv);
bluev = (TextView) findViewById(R.id.bluev);
redcontrol = (SeekBar) findViewById(R.id.seekBar);
greencontrol = (SeekBar) findViewById(R.id.seekBar2);
bluecontrol = (SeekBar) findViewById(R.id.seekBar3);
redcontrol.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
int progressChanged = 0;
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
progressChanged = progress;
redv.setText(String.valueOf(progress));
}
public void onStartTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
public void onStopTrackingTouch(SeekBar seekBar) {
//Toast.makeText(MainActivity.this, "seek bar progress:" + progressChanged,
// Toast.LENGTH_SHORT).show();
}
});
greencontrol.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
int progressChanged = 0;
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
progressChanged = progress;
greenv.setText(String.valueOf(progress));
}
public void onStartTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
public void onStopTrackingTouch(SeekBar seekBar) {
// Toast.makeText(MainActivity.this, "seek bar progress:" + progressChanged,
//Toast.LENGTH_SHORT).show();
}
});
bluecontrol.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
int progressChanged = 0;
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
progressChanged = progress;
bluev.setText(String.valueOf(progress));
}
public void onStartTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
public void onStopTrackingTouch(SeekBar seekBar) {
//Toast.makeText(MainActivity.this, "seek bar progress:" + progressChanged,
// Toast.LENGTH_SHORT).show();
}
});
linearLayout = (LinearLayout) findViewById(R.id.linearLayout);
on = (Button) findViewById(R.id.on);
off = (Button) findViewById(R.id.off);
on.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
on.setBackgroundColor(Color.parseColor("#57D3E8"));
off.setBackgroundColor(Color.parseColor("#EAEAEA"));
if (!btadapter.isEnabled()) {
Intent turnOn = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(turnOn, 0);
Toast.makeText(getApplicationContext(), "Bluetooth Turning On"
, Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getApplicationContext(), "Already On",
Toast.LENGTH_SHORT).show();
}
}
});
off.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
off.setBackgroundColor(Color.parseColor("#57D3E8"));
on.setBackgroundColor(Color.parseColor("#EAEAEA"));
if (btadapter.isEnabled()) {
btadapter.disable();
Toast.makeText(getApplicationContext(), "Bluetooth Off"
, Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getApplicationContext(), "Already Off",
Toast.LENGTH_SHORT).show();
}
}
});
}
public void list(View view) {
pairedDevices = btadapter.getBondedDevices();
ArrayList list = new ArrayList();
for(BluetoothDevice bt : pairedDevices)
list.add(bt.getName() +"\n" + bt.getAddress() );
Toast.makeText(getApplicationContext(),"Showing Paired Devices",
Toast.LENGTH_SHORT).show();
final ArrayAdapter adapter = new ArrayAdapter
(this,android.R.layout.simple_list_item_1, list);
lv.setAdapter(adapter);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
String item = ((TextView) view).getText().toString();
Toast.makeText(getBaseContext(), item, Toast.LENGTH_SHORT).show();
for (BluetoothDevice device : pairedDevices) {
if ("bluetooth".equals(device.getName())) {
Intent launchActivity2 = new Intent(MainActivity.this, myown.class);
MainActivity.this.startActivity(launchActivity2);
break;
}
if (BluetoothDevice.ACTION_ACL_CONNECTED.equals(true)) {
Toast.makeText(getBaseContext(), "Connected",Toast.LENGTH_SHORT).show();
//do nothing
}else {
Toast.makeText(getBaseContext(), "Unable to connect Light",Toast.LENGTH_SHORT).show();
}
view.setEnabled(false);
}
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
myown.java
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import java.io.IOException;
import java.util.UUID;
public class myown {
public class myOwnBroadcastReceiver extends BroadcastReceiver {
ConnectToBluetooth connectBT;
public BluetoothSocket scSocket;
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
BluetoothDevice discoveredDevice = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
connectBT = new ConnectToBluetooth(discoveredDevice);
new Thread(connectBT).start();
}
class ConnectToBluetooth implements Runnable {
private BluetoothDevice btShield;
private BluetoothSocket mySocket = null;
private UUID uuid = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
public ConnectToBluetooth(BluetoothDevice bluetoothShield) {
btShield = bluetoothShield;
try {
mySocket = btShield.createRfcommSocketToServiceRecord(uuid);
} catch (IOException createSocketException) {
}
}
#Override
public void run() {
try {
mySocket.connect();
scSocket = mySocket;
} catch (IOException connectException) {
try {
mySocket.close(); //try to close the socket
} catch (IOException closeException) {
}
return;
}
}
// Will allow you to get the socket from this class
public BluetoothSocket getSocket() {
return mySocket;
}
/* Will cancel an in-progress connection, and close the socket */
public void cancel() {
try {
mySocket.close();
} catch (IOException e) {
}
}
}
}
}

add this to your activity
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,long id) {
//add this
Intent launchActivity2 = new Intent(MainActivity.this, myown.class);
MainActivity.this.startActivity(launchActivity2);
//
String item = ((TextView) view).getText().toString();
Toast.makeText(getBaseContext(), item, Toast.LENGTH_SHORT).show();
for (BluetoothDevice device : pairedDevices) {
if ("bluetooth".equals(device.getName())) {
Intent launchActivity2 = new Intent(MainActivity.this, myown.class);
MainActivity.this.startActivity(launchActivity2);
break;
}
if (BluetoothDevice.ACTION_ACL_CONNECTED.equals(true)) {
Toast.makeText(getBaseContext(), "Connected",Toast.LENGTH_SHORT).show();
//do nothing
}else {
Toast.makeText(getBaseContext(), "Unable to connect Light",Toast.LENGTH_SHORT).show();
}
view.setEnabled(false);
}
}
});

Related

error: unreachable statement myBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

I am creating an application for working with a bluetooth device using the navigation drawer activity template, there was a problem with initializing the bluetooth adapter in a fragment, I attach my code below. When compiling the code, it gives the error
error: unreachable statement
myBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
package com.example.myt.ui.home;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProviders;
import androidx.navigation.ui.AppBarConfiguration;
import com.example.myt.R;
import java.io.IOException;
import java.util.Set;
import java.util.UUID;
public class HomeFragment extends Fragment {
private HomeViewModel homeViewModel;
private static final int REQUEST_ENABLE_BT = 1;
private Button onBtn;
private Button offBtn;
private Button listBtn;
private Button findBtn;
private TextView text;
private BluetoothAdapter myBluetoothAdapter;
private BluetoothSocket socket;
private Set<BluetoothDevice> pairedDevices;
private ListView myListView;
private ArrayAdapter<String> BTArrayAdapter;
private static final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
private AppBarConfiguration mAppBarConfiguration;
public View onCreateView(#NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
homeViewModel =
ViewModelProviders.of(this).get(HomeViewModel.class);
View root = inflater.inflate(R.layout.fragment_home, container, false);
return root;
// take an instance of BluetoothAdapter - Bluetooth radio
myBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if(myBluetoothAdapter == null) {
onBtn.setEnabled(false);
offBtn.setEnabled(false);
listBtn.setEnabled(false);
findBtn.setEnabled(false);
text.setText("Status: not supported");
Toast.makeText(getActivity().getBaseContext(),"Your device does not support Bluetooth",
Toast.LENGTH_LONG).show();
} else {
text = (TextView) root.findViewById(R.id.text);
onBtn = (Button) root.findViewById(R.id.turnOn);
onBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
on(v);
}
});
offBtn = (Button) root.findViewById(R.id.turnOff);
offBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
off(v);
}
});
listBtn = (Button) root.findViewById(R.id.paired);
listBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
list(v);
}
});
findBtn = (Button) root.findViewById(R.id.search);
findBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
find(v);
}
});
myListView = (ListView) root.findViewById(R.id.listView1);
// create the arrayAdapter that contains the BTDevices, and set it to the ListView
BTArrayAdapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1);
myListView.setAdapter(BTArrayAdapter);
}
myListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
myBluetoothAdapter.cancelDiscovery();
final String info = ((TextView) arg1).getText().toString();
//get the device address when click the device item
String address = info.substring(info.length()-17);
//connect the device when item is click
BluetoothDevice connect_device = myBluetoothAdapter.getRemoteDevice(address);
try {
socket = connect_device.createRfcommSocketToServiceRecord(MY_UUID);
socket.connect();
} catch (IOException e) {
try {
socket.close();
} catch (IOException e2) {
errorExit("Fatal Error", "In onResume() and unable to close socket during connection failure" + e2.getMessage() + ".");
}
}
}
});//************new_devices_list end
}
private void errorExit(String title, String message){
Toast.makeText(getActivity().getBaseContext(), title + " - " + message, Toast.LENGTH_LONG).show();
getActivity().finish();
}
public void on(View view){
if (!myBluetoothAdapter.isEnabled()) {
Intent turnOnIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(turnOnIntent, REQUEST_ENABLE_BT);
Toast.makeText(getActivity().getBaseContext(),"Bluetooth turned on" ,
Toast.LENGTH_LONG).show();
}
else{
Toast.makeText(getActivity().getBaseContext(),"Bluetooth is already on",
Toast.LENGTH_LONG).show();
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_ENABLE_BT) {
if (myBluetoothAdapter.isEnabled()) {
text.setText("Status: Enabled");
} else {
text.setText("Status: Disabled");
}
}
}
public void list(View view){
// get paired devices
pairedDevices = myBluetoothAdapter.getBondedDevices();
// put it's one to the adapter
for(BluetoothDevice device : pairedDevices)
BTArrayAdapter.add(device.getName()+ "\n" + device.getAddress());
Toast.makeText(getActivity().getBaseContext(),"Show Paired Devices",
Toast.LENGTH_SHORT).show();
}
final BroadcastReceiver bReceiver = new BroadcastReceiver() {
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);
// add the name and the MAC address of the object to the arrayAdapter
BTArrayAdapter.add(device.getName() + "\n" + device.getAddress());
BTArrayAdapter.notifyDataSetChanged();
}
}
};
public void find(View view) {
if (myBluetoothAdapter.isDiscovering()) {
// the button is pressed when it discovers, so cancel the discovery
myBluetoothAdapter.cancelDiscovery();
}
else {
BTArrayAdapter.clear();
myBluetoothAdapter.startDiscovery();
getActivity().registerReceiver(bReceiver, new IntentFilter(BluetoothDevice.ACTION_FOUND));
}
}
public void off(View view){
myBluetoothAdapter.disable();
text.setText("Status: Disconnected");
Toast.makeText(getActivity().getBaseContext(),"Bluetooth turned off",
Toast.LENGTH_LONG).show();
}
}
You are returning the view immediately on onCreateView, which is why the rest of the code can never be reached. The issue is here:
View root = inflater.inflate(R.layout.fragment_home, container, false);
return root;
Place return root; after:
new_devices list end

TextView is not being updated

I am facing a problem, I have implemented a code, it is showing me message in Logs correctly but it doesn't update the TextView's text. Here i have tried this version. How i can update it? I tried it using threads as well but in vain.
I have seen many solution over this StackOverflow platform but i could not find my any solution for my problem.
package com.example.yousafmoh.seizuredetection;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.provider.ContactsContract;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.bluetooth.BluetoothSocket;
import android.content.Intent;
import android.view.View;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import android.app.ProgressDialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.os.AsyncTask;
import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;
public class ledControl extends AppCompatActivity {
// Button btnOn, btnOff, btnDis;
ImageButton On, Off, Discnt, Abt;
TextView txtMessage;
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 widgets
On = (ImageButton)findViewById(R.id.on);
Off = (ImageButton)findViewById(R.id.off);
Discnt = (ImageButton)findViewById(R.id.discnt);
Abt = (ImageButton)findViewById(R.id.abt);
txtMessage = (TextView) findViewById(R.id.txtMessage);
new ConnectBT().execute(); //Call the class to connect
//myBluetoothThread();
//commands to be sent to bluetooth
On.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
turnOnLed(); //method to turn on
}
});
Off.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
turnOffLed(); //method to turn off
}
});
Discnt.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
Disconnect(); //close connection
}
});
}
private void myBluetoothThread() {
while(true)
{
if (btSocket!=null)
{
try
{
if(isBtConnected) {
InputStream inputStream = btSocket.getInputStream();
for (int i = 0; i <= inputStream.available(); i++) {
//Log.d("data", inputStream.read() + " "+"ok");
int val = inputStream.read();
if (val == 49) // seizure detected
{
this.runOnUiThread(new Runnable() {
#Override
public void run() {
txtMessage.setText("Seizure Detected!!!");
txtMessage.setTextColor(getResources().getColor(android.R.color.holo_red_dark));
Log.d("Message", " Detected");
}
});
Log.d("Message", " Detected");
} else if (val == 48) // no detection
{
this.runOnUiThread(new Runnable() {
#Override
public void run() {
txtMessage.setText("Normal Condition");
txtMessage.setTextColor(getResources().getColor(android.R.color.holo_blue_dark));
Log.d("Message", "not Detected");
}
});
Log.d("Message", "not Detected");
//, Toast.LENGTH_SHORT).show();
}
}
}
}
catch (IOException e)
{
msg("Error");
}
}
}
}
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
{
InputStream inputStream = btSocket.getInputStream();
for(int i = 0 ; i <= inputStream.available();i++)
{
Log.d("data",inputStream.read()+" ");
}
Log.d("Bytes available off",String.valueOf(inputStream.available()));
Log.d("Message off",String.valueOf(inputStream.read()));
//btSocket.getOutputStream().write("0".toString().getBytes());
}
catch (IOException e)
{
msg("Error");
}
}
}
private void turnOnLed()
{
if (btSocket!=null)
{
try
{
InputStream inputStream = btSocket.getInputStream();
Log.d("Bytes available on",String.valueOf(inputStream.available()));
Log.d("Message on",String.valueOf(inputStream.read()));
Log.d("Message on",inputStream.toString());
btSocket.getOutputStream().write("1".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();
}
public void about(View v)
{
if(v.getId() == R.id.abt)
{
Intent i = new Intent(this, AboutActivity.class);
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_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
progress.dismiss();
}
}
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;
}
if(progress!=null)
progress.dismiss();
if(isBtConnected)
{
myBluetoothThread();
}
}
}
}
Try using this if its a fragment class
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
txtMessage.setText("Normal Condition");
txtMessage.setTextColor(getResources().getColor(android.R.color.holo_blue_dark));
}
});
and this is its an activity
this.runOnUiThread(new Runnable() {
#Override
public void run() {
txtMessage.setText("Normal Condition");
txtMessage.setTextColor(getResources().getColor(android.R.color.holo_blue_dark));
}
});
Another solution u can try is.
You can use handler
Handler handler = new Handler();
handler.post(new Runnable() {
public void run() {
txtMessage.setText("Seizure Detected!!!");
txtMessage.setTextColor(getResources().getColor(android.R.color.holo_red_dark));
}
});
I have read some article somewhere that you should not update your textview directly inside the Runnable Thread. So what I did is i created a function that updates the textview then the Runnable run method calls that function. So It look like this.
public class SampleActivity extends AppCompatActivity {
TextView sample;
int counter = 0;
Handler handler;
Runnable runnable;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.sample);
sample = findViewById(R.id.sample);
handler = new Handler();
runnable = new Runnable() {
#Override
public void run() {
counter++;
updateTextView("Counter: " + counter);
handler.postDelayed(this, 1000);
}
};
handler.postDelayed(runnable, 1000);
}
public void updateTextView(String message) {
sample.setText(message);
}
But I tried it calling the sample.setText("Counter: "+counter) inside the Runnable Thread, it still works though.
Btw here is my sample.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/sample"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text="SAWSAW"
android:textColor="#000"
android:textSize="32dp" />
</LinearLayout>

Why It show me "Unfortunately, Application has stopped"

Hi every one before i start excuse me because of my grammatically wrong sentences, my native language is not English.
i wrote a code for turning on and ... Bluetooth
i put a menu at the end which has only one item exit
but when i click that it show me "Unfortunately, Application has stopped"
please please help me
the MainActivity is shown below:
package com.example.application;
import android.os.Bundle;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import java.util.Set;
import android.content.Intent;
import android.content.IntentFilter;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;
public class MainActivity extends Activity {
private static final int REQUEST_ENABLE_BT = 1;
private Button listBtn;
private Button findBtn;
private TextView text;
private BluetoothAdapter myBluetoothAdapter;
private Set<BluetoothDevice> pairedDevices;
private ListView myListView;
private ArrayAdapter<String> BTArrayAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if(myBluetoothAdapter == null) {
listBtn.setEnabled(false);
findBtn.setEnabled(false);
text.setText("Status: not supported");
Toast.makeText(getApplicationContext(),"Your device does not support Bluetooth!",
Toast.LENGTH_LONG).show();
}
//---------------------------------------------------------
else {
final ImageView iv = (ImageView) findViewById(R.id.imageView1);
final ToggleButton tb = (ToggleButton) findViewById(R.id.toggleButton1);
text = (TextView) findViewById(R.id.text);
iv.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(!(tb.isChecked())){
if (!myBluetoothAdapter.isEnabled()) {
Intent turnOnIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(turnOnIntent, REQUEST_ENABLE_BT);
Toast.makeText(getApplicationContext(),"Bluetooth turned on !" ,
Toast.LENGTH_LONG).show();
tb.toggle();
iv.setImageResource(R.drawable.on);
}
else{
Toast.makeText(getApplicationContext(),"Bluetooth is already on !",
Toast.LENGTH_LONG).show();
}
}else{
myBluetoothAdapter.disable();
text.setText("Status: Disconnected");
Toast.makeText(getApplicationContext(),"Bluetooth turned off !",
Toast.LENGTH_LONG).show();
tb.toggle();
iv.setImageResource(R.drawable.off);
}
}
});
listBtn = (Button)findViewById(R.id.paired);
listBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
list(v);
}
});
findBtn = (Button)findViewById(R.id.search);
findBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
find(v);
}
});
myListView = (ListView)findViewById(R.id.listView1);
// create the arrayAdapter that contains the BTDevices, and set it to the ListView
BTArrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1);
myListView.setAdapter(BTArrayAdapter);
}
}
//---------------------------------------------------------
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
if(requestCode == REQUEST_ENABLE_BT){
if(myBluetoothAdapter.isEnabled()) {
text.setText("Status: Enabled");
} else {
text.setText("Status: Disabled");
}
}
}
public void list(View view){
// get paired devices
pairedDevices = myBluetoothAdapter.getBondedDevices();
// put it's one to the adapter
for(BluetoothDevice device : pairedDevices)
BTArrayAdapter.add(device.getName()+ "\n" + device.getAddress());
Toast.makeText(getApplicationContext(),"Show Paired Devices",
Toast.LENGTH_SHORT).show();
}
final BroadcastReceiver bReceiver = new BroadcastReceiver() {
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);
// add the name and the MAC address of the object to the arrayAdapter
BTArrayAdapter.add(device.getName() + "\n" + device.getAddress());
BTArrayAdapter.notifyDataSetChanged();
}
}
};
public void find(View view) {
if (myBluetoothAdapter.isDiscovering()) {
// the button is pressed when it discovers, so cancel the discovery
myBluetoothAdapter.cancelDiscovery();
}
else {
BTArrayAdapter.clear();
myBluetoothAdapter.startDiscovery();
registerReceiver(bReceiver, new IntentFilter(BluetoothDevice.ACTION_FOUND));
}
}
#Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
unregisterReceiver(bReceiver);
}
// menu is shown here
//---------------------------------------------------
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.mainmenu,menu );
return true;
}
//--------------------------------------------------
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if(item.getItemId()==R.id.item1)
{
this.finish();
}
return super.onOptionsItemSelected(item);
}
//-------------------------------------------------
}
what should i do in menu code to ...
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.mainmenu,menu );
return true;
}
//--------------------------------------------------
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if(item.getItemId()==R.id.item1)
{
======>>>>>>>>>> this.finish(); <<<<<<===========
}
return super.onOptionsItemSelected(item);
}
//-------------------------------------------------

How to pair bluetooth device and connect with it?

I would like to pair a Bluetooth device using Eclipse. But I don't really know to fix this code. Here is the code below:
package com.example.bluetoothtest;
import android.os.Bundle;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import java.util.Set;
import android.content.Intent;
import android.content.IntentFilter;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
private static final int REQUEST_ENABLE_BT = 1;
private Button myonbutton;
private Button myoffbutton;
private Button mylistbutton;
private Button myfindbutton;
private TextView mytext;
private BluetoothAdapter myBluetoothAdapter;
private Set<BluetoothDevice> mypairedDevices;
private ListView myListView;
private ArrayAdapter<String> myArrayAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if(myBluetoothAdapter == null) {
myonbutton.setEnabled(false);
myoffbutton.setEnabled(false);
mylistbutton.setEnabled(false);
myfindbutton.setEnabled(false);
mytext.setText("Status: Your device is not supported");
Toast.makeText(getApplicationContext(),"Your device does not support Bluetooth",
Toast.LENGTH_LONG).show();
} else {
mytext = (TextView) findViewById(R.id.text);
myonbutton = (Button)findViewById(R.id.turnOn);
myonbutton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
on(v);
}
});
myoffbutton = (Button)findViewById(R.id.turnOff);
myoffbutton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
off(v);
}
});
mylistbutton = (Button)findViewById(R.id.paired);
mylistbutton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
list(v);
}
});
myfindbutton = (Button)findViewById(R.id.search);
myfindbutton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
find(v);
}
});
myListView = (ListView)findViewById(R.id.listView1);
myArrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1);
myListView.setAdapter(myArrayAdapter);
}
}
public void on(View view){
if (!myBluetoothAdapter.isEnabled()) {
Intent turnOnIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(turnOnIntent, REQUEST_ENABLE_BT);
Toast.makeText(getApplicationContext(),"Bluetooth turned on" ,
Toast.LENGTH_LONG).show();
}
else{
Toast.makeText(getApplicationContext(),"Bluetooth is already on",
Toast.LENGTH_LONG).show();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
if(requestCode == REQUEST_ENABLE_BT){
if(myBluetoothAdapter.isEnabled()) {
mytext.setText("Status: Enabled");
} else {
mytext.setText("Status: Disabled");
}
}
}
public void list(View view){
mypairedDevices = myBluetoothAdapter.getBondedDevices();
for(BluetoothDevice device : mypairedDevices)
myArrayAdapter.add(device.getName()+ "\n" + device.getAddress());
Toast.makeText(getApplicationContext(),"Show Paired Devices",
Toast.LENGTH_SHORT).show();
}
final BroadcastReceiver bReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
myArrayAdapter.add(device.getName() + "\n" + device.getAddress());
myArrayAdapter.notifyDataSetChanged();
}
}
};
public void find(View view) {
if (myBluetoothAdapter.isDiscovering()) {
myBluetoothAdapter.cancelDiscovery();
}
else {
myArrayAdapter.clear();
myBluetoothAdapter.startDiscovery();
registerReceiver(bReceiver, new IntentFilter(BluetoothDevice.ACTION_FOUND));
}
}
public void off(View view){
myBluetoothAdapter.disable();
mytext.setText("Status: Disconnected");
Toast.makeText(getApplicationContext(),"Bluetooth turned off",
Toast.LENGTH_LONG).show();
}
#Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
unregisterReceiver(bReceiver);
}
}
Here android developers on bluetooth
and some nice example: example from javacodegeeks

androids listView's setOnItemClickListener works only if do not update data set. after update it stops

I have creating ListView of wifi channels and it works fine, onResume() calls the AsyncTask which updates the list, but after update the click listener stops working, even if I try to set it again. Here is my code:
package co.uk.company.application.ui.wifi;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import co.uk.company.application.R;
import co.uk.company.application.injected.ApplicationGlobalState;
import co.uk.company.application.ui.companyActivity;
import co.uk.company.application.ui.dialog.YesNoAlertDialogCreator;
import co.uk.company.sources.telnet.WifiTelnetClass;
import com.google.inject.Inject;
import java.util.ArrayList;
import java.util.Vector;
import roboguice.inject.InjectView;
public class WifiAPsActivity extends companyActivity{
#Inject private ApplicationGlobalState applicationGlobalState;
#InjectView(R.id.wifi_networks_list) private ListView listView1;
private WifiChannels wifiChannels;
private WifiChannel channelSelected;
private ArrayList<WifiChannel> data;
private ArrayList<WifiChannel> dataold;
private Vector <WifiChannel> vect;
private WifiAPsAdapter adapter;
private RealtimeUpdateScreen realtimeUpdateScreen;
private AdapterView.OnItemClickListener listener;
#Override
public void onCreate(Bundle savedInstanceState){
Log.w("","onCreate(...) start");
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_wifi_networks);
listener= new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, final int arg2, long arg3) {
arg0.showContextMenuForChild(arg1);
//if(adapter.getItem(arg2).toString().endsWith(".txt"))
Toast.makeText(getApplicationContext(),getString(R.string.loading), Toast.LENGTH_LONG).show();
}
};
dataold= new ArrayList<WifiChannel>();
data =new ArrayList<WifiChannel>();
wifiChannels=applicationGlobalState.wifiCurrentChannels;
if (wifiChannels != null)
for(WifiChannel chn : wifiChannels.getChannels()){
dataold.add(chn);
data.add(chn);
}
wifiChannels=applicationGlobalState.wifiCurrentChannels5GHz;
if (wifiChannels != null)
for(WifiChannel chn : wifiChannels.getChannels()){
dataold.add(chn);
data.add(chn);
}
adapter = new WifiAPsAdapter(this,R.layout.wifi_networks_item_row, data);
listView1.setAdapter(adapter);
listView1.setItemsCanFocus(false);
registerForContextMenu(listView1);
listView1.setOnItemClickListener(listener);
Log.w("","onCreate(...) finish");
}
#Override
public void onResume(){
Log.w("","onResume() start");
super.onResume();
//realtimeUpdateScreen = new RealtimeUpdateScreen();
//realtimeUpdateScreen.execute(new Object());
Log.w("","onResume() finish");
}
#Override
public void onPause(){
super.onPause();
realtimeUpdateScreen.cancel(true);
realtimeUpdateScreen = null;
Log.w("","onPause() finish");
}
#Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo){
Log.w("","onCreateContextMenu");
AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) menuInfo;
// menu.setHeaderTitle(fileNames.get(info.position));
channelSelected = data.get(info.position);
menu.add(Menu.NONE, 0, 0, "Connect");
menu.add(Menu.NONE, 1, 1, "Disconnect");
menu.add(Menu.NONE, 2, 2, "Do nothing");
}
#Override
public boolean onContextItemSelected(MenuItem item) {
Log.w("","onContextItemSelected");
int menuItemIndex = item.getItemId();
//final AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
switch (menuItemIndex){
case 0:
final AlertDialog.Builder alert = new AlertDialog.Builder(this);
LayoutInflater li = LayoutInflater.from(this);
View promptsView = li.inflate(R.layout.dialog_with_text_fields, null);
alert.setView(promptsView);
final TextView SSIDfield = (TextView) promptsView.findViewById(R.id.ssid_field);
final EditText input2 = (EditText) promptsView.findViewById(R.id.password_field);
SSIDfield.setText(channelSelected.getName());
// final Button okButton = (Button) promptsView.findViewById(R.id.wifi_button_yes);
// final Button cancelButton =(Button)promptsView.findViewById(R.id.wifi_button_no);
// okButton.setOnClickListener(new View.OnClickListener() {
// #Override
// public void onClick(View arg0) {
//
// }
// });
//
// cancelButton.setOnClickListener(new View.OnClickListener() {
// #Override
// public void onClick(View arg0) {
// // alert.
// }
// });
alert.setPositiveButton("OKK",
new DialogInterface.OnClickListener(){
public void onClick(DialogInterface dialog,int id) {
String SSID = channelSelected.getName();
String PASSWORD = input2.getText().toString().trim();
if(WifiTelnetClass.getInstance().connect(SSID, PASSWORD))
Toast.makeText(getApplicationContext(), SSID+" Connected", Toast.LENGTH_SHORT).show();
else Toast.makeText(getApplicationContext(), "Not Connected!", Toast.LENGTH_SHORT).show();
}
});
alert.setNegativeButton("CCancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
dialog.cancel();
}
});
alert.show();
break;
case 1:
YesNoAlertDialogCreator.create(this, "Are You Sure?",
getString(R.string.sure_delete_result), new DialogInterface.OnClickListener(){
public void onClick(DialogInterface dialog, int whichButton) {
Toast.makeText(getApplicationContext(),"Disconnecting!!", Toast.LENGTH_LONG).show();
if(WifiTelnetClass.getInstance().disconnect())
Toast.makeText(getApplicationContext(), " Disconnected", Toast.LENGTH_SHORT).show();
else Toast.makeText(getApplicationContext(), "Not Disconnected!", Toast.LENGTH_SHORT).show();
}
}).show();
Toast.makeText(getApplicationContext(),"Nothing!!!", Toast.LENGTH_LONG).show();
break;
case 2:
YesNoAlertDialogCreator.create(this, "Password please!!!",
getString(R.string.sure_delete_result), new DialogInterface.OnClickListener(){
public void onClick(DialogInterface dialog, int whichButton) {
}
}).show();
Toast.makeText(getApplicationContext(),"It!", Toast.LENGTH_LONG).show();
break;
}
return true;
}
class RealtimeUpdateScreen extends AsyncTask{
#Override
protected void onPreExecute(){
try{
Thread.sleep(50L);
}catch(Exception e){}
}
#Override
protected Object doInBackground(Object... arg0){
while(!isCancelled()){
try{
if(wifiChannels!=applicationGlobalState.wifiCurrentChannels)
publishProgress(arg0);
try{Thread.sleep(50);}catch(Exception e){}
}catch(Exception e){Log.e("","",e);}
}
return null;
}
protected void onProgressUpdate(Object...objects ){
try{
for(WifiChannel chn_ : dataold){
adapter.remove(chn_);
}
}catch(Exception e){Log.e("","",e);}
try{
dataold = new ArrayList<WifiChannel>();
//adapter.notifyDataSetChanged();
vect=applicationGlobalState.wifiCurrentChannels5GHz.getChannels();
for(WifiChannel chn : vect){
dataold.add(chn);
adapter.add(chn);
}
vect=applicationGlobalState.wifiCurrentChannels.getChannels();
for(WifiChannel chn : vect){
dataold.add(chn);
adapter.add(chn);
}
adapter.notifyDataSetChanged();
}catch(Exception e){Log.e("","",e);}
}
}
}
what can it be?
thank You!
Found it: I have to setOnItemClickListener after each notifyDataSetChanged again.

Categories

Resources