I want to make a TCP client that can sent and receive data for server. I use Hercules(TCP/UDP test program) as Server. My code can send string "Submit" to Server. I try to make my code can receive data from Hercules but it not work.what I have to do for edit it?
This is my MainActivity code
public class MainActivity extends Activity {
// Used to reference UI elements of main.xml
private TextView text,serverResponse;
private EditText ipBox;
private EditText portBox;
private ToggleButton connect;
private Button send;
private static final String TAG = "CClient";
private String ipAddress;
private Socket client;
private DataOutputStream outToServer;
private DataInputStream inFromServer;
private boolean connected = false;
private final int START = 0xffffff;
private final int msgBoxHint = START;
private final int appendText = START + 1;
Toast mytoast , savetoast;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
Log.d(TAG, "Here 1");
ipAddress = getLocalIpAddress();
Log.d(TAG, "Get local IP="+ ipAddress);
text = (TextView) findViewById(R.id.text);
ipBox = (EditText) findViewById(R.id.ipBox);
serverResponse = (TextView) findViewById(R.id.response);
portBox = (EditText) findViewById(R.id.portBox);
send = (Button) findViewById(R.id.send);
send.setOnClickListener(buttonsendOnClickListener);
connect = (ToggleButton) findViewById(R.id.connect);
connect.setOnClickListener(buttonConnectOnClickListener);
Button buttonExit = (Button) findViewById(R.id.btnExit);
buttonExit.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Log.d(TAG, "Exit");
Log.d(TAG, "Disconnect" );
if(client != null)
{
try {
client.close();
} catch (IOException e) {
Log.d(TAG, "Disconnect"+e.toString() );
}
}
finish();
}
});
}
OnClickListener buttonConnectOnClickListener = new OnClickListener() {
/** Manages all button clicks from the screen */
#TargetApi(Build.VERSION_CODES.HONEYCOMB) #Override
public void onClick(View arg0) {
switch(arg0.getId())
{
case R.id.connect:
if(connect.isChecked())
{
Log.d(TAG, "Connect" );
EditText edIP = (EditText) findViewById(R.id.ipBox);
String ed_textIP = edIP.getText().toString().trim();
if(ed_textIP.isEmpty() || ed_textIP.length() == 0 || ed_textIP.equals("") || ed_textIP == null )
{
Toast.makeText(MainActivity.this, "IP Address or PORT is incorrect", Toast.LENGTH_SHORT).show();
Log.d(TAG, "IP Address or PORT is incorrect");
}
setValues(R.id.connect,true);
setValues(R.id.send,true);
setValues(R.id.ipBox,false);
String tMsg = welcomeMsg.toString();
MyClientTask myClientTask = new MyClientTask(ipBox
.getText().toString(), Integer.parseInt(portBox
.getText().toString()),
tMsg);
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB)
myClientTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
else
myClientTask.execute();
}
else
{ /*Toast.makeText(this, ipBox.getText(), Toast.LENGTH_LONG).show();*/
Log.d(TAG, "Disconnect" );
if(client != null)
{
try {
client.close();
} catch (IOException e) {
Log.d(TAG, "Disconnect"+e.toString() );
}
setText(R.id.text,"Press the connect button to start the client");
setText(msgBoxHint,"");
setValues(R.id.connect,false);
setValues(R.id.ipBox,true);
setValues(R.id.send,false);
}
else
{
setValues(R.id.connect,false);
}
}
break;
}
}
};
public class MyClientTask extends AsyncTask<Void, Void, Void> {
String dstAddress;
int dstPort;
String response = "";
String msgToServer;
MyClientTask(String addr, int port, String msgTo) {
dstAddress = addr;
dstPort = port;
msgToServer = msgTo;
}
protected Void doInBackground(Void... Arg0) {
Log.d(TAG, "InBackground");
Socket socket = null;
DataOutputStream outToServer = null;
DataInputStream inFromServer = null;
try {
client = new Socket(dstAddress, dstPort);
outToServer = new DataOutputStream(client.getOutputStream());
inFromServer = new DataInputStream(new BufferedInputStream(client.getInputStream())); // Input stream <- from server
}catch (UnknownHostException e) {
// TODO Auto-generated catch block
Log.d(TAG, "InBackground 1");
e.printStackTrace();
response = "UnknownHostException: " + e.toString();
MainActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
mytoast = Toast.makeText(MainActivity.this, "Error UnknownHostException",
Toast.LENGTH_SHORT);
mytoast.show();
setValues(R.id.send,false);
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
mytoast.cancel();
}
}, 500);
}
});
} catch (IOException e) {
Log.d(TAG, "InBackground 2");
// TODO Auto-generated catch block
e.printStackTrace();
response = "IOException: " + e.toString();
MainActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
mytoast = Toast.makeText(MainActivity.this, "Error IOException",
Toast.LENGTH_SHORT);
mytoast.show();
setValues(R.id.connect,false);
setValues(R.id.send,false);
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
mytoast.cancel();
}
}, 500);
}
});
}finally {
Log.d(TAG, "InBackground 3");
if (socket != null) {
try {
socket.close();
Log.d(TAG, "InBackground 3.11");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Log.d(TAG, "InBackground 3.12");
}
}
Log.d(TAG, "InBackground 3.1");
}
Log.d(TAG, "InBackground 4");
return null;
}
#Override
protected void onPostExecute(Void result) {
serverResponse.setText(response);
super.onPostExecute(result);
}
}
OnClickListener buttonsendOnClickListener = new OnClickListener() {
/** Manages all button clicks from the screen */
#TargetApi(Build.VERSION_CODES.HONEYCOMB) #Override
public void onClick(View arg0) {
switch(arg0.getId())
{
case R.id.send:
Log.d(TAG, "Sent" );
String sentence = "Submit";
String recieve = "";
serverResponse = (TextView) findViewById(R.id.response);
try {
outToServer = new DataOutputStream(client.getOutputStream());
inFromServer = new DataInputStream(new BufferedInputStream(client.getInputStream()));
Log.d(TAG, "Sent 1-1" );
if(sentence != null){
outToServer.writeUTF(sentence);
outToServer.flush();
}
/*
*
*
*
*
*
*/
Log.d(TAG, "Sent 1-2"+ recieve);
} catch (IOException e) {
setValues(R.id.ipBox,true);
setValues(R.id.connect,false);
setValues(R.id.send,false);
}
break;
}
}
};
private String getLocalIpAddress() {
Log.d(TAG, "Here 2");
WifiManager wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
Log.d(TAG, "Here 3");
WifiInfo info = wifi.getConnectionInfo();
Log.d(TAG, "Here 4");
return Formatter.formatIpAddress(info.getIpAddress());
}
private void setText(int view, String content)
{
switch(view)
{
case R.id.ipBox: ipBox.setText(content); break;
case R.id.text: text.setText(content+"\n\n"); break;
case appendText: text.append(content+"\n\n"); break;
}
}
private void setValues(int view, boolean value)
{
switch(view)
{
case R.id.ipBox: ipBox.setEnabled(value); break;
case R.id.send: send.setEnabled(value); break;
case R.id.connect: connect.setChecked(value); break;
}
}
}
I think, I have to add receive code in buttonsendOnClickListener near /*****/.
Do not work with sockets in main (gui) thread. Use AsyncTask!
Android fails if work with sockets in main (gui) thread.
Example:
new AsyncTask<Void, Void, Void>() {
#Override
protected void onPreExecute() {
super.onPreExecute();
// do in main thread before
}
#Override
protected Void doInBackground(Void... v) {
// do in thread, use sockets
return null;
}
#Override
protected void onPostExecute(Void v) {
super.onPostExecute(integer);
// do in main thread after
}
}.execute();
Learn about AsyncTask advance.
Related
Here is the error - java.lang.NullPointerException: Attempt to invoke virtual method 'void com.example.wdchat.MainActivity$SendReceive.write(byte[])' on a null object reference.
I have included my mainactivity class code and wifibroadcastreceover class code as well. The code is actually from wifip2p tutorial on youtube made by sarthi technology
Here is my MainActivity class.
public class MainActivity extends AppCompatActivity {
Toolbar toolbar;
AppCompatEditText editText;
ImageView wifi_on_off_iv, wifi_descovery_iv, send_btn_iv, save_ic_iv, brd_msg_iv;
TextView username, sentMessage, connectionStatus, tallytext, tallyno;
WifiManager wifiManager;
WifiP2pManager p2pManager;
WifiP2pManager.Channel mchannel;
String messageText;
LinearLayout nestedLinearlayout;
ListView listView;
ServerClass serverClass;
ClientClass clientClass;
SendReceive sendReceive;
BroadcastReceiver broadcastReceiver;
IntentFilter intentFilter;
List<WifiP2pDevice> peers = new ArrayList<WifiP2pDevice>();
String[] devicenameArray;
WifiP2pDevice[] wifiP2pDeviceArray;
static final int MESSAGE_READ = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initializeViews();
exqListener();
}
Handler handler = new Handler(new Handler.Callback() {
#Override
public boolean handleMessage(Message message) {
switch (message.what){
case MESSAGE_READ:
byte[] readBuff = (byte[]) message.obj;
String temMsg = new String(readBuff, 0, message.arg1);
sentMessage.setText(temMsg);
break;
}
return true;
}
});
private void exqListener() {
wifi_on_off_iv.setOnClickListener(view -> {
if (wifiManager.isWifiEnabled()) {
wifi_on_off_iv.setImageResource(R.drawable.ic_wifi_on);
wifiManager.setWifiEnabled(false);
wifi_on_off_iv.setImageResource(R.drawable.ic_wifi_off);
} else {
wifiManager.setWifiEnabled(true);
wifi_on_off_iv.setImageResource(R.drawable.ic_wifi_on);
}
});
wifi_descovery_iv.setOnClickListener(view -> p2pManager.discoverPeers(mchannel, new WifiP2pManager.ActionListener() {
#Override
public void onSuccess() {
connectionStatus.setText(R.string.discovery_on);
wifi_descovery_iv.setImageResource(R.drawable.ic_wifi_discover);
connectionStatus.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.purple_500));
}
#Override
public void onFailure(int i) {
connectionStatus.setText(R.string.discovery_off);
wifi_descovery_iv.setImageResource(R.drawable.ic_wifi_discovery_off);
connectionStatus.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.red));
}
}));
p2pManager.createGroup(mchannel, new WifiP2pManager.ActionListener() {
#Override
public void onSuccess() {
}
#Override
public void onFailure(int i) {
}
});
listView.setOnItemClickListener((adapterView, view, i, l) -> {
final WifiP2pDevice device = wifiP2pDeviceArray[i];
WifiP2pConfig config = new WifiP2pConfig();
config.deviceAddress = device.deviceAddress;
p2pManager.connect(mchannel, config, new WifiP2pManager.ActionListener() {
#Override
public void onSuccess() {
Toast.makeText(MainActivity.this, "Connected to " + device.deviceName, Toast.LENGTH_SHORT).show();
}
#Override
public void onFailure(int i) {
Toast.makeText(MainActivity.this, "Not connected", Toast.LENGTH_SHORT).show();
}
});
});
send_btn_iv.setOnClickListener(view -> {
// sendReceive = new SendReceive(sock);
messageText = Objects.requireNonNull(editText.getText()).toString().trim();
sendReceive.write(messageText.getBytes());
Toast.makeText(MainActivity.this, "you sent"+ messageText, Toast.LENGTH_SHORT).show();
});
}
private void initializeViews() {
intentFilter = new IntentFilter();
intentFilter.addAction(WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION);
intentFilter.addAction(WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION);
intentFilter.addAction(WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION);
intentFilter.addAction(WifiP2pManager.WIFI_P2P_THIS_DEVICE_CHANGED_ACTION);
toolbar = findViewById(R.id.mdboard_toolbar);
wifi_on_off_iv = findViewById(R.id.md_wifi);
wifi_descovery_iv = findViewById(R.id.md_wifi_descov);
brd_msg_iv = findViewById(R.id.md_broadcast_mesaage);
editText = findViewById(R.id.md_editext);
sentMessage = findViewById(R.id.md_tally_message);
send_btn_iv = findViewById(R.id.md_send_btn);
save_ic_iv = findViewById(R.id.md_save);
username = findViewById(R.id.md_profile_username);
connectionStatus = findViewById(R.id.md_status_text);
listView = findViewById(R.id.md_list_view);
tallytext = findViewById(R.id.md_tally_text);
tallyno = findViewById(R.id.md_tally_no);
nestedLinearlayout = findViewById(R.id.nestedscroll_linearlayout);
setSupportActionBar(toolbar);
getSupportActionBar().setTitle(R.string.dashboard);
ViewCompat.setNestedScrollingEnabled(nestedLinearlayout, true);
wifiManager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
p2pManager = (WifiP2pManager) getSystemService(Context.WIFI_P2P_SERVICE);
mchannel = p2pManager.initialize(this, getMainLooper(), null);
broadcastReceiver = new WifiDirectBroadcastReceiver(p2pManager, mchannel, this);
}
WifiP2pManager.PeerListListener peerListListener = new WifiP2pManager.PeerListListener() {
#Override
public void onPeersAvailable(WifiP2pDeviceList wifiP2pDeviceList) {
if (!wifiP2pDeviceList.getDeviceList().equals(peers)) {
peers.clear();
peers.addAll(wifiP2pDeviceList.getDeviceList());
devicenameArray = new String[wifiP2pDeviceList.getDeviceList().size()];
wifiP2pDeviceArray = new WifiP2pDevice[wifiP2pDeviceList.getDeviceList().size()];
int index = 0;
for (WifiP2pDevice device: wifiP2pDeviceList.getDeviceList()) {
devicenameArray[index] = device.deviceName;
wifiP2pDeviceArray[index] = device;
index++;
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_list_item_1, devicenameArray);
listView.setAdapter(adapter);
}
if (peers.size()==0) {
Toast.makeText(MainActivity.this, "No device found", Toast.LENGTH_SHORT).show();
return;
}
}
};
WifiP2pManager.ConnectionInfoListener connectionInfoListener = new WifiP2pManager.ConnectionInfoListener(){
#Override
public void onConnectionInfoAvailable(WifiP2pInfo wifiP2pInfo) {
final InetAddress groupOwner = wifiP2pInfo.groupOwnerAddress;
if (wifiP2pInfo.groupFormed && wifiP2pInfo.isGroupOwner){
connectionStatus.setText("Host");
serverClass = new ServerClass();
serverClass.start();
} else if (wifiP2pInfo.groupFormed){
connectionStatus.setText("CLient");
clientClass = new ClientClass(groupOwner);
clientClass.start();
}
}
};
#Override
protected void onStart(){
super.onStart();
exqListener();
}
#Override
protected void onResume() {
super.onResume();
registerReceiver(broadcastReceiver, intentFilter);
}
#Override
protected void onPause() {
super.onPause();
unregisterReceiver(broadcastReceiver);
}
public class ServerClass extends Thread {
Socket socket;
ServerSocket serverSocket;
#Override
public void run() {
try {
serverSocket = new ServerSocket(8888);
socket = serverSocket.accept();
sendReceive = new SendReceive(socket);
sendReceive.start();
} catch (IOException e) {
e.printStackTrace();
}
}
}
private class SendReceive extends Thread{
private Socket socket;
private InputStream inputStream;
private OutputStream outputStream;
public SendReceive(Socket skt) {
socket = skt;
try {
inputStream = socket.getInputStream();
outputStream = socket.getOutputStream();
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void run() {
byte[] buffer = new byte[1024];
int bytes;
while (socket!=null) {
try {
bytes = inputStream.read(buffer);
if (bytes>0){
handler.obtainMessage(MESSAGE_READ, bytes, -1, buffer).sendToTarget();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
public void write(byte[] bytes){
outputStream = new OutputStream() {
#Override
public void write(int i) throws IOException {
outputStream.write(bytes);
}
};
}
}
public class ClientClass extends Thread {
Socket socket;
String hostAdd;
public ClientClass(InetAddress hostAddress) {
hostAdd = hostAddress.getHostAddress();
socket = new Socket();
}
#Override
public void run() {
try {
socket.connect(new InetSocketAddress(hostAdd, 8888),500);
sendReceive = new SendReceive(socket);
sendReceive.start();
} catch (IOException e) {
e.printStackTrace();
}
}
}
// requestGroupInfo
private void requestGroupInfo() {
p2pManager.requestGroupInfo(mchannel, new WifiP2pManager.GroupInfoListener() {
#Override
public void onGroupInfoAvailable(WifiP2pGroup wifiP2pGroup) {
connectionStatus.setText("request group info");
}
});
}
}
Here is my wifibroadcastReceiver class
public class WifiDirectBroadcastReceiver extends BroadcastReceiver {
WifiP2pManager wifiP2pManager;
WifiP2pManager.Channel channel;
MainActivity mainActivity;
public WifiDirectBroadcastReceiver(WifiP2pManager mManager, WifiP2pManager.Channel mchannel, MainActivity mActivity) {
this.wifiP2pManager = mManager;
this.channel = mchannel;
this.mainActivity = mActivity;
}
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION.equals(action)){
int state = intent.getIntExtra(WifiP2pManager.EXTRA_WIFI_STATE, -1);
if (state == WifiP2pManager.WIFI_P2P_STATE_ENABLED) {
mainActivity. wifi_on_off_iv.setImageResource(R.drawable.ic_wifi_on);
Toast.makeText(context, "Wifi is on", Toast.LENGTH_SHORT).show();
} else {
mainActivity.wifi_on_off_iv.setImageResource(R.drawable.ic_wifi_off);
Toast.makeText(context, "Wifi is off", Toast.LENGTH_SHORT).show();
}
} else if(WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION.equals(action)) {
// do somethimg
if (wifiP2pManager != null) {
wifiP2pManager.requestPeers(channel, mainActivity.peerListListener);
}
} else if(WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION.equals(action)) {
// do somthing
if (wifiP2pManager == null) {
return;
}
NetworkInfo networkInfo = intent.getParcelableExtra(WifiP2pManager.EXTRA_NETWORK_INFO);
if (networkInfo.isConnected()) {
wifiP2pManager.requestConnectionInfo(channel, mainActivity.connectionInfoListener);
mainActivity.connectionStatus.setText("[Device connected]");
mainActivity.wifi_descovery_iv.setImageResource(R.drawable.ic_wifi_discover);
} else {
mainActivity.connectionStatus.setText("[Device disconnected]");
mainActivity.wifi_descovery_iv.setImageResource(R.drawable.ic_wifi_discovery_off);
}
}else if(WifiP2pManager.WIFI_P2P_THIS_DEVICE_CHANGED_ACTION.equals(action)) {
}
}
}
In the following code of my MainActivity (which downloads a json I need in another activity and shows a loading progress bar), which starts before launching HomeActivity, I get a null object reference error (on the getProgress() method), but HomeActivity then starts anyway if I press back button.
I have searched for this kind of error, but the only solution that seems working is the one that let me starts the HomeActivity after some delay, changing setProgress method like this: (but it seems that the bar doesn't change and I don't think it's a real solution to the problem)
public void setProgress(ProgressBar bar, int progress) {
int oldProgress = bar.getProgress();
int totalProgress = oldProgress + progress;
bar.setProgress(totalProgress);
if (bar.getProgress() == 100) {
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
final Intent intent = new Intent(MainActivity.this, HomePage.class);
startActivity(intent);
}
}, 4000);
}
}
----------------------------------------------------------------------
package ...
import ...
public class MainActivity extends AppCompatActivity {
private ProgressBar progressBar;
private TextView textView;
private OkHttpClient httpClient;
private String url;
private Request request;
private static boolean loaded = false;
private FileInputStream inputStream;
private FileOutputStream outputStream;
private static final String FILE_NAME = "data.txt";
private AlertDialogConnection noResponse;
private AlertDialogConnection noInternet;
private AlertDialogConnection serverError;
private AlertDialogConnection internalError;
public MainActivity(){
this.inputStream = null;
this.outputStream = null;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setContentView(R.layout.activity_main);
getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_HIDE_NAVIGATION);
this.httpClient = new OkHttpClient();
this.url = "my url";
this.request = new Request.Builder().url(url).build();
this.progressBar = findViewById(R.id.progressBar);
this.progressBar.getProgressDrawable().setColorFilter(getResources().getColor(R.color.progressBarColor), android.graphics.PorterDuff.Mode.SRC_IN);
this.textView = findViewById(R.id.textView);
this.noResponse = new AlertDialogConnection();
this.noInternet = new AlertDialogConnection();
this.serverError = new AlertDialogConnection();
this.internalError = new AlertDialogConnection();
checkConnectionStatusAndStart();
}
#Override
public void onWindowFocusChanged(boolean hasFocus) {
super.onWindowFocusChanged(hasFocus);
if (hasFocus) {
getWindow().getDecorView().setSystemUiVisibility(
View.SYSTEM_UI_FLAG_LAYOUT_STABLE
| View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
| View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
| View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
| View.SYSTEM_UI_FLAG_FULLSCREEN
| View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
}
}
public void checkConnectionStatusAndStart(){
if(checkConnectionStatus())
requestData();
else{
this.noInternet.setTitle("no connection!");
this.noInternet.setText("connection error!");
this.noInternet.show(getSupportFragmentManager(), "no connection!");
}
}
public boolean checkConnectionStatus(){
boolean wifiConnection = false;
boolean mobileConnection = false;
ConnectivityManager connectivityManager = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = null;
if (connectivityManager != null)
networkInfo = connectivityManager.getActiveNetworkInfo();
if((networkInfo != null) && networkInfo.isConnected()){
if(networkInfo.getType() == ConnectivityManager.TYPE_WIFI){
/* Wifi On */
wifiConnection = true;
}
if(networkInfo.getType() == ConnectivityManager.TYPE_MOBILE){
/* Mobile data On */
mobileConnection = true;
}
return (wifiConnection || mobileConnection);
}else{
/* You are not connected */
return false;
}
}
public void requestData(){
textView.setText("waiting server...");
httpClient.connectTimeoutMillis(); //Timeout
httpClient.writeTimeoutMillis();
httpClient.newCall(request).enqueue(new Callback() {
#Override
public void onFailure(Call call, IOException e) {
if(!call.isExecuted()){
Toast.makeText(getApplicationContext(), "server error!", Toast.LENGTH_LONG).show();
}
Log.d("HTTP-Error", "HTTP error!");
AlertDialogConnection errorDialog = new AlertDialogConnection();
errorDialog.setTitle("server error!");
errorDialog.setText("server error, try later");
errorDialog.show(getSupportFragmentManager(), "messaging error!");
}
#Override
public void onResponse(#NotNull Call call, Response response) throws IOException {
if(response.isSuccessful()){
/* HTTP-code: 200 */
final String body = response.body().string();
MainActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
((TextView)findViewById(R.id.textView)).setText("Setting of suggestion variables!");
setProgress(progressBar, 10);
try {
JSONObject json = new JSONObject(body);
try {
((TextView)findViewById(R.id.textView)).setText("retrieving server infos!");
saveJSON(json, getApplicationContext());
} catch (FileNotFoundException e) {
Log.d("File Not Found!", "FileNotFoundException!");
internalError.setTitle("error while saving data!");
internalError.setText("server error, try later");
internalError.show(getSupportFragmentManager(), "error while saving data!");
e.printStackTrace();
} catch (IOException e) {
Log.d("File Not Found!", "IOException!");
internalError.setTitle("error while saving data!");
internalError.setText("server error, try later");
internalError.show(getSupportFragmentManager(), "error while saving data!");
e.printStackTrace();
}
setProgress(progressBar, 90);
MainActivity.loaded = true;
} catch (JSONException e) {
e.printStackTrace();
Log.d("JSON-Error", "parsing JSON error!");
internalError.setTitle("server error!");
internalError.setText("server error, try later");
internalError.show(getSupportFragmentManager(), "JSON messaging error!");
}
}
});
}else{
/* Http-code: 500 */
Log.d("HTTP-Error", "server error!");
serverError.setTitle("server error!");
serverError.setText("server error");
serverError.show(getSupportFragmentManager(), "server error!");
}
}
});
}
public void setProgress(ProgressBar bar, int progress){
int oldProgress = bar.getProgress();
int totalProgress = oldProgress + progress;
bar.setProgress(totalProgress);
if(bar.getProgress() == 100){
Intent intent = new Intent(this, HomePage.class);
startActivity(intent);
this.onDestroy();
}
}
private void saveJSON(JSONObject json, Context context) throws IOException {
outputStream = null;
try{
outputStream = context.openFileOutput(FILE_NAME, MODE_PRIVATE);
outputStream.write(json.toString().getBytes());
}finally {
if(outputStream != null){
outputStream.close();
}
}
}
public JSONObject loadJSON(Context context) throws IOException, JSONException {
inputStream = context.openFileInput(FILE_NAME);
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
JSONObject jsonObject = new JSONObject(reader.readLine());
inputStream.close();
return jsonObject;
}
#Override
protected void onStart() {
super.onStart();
}
#Override
protected void onStop() {
super.onStop();
}
#Override
protected void onDestroy() {
this.httpClient = null;
this.noResponse = null;
this.noInternet = null;
this.serverError = null;
this.internalError = null;
this.request = null;
this.textView = null;
this.progressBar = null;
this.url = null;
super.onDestroy();
}
#Override
protected void onResume() {
if(!loaded){
checkConnectionStatusAndStart();
}
super.onResume();
}
#Override
protected void onRestart() {
if(!loaded){
checkConnectionStatusAndStart();
}
super.onRestart();
}
#Override
protected void onPause() {
if(!loaded ){
checkConnectionStatusAndStart();
}
super.onPause();
}
}
I'm making a OBDII reader app and would like to see the (in this case) voltage on text rather than in the Logcat which is what I currently see. You can see in the code below where I read the voltage in my while loop. Is it possible to update the textView everytime the loop runs?
Any help is appreciated!
.java
public class BTHandler {
public static final int STATE_NONE = 0; // we're doing nothing
public static final int STATE_CONNECTING = 2; // now initiating an outgoing connection
public static final int STATE_CONNECTED = 3; // now connected to a remote device
private final BluetoothAdapter mAdapter;
private final Handler mHandler;
BluetoothAdapter mBluetoothAdapter;
UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
private String status;
private BluetoothDevice mmDevice;
private ConnectedThread mConnectedThread;
private ConnectThread mConnectThread;
private int pPlatform = Constants.SPA;
private boolean connectionStatus = false;
public BTHandler(Context context, Handler handler) { // Konstruktor
mAdapter = BluetoothAdapter.getDefaultAdapter();
mHandler = handler;
}
public void write(String s) {
mConnectedThread.sendRawCommand(s);
Log.v("write", "write");
}
public void close() {
try {
mConnectedThread.cancel();
} catch (NullPointerException e) {
}
}
public void connect(String deviceAddress) {
mConnectThread = new ConnectThread(deviceAddress);
mConnectThread.start();
}
private void guiHandler(int what, int arg1, String obj) {
Message msg = mHandler.obtainMessage();
msg.what = what;
msg.obj = obj;
msg.arg1 = arg1;
msg.sendToTarget();
}
private class ConnectThread extends Thread {
private final BluetoothDevice mmDevice;
BluetoothSocket tmp = null;
private BluetoothSocket mmSocket;
public ConnectThread(String deviceAddress) {
mmDevice = mAdapter.getRemoteDevice(deviceAddress);
try {
// MY_UUID is the app's UUID string, also used by the server code
tmp = mmDevice.createRfcommSocketToServiceRecord(MY_UUID);
} catch (IOException e) {
}
mmSocket = tmp;
}
public void run() {
// Cancel discovery because it will slow down the connection
mAdapter.cancelDiscovery();
try {
// Connect the device through the socket. This will block
// until it succeeds or throws an exception
mmSocket.connect();
} catch (IOException connectException) {
// Unable to connect; close the socket and get out
try {
mmSocket.close();
} catch (IOException closeException) {
}
guiHandler(Constants.TOAST, Constants.SHORT, "Connection Failed");
return;
}
// Do work to manage the connection (in a separate thread)
guiHandler(Constants.CONNECTION_STATUS, Constants.STATE_CONNECTED, "");
mConnectedThread = new ConnectedThread(mmSocket);
mConnectedThread.start();
}
}
private class ConnectedThread extends Thread {
private final InputStream mmInStream;
private final OutputStream mmOutStream;
private BluetoothSocket mmSocket;
private ObdMultiCommand multiCommand;
public ConnectedThread(BluetoothSocket socket) {
connectionStatus = true;
mmSocket = socket;
InputStream tmpIn = null;
OutputStream tmpOut = null;
switch (pPlatform) {
case Constants.SPA:
multiCommand = new ObdMultiCommand();
multiCommand.add(new OdbRawCommand(SPA.VOLTAGE));
break;
}
try {
tmpIn = socket.getInputStream();
tmpOut = socket.getOutputStream();
} catch (IOException e) {
Log.v("e", "e");
}
mmInStream = tmpIn;
mmOutStream = tmpOut;
}
public void run() {
OBDcmds();
ModuleVoltageCommand voltageCommand = new ModuleVoltageCommand();
//TextView textView = (TextView) findViewById(R.id.textView);
while (!Thread.currentThread().isInterrupted()) {
try {
voltageCommand.run(mmInStream, mmOutStream);
voltageCommand.getFormattedResult();
Log.d("Log", "Voltage:" + voltageCommand.getFormattedResult());
textView.setText(voltageCommand.getFormattedResult());
} catch (Exception e) {
e.printStackTrace();
}
}
}
// CALL this to MainActivity
public void sendRawCommand(String s) {
try {
} catch (Exception e) {
Log.v("sendRawCommand", "e");
}
}
/*
// Call this from the main activity to send data to the remote device
public void write(byte[] bytes) {
try {
mmOutStream.write(bytes);
} catch (IOException e) {
e.printStackTrace();
}
}
*/
private void OBDcmds() { // execute commands
try {
new EchoOffCommand().run(mmInStream, mmOutStream);
new LineFeedOffCommand().run(mmInStream, mmOutStream);
new TimeoutCommand(100).run(mmInStream, mmOutStream);
new SelectProtocolCommand(ObdProtocols.AUTO).run(mmInStream, mmOutStream);
//ISO_15765_4_CAN
} catch (Exception e) {
Log.v("OBDcmds", "e");
// handle errors
}
}
/* Call this from the main activity to shutdown the connection */
public void cancel() {
try {
connectionStatus = false;
mmSocket.close();
guiHandler(Constants.CONNECTION_STATUS, Constants.STATE_NOT_CONNECTED, "");
} catch (IOException e) {
}
}
}
}
.xml
<TextView
android:id="#+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="178dp"
android:text="Medium Text"
android:textAppearance="?android:attr/textAppearanceMedium" />
MainActivity
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
Button b1;
BluetoothAdapter mAdapter;
BTHandler btHandler;
private Handler mHandler = new Handler() {
#Override
public void handleMessage(Message msg) {
switch (msg.what) {
case Constants.MESSAGE_STATE_CHANGE:
switch (msg.arg1) {
case BTHandler.STATE_CONNECTED:
setContentView(R.layout.activity_connected);
Toast.makeText(getApplicationContext(), R.string.title_connected_to, Toast.LENGTH_SHORT).show();
Log.v("Log", "Connected");
break;
case BTHandler.STATE_NONE:
Toast.makeText(getApplicationContext(), R.string.title_not_connected, Toast.LENGTH_SHORT).show();
break;
}
}
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView textView = (TextView) findViewById(R.id.textView);
btHandler = new BTHandler(MainActivity.this, mHandler);
b1 = (Button) findViewById(R.id.connect);
b1.setOnClickListener(this);
mAdapter = BluetoothAdapter.getDefaultAdapter();
if (mAdapter == null) {
Toast.makeText(getApplicationContext(), R.string.device_not_supported, Toast.LENGTH_LONG).show();
finish();
} else {
if (!mAdapter.isEnabled()) {
Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(intent, 1);
}
}
}
public void onClick(View v) {
int id = v.getId();
//String voltage = ("ATRV");
switch (id) {
case R.id.connect:
onConnect(); //Operation
Log.v("Log", "Pressed onClick");
break;
case R.id.getValue:
btHandler.write(SPA.VOLTAGE);
Log.v("getValue","" + SPA.VOLTAGE);
break;
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_CANCELED) {
Toast.makeText(getApplicationContext(), R.string.enable_bluetooth, Toast.LENGTH_SHORT).show();
finish();
}
}
private void onConnect() {
ArrayList deviceStrs = new ArrayList();
final ArrayList<String> devices = new ArrayList();
BluetoothAdapter mAdapter = BluetoothAdapter.getDefaultAdapter();
Set pairedDevices = mAdapter.getBondedDevices();
if (pairedDevices.size() > 0) {
for (Object device : pairedDevices) {
BluetoothDevice bdevice = (BluetoothDevice) device;
deviceStrs.add(bdevice.getName() + "\n" + bdevice.getAddress());
devices.add(bdevice.getAddress());
}
}
// show list
final AlertDialog.Builder alertDialog = new AlertDialog.Builder(this);
ArrayAdapter adapter = new ArrayAdapter(this, android.R.layout.select_dialog_singlechoice,
deviceStrs.toArray(new String[deviceStrs.size()]));
alertDialog.setSingleChoiceItems(adapter, -1, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
int position = ((AlertDialog) dialog).getListView().getCheckedItemPosition();
String deviceAddress = devices.get(position);
btHandler.connect(deviceAddress);
}
});
alertDialog.setTitle("Paired devices");
alertDialog.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_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);
}
}
Your object extends the Thread so I assume that it would be started like this
ConnectedThread ct = new ConnectedThread(socket);
ct.start();
In Android you can't update View from non-UI thread. You would need to create a Handler and pass the data to it. In you Handler implementation you would be able to call the setText() method to update your TextView.
See this link for more details about communication with UT thread.
For the updated post
I personally don't like the idea to change the layout of the Activity in the Handler implementation - I would go for Fragments usage.
Anyway after calling the setContentView(R.layout.activity_connected) in your Handler you need to call the findViewById again to find the TextView in your activity_connected layout:
case BTHandler.STATE_CONNECTED:
setContentView(R.layout.activity_connected);
Toast.makeText(getApplicationContext(), R.string.title_connected_to, Toast.LENGTH_SHORT).show();
Log.v("Log", "Connected");
TextView tv = (TextView)findViewById(R.id.textView);
tv.setText("Connected");
break;
Code snippet update
ConnectedThread#run()
public void run() {
OBDcmds();
ModuleVoltageCommand voltageCommand = new ModuleVoltageCommand();
//TextView textView = (TextView) findViewById(R.id.textView);
while (!Thread.currentThread().isInterrupted()) {
try {
voltageCommand.run(mmInStream, mmOutStream);
Log.d("Log", "Voltage:" + voltageCommand.getFormattedResult());
guiHandler(Constants.VOLTAGE_STATUS, 0, voltageCommand.getFormattedResult())
} catch (Exception e) {
e.printStackTrace();
}
}
}
Handler implementation
private Handler mHandler = new Handler() {
TextView textView = null;
#Override
public void handleMessage(Message msg) {
switch (msg.what) {
case Constants.MESSAGE_STATE_CHANGE:
switch (msg.arg1) {
case BTHandler.STATE_CONNECTED:
setContentView(R.layout.activity_connected);
Toast.makeText(getApplicationContext(), R.string.title_connected_to, Toast.LENGTH_SHORT).show();
Log.v("Log", "Connected");
textView = (TextView)findViewById(R.id.textView);
break;
case BTHandler.STATE_NONE:
Toast.makeText(getApplicationContext(), R.string.title_not_connected, Toast.LENGTH_SHORT).show();
break;
}
break;
case Constants.VOLTAGE_STATUS:
if(msg.obj != null && textView != null){
textView.setText((String)msg.obj)
}
break;
}
}
};
Use textView.setText(voltageCommand.getFormattedResult())
First, you need to map your textView to the resource ID.
TextView textView = (TextView) findViewById(R.id.textView);
you can place the above line after setContentView("your layout");
Now, you can use this textView and set the data as shown below,
textView.setText(voltageCommand.getFormattedResult());
This is about Android app development basics, you should read the tutorials at developer.android.com.
You can access the TextView with
TextView textView = (TextView) findViewbyId(R.id.textView);.
Then change your text with
textView.setText("new message");
HTH
I'm creating an app in Android using Socket.IO. I am stuck at the Login itself. Here is my code for Login
public class MainActivity extends AppCompatActivity {
EditText uname_et, pwd_et;
Button log;
String username, password;
private Socket mSocket;
private Emitter.Listener onLogin = new Emitter.Listener() {
#Override
public void call(Object... args) {
Log.e(args[0].toString(), "data");
Log.w("yes ", "in evtLogin");
// JSONObject data = (JSONObject) args[0];
}
};
{
try {
String URL = "http://MYIP:8081";
mSocket = IO.socket(URL);
} catch (URISyntaxException e1) {
e1.printStackTrace();
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
uname_et = (EditText) findViewById(R.id.username_input);
pwd_et = (EditText) findViewById(R.id.pwd);
log = (Button) findViewById(R.id.sign_in_button);
log.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
signin();
}
});
mSocket.on(Socket.EVENT_CONNECT, new Emitter.Listener() {
#Override
public void call(Object... args) {
Log.i("Make Emit", "Emit");
Log.w(mSocket.connected() + " - ", "Connection status");
}
});
mSocket.on("evtLogin", onLogin);
mSocket.connect();
}
private void signin() {
username = uname_et.getText().toString();
password = pwd_et.getText().toString();
mSocket.emit("userName", username);
mSocket.emit("Password", password);
}
#Override
protected void onDestroy() {
super.onDestroy();
mSocket.off("evtLogin", onLogin);
}
}
I'm not sure that socket is even connected or not, I'm gettong logs from Socket.EVENT_CONNECT
08-31 12:22:22.062 13399-13441/com.fis.kotsocket I/Make Emit﹕ Emit
08-31 12:22:22.063 13399-13441/com.fis.kotsocket W/true -﹕ Connection status
But onLogin listener is not called.
As a newbie I am not sure what to do exactly.
js code
//code for login event
socket.on('evtLogin', function (loginData) {
console.log('loged');
User.findOne({'login.userName':loginData.userName,'login.password':loginData.password},function(err,user){
if(err){throw err;}
else {if(!user){
console.log('not a authenticated user');
}
else
{
var userType;
User.find({'login.userName':loginData.userName,'login.password':loginData.password},function(err,rslt){
if(err){throw err;}
else
{
userType = JSON.stringify(rslt[0]['userType'].userId);
socket.emit('evtUserType',userType);
}
})
}
}
});
console.log('done');
});
Your socket is not getting initialized.
Try this initialization:
private Socket mSocket;
{
try {
mSocket = IO.socket("enter url here");
} catch (URISyntaxException e) {}
}
Or it might be that you are not emitting the evtLogin event from your javascript code.
I'm new at java and i would like to know how to click multiple buttons on same page without making the app force close. I tried to make the code more simple. For now , the first button is work well but the second button will force close the app when get clicked.
Im sorry if im not clear enough to explain my problem
im open for any advices
public static enum CONN_TYPE {
LEJOS_PACKET, LEGO_LCP
}
class UIMessageHandler extends Handler {
#Override
public void handleMessage(Message msg) {
switch (msg.what) {
case MESSAGE:
_message.setText((String) msg.getData().get(MESSAGE_CONTENT));
break;
case TOAST:
showToast((String) msg.getData().get(MESSAGE_CONTENT));
break;
}
_message.setVisibility(View.VISIBLE);
_message.requestLayout();
}
}
public static final String MESSAGE_CONTENT = "String_message";
public static final int MESSAGE = 1000;
public static final int TOAST = 2000;
private BTSend Right;
private TachoCount tachoCount;
private Toast reusableToast;
private TextView _message;
//static final String START_MESSAGE = "Please make sure you NXT is on and both it and your Android handset have bluetooth enabled";
private static final String GO_AHEAD = "Choose one!";
public static UIMessageHandler mUIMessageHandler;
private final static String TAG = "LeJOSDroid";
public static NXTConnector connect(final CONN_TYPE connection_type) {
Log.d(TAG, " about to add LEJOS listener ");
NXTConnector conn = new NXTConnector();
conn.setDebug(true);
conn.addLogListener(new NXTCommLogListener() {
public void logEvent(String arg0) {
Log.e(TAG + " NXJ log:", arg0);
}
public void logEvent(Throwable arg0) {
Log.e(TAG + " NXJ log:", arg0.getMessage(), arg0);
}
});
switch (connection_type) {
case LEGO_LCP:
conn.connectTo("btspp://NXT", NXTComm.LCP);
break;
case LEJOS_PACKET:
conn.connectTo("btspp://");
break;
}
return conn;
}
public static void displayToastOnUIThread(String message) {
Message message_holder = formMessage(message);
message_holder.what = LeJOSDroid.TOAST;
mUIMessageHandler.sendMessage(message_holder);
}
private static Message formMessage(String message) {
Bundle b = new Bundle();
b.putString(LeJOSDroid.MESSAGE_CONTENT, message);
Message message_holder = new Message();
message_holder.setData(b);
return message_holder;
}
public static void sendMessageToUIThread(String message) {
Message message_holder = formMessage(message);
message_holder.what = LeJOSDroid.MESSAGE;
mUIMessageHandler.sendMessage(message_holder);
}
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mUIMessageHandler = new UIMessageHandler();
setContentView(R.layout.main);
_message = (TextView) findViewById(R.id.messageText);
seupNXJCache();
setupTachoCount(this);
setupRight(this);
setupBackward(this);
reusableToast = Toast.makeText(this, "", Toast.LENGTH_SHORT);
}
#Override
protected void onPause() {
super.onPause();
if (Right != null) {
Log.d(TAG, "onPause() closing btSend ");
Right.closeConnection();
Right = null;
}
if (tachoCount != null) {
Log.d(TAG, "onPause() closing btSend ");
tachoCount.closeConnection();
}
}
#Override
protected void onResume() {
super.onResume();
}
public void onCreate1 (Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button button3 = (Button) findViewById(R.id.button3);
Button button1 = (Button) findViewById(R.id.button1);
Button button2 = (Button) findViewById(R.id.button2);
button2.setOnClickListener(new View.OnClickListener(){
public void onClick(View arg0) {
switch(arg0.getId()){
case R.id.button2:
try {
tachoCount = new TachoCount();
_message.setVisibility(View.INVISIBLE);
tachoCount.start();
} catch (Exception e) {
Log.e(TAG, "failed to run BTSend:" + e.getMessage(), e);
}
break;
}
}
});
button3.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
switch(arg0.getId()){
case R.id.button3:
try {
tachoCount = new TachoCount();
_message.setVisibility(View.INVISIBLE);
tachoCount.start();
} catch (Exception e) {
Log.e(TAG, "failed to run TachoCount:" + e.getMessage(), e);
}
break;
}
}
});
button1.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
switch(arg0.getId()){
case R.id.button1:
try {
tachoCount = new TachoCount();
_message.setVisibility(View.INVISIBLE);
tachoCount.start();
} catch (Exception e) {
Log.e(TAG, "failed to run TachoCount:" + e.getMessage(), e);
}
break;
}
}
});
}
private void seupNXJCache() {
File root = Environment.getExternalStorageDirectory();
try {
String androidCacheFile = "nxj.cache";
File mLeJOS_dir = new File(root + "/leJOS");
if (!mLeJOS_dir.exists()) {
mLeJOS_dir.mkdir();
}
File mCacheFile = new File(root + "/leJOS/", androidCacheFile);
if (root.canWrite() && !mCacheFile.exists()) {
FileWriter gpxwriter = new FileWriter(mCacheFile);
BufferedWriter out = new BufferedWriter(gpxwriter);
out.write("");
out.flush();
out.close();
_message.setText("nxj.cache (record of connection addresses) written to: " + mCacheFile.getName() + GO_AHEAD);
} else {
_message.setText("nxj.cache file not written as"
+ (!root.canWrite() ? mCacheFile.getName() + " can't be written to sdcard." : " cache already exists.") + GO_AHEAD);
}
} catch (IOException e) {
Log.e(TAG, "Could not write nxj.cache " + e.getMessage(), e);
}
_message.setVisibility(View.VISIBLE);
_message.requestLayout();
}
private void showToast(String textToShow) {
reusableToast.setText(textToShow);
reusableToast.show();
}
}
You can use this method to your Button View, to manually click it.
View.performClick();
The same you can do to other button, to click them together.
It is hard to say, why your app is closing, looking on your code. What I have noticed, is that you are doing the same work, in all 3 buttons clickMethods. In all 3 buttons you are doing:
tachoCount = new TachoCount();
_message.setVisibility(View.INVISIBLE);
tachoCount.start();
Also, I see from your code, that you can use only one button onCLick listener, by combine all your listeners code together.
View.OnClickListener buttonListener = new View.OnClickListener() {
public void onClick(View arg0) {
switch(arg0.getId()){
case R.id.button1:
try {
tachoCount = new TachoCount();
_message.setVisibility(View.INVISIBLE);
tachoCount.start();
} catch (Exception e) {
Log.e(TAG, "failed to run TachoCount:" + e.getMessage(), e);
}
break;
case R.id.button3:
try {
tachoCount = new TachoCount();
_message.setVisibility(View.INVISIBLE);
tachoCount.start();
} catch (Exception e) {
Log.e(TAG, "failed to run TachoCount:" + e.getMessage(), e);
}
break;
case R.id.button2:
try {
tachoCount = new TachoCount();
_message.setVisibility(View.INVISIBLE);
tachoCount.start();
} catch (Exception e) {
Log.e(TAG, "failed to run BTSend:" + e.getMessage(), e);
}
break;
}
}
And later
button2.setOnClickListener(buttonListener);
Check your logfile if it is memory related issue you can increase you heap memory Increase Heap Memory