I am successfully passing string from my android to computer(through WiFi) using two simple button.but my question is i want to use single radio button (as toggle) instead of two simple button .here is my code
import java.io.IOException;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import android.os.Bundle;
import android.app.Activity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class MainActivity extends Activity {
private Socket client;
private PrintWriter printwriter;
private Button button;
private Button button1;
private String messsage;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
button = (Button) findViewById(R.id.button1);
button1 = (Button) findViewById(R.id.button2);
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
messsage = "TV ON" ; //etMsg.getText().toString();
//etMsg.setText("");
// port = Integer.parseInt(etPort.getText().toString());
new Thread(new Runnable()
{
#Override
public void run() {
// TODO Auto-generated method stub
try
{
// client = new Socket(etIP.getText().toString(), port);
client = new Socket("1.2.3.4",2000);
printwriter = new PrintWriter(client.getOutputStream(),true);
printwriter.write(messsage);
printwriter.flush();
printwriter.close();
client.close();
}
catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}).start();
}
});
button1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
messsage = "TV OFF" ; //etMsg.getText().toString();
//etMsg.setText("");
// port = Integer.parseInt(etPort.getText().toString());
new Thread(new Runnable()
{
#Override
public void run() {
// TODO Auto-generated method stub
try
{
// client = new Socket(etIP.getText().toString(), port);
client = new Socket("1.2.3.4",2000);
printwriter = new PrintWriter(client.getOutputStream(),true);
printwriter.write(messsage);
printwriter.flush();
printwriter.close();
client.close();
}
catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}).start();
}
});
}
}
Lets Consider,
RadioButtonGroup ID : ControlTVRadioButtonGroup
Radio Buttons in this group are : TV_on_rb and TV_off_rb
code:
ControlTVRadioButtonGroup= (RadioGroup) view.findViewById(R.id.ControlTVRadioButtonGroup);
ControlTVRadioButtonGroup.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
if(checkedId == R.id.TV_on_rb)
{
//code you have written in onclick of button (i.e for tv_on)
}
else if(checkedId == R.id.TV_off_rb)
{
//code you have written in onclick of button1 (i.e for tv_off)
}
}
});
I think you want to look into using a CheckBox instead of a radio button group. It's a simple two-state button (checked or unchecked). From the documentation:
final CheckBox checkBox = (CheckBox) findViewById(R.id.checkbox_id);
if (checkBox.isChecked()) {
checkBox.setChecked(false);
}
Related
Im almost getting to the end of my Sound bar project (2 arduinos, relays, digital potentiometers, leds, i2c, bluetooth and ir remote, diy amplifier,...) and I`m stuck.
This is my first time using android studio and things are becoming so hard for me.
I created an app with a few buttons, switch, sliders and dropdown menu that connects to bluetooth module and sends values to my arduino.
Now I need to add a script that would receive values that arduino is sending (got arduino code done), and would eventualy set buttons clickable/unclickable and set slider positions depending on values being received thru bluetooth.
Can somebody please show me the way to read values from bluetooth and store them in integer or something so that buttons could be disabled and enabled with if(integer=x); statements.
I will post my java code (App is almost done, excepet for sliders and this bluetooth receive part) and I will post the code I came with so far...
I`m going nuts on this one.
Thank you for help :)
package com.interface80.soundbarcontrol;
import androidx.appcompat.app.AppCompatActivity;
import android.content.pm.ActivityInfo;
import android.icu.text.Transliterator;
import android.os.Build;
import android.os.*;
import android.os.Bundle;
import android.app.Activity;
import android.app.ProgressDialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Intent;
import android.os.AsyncTask;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.RadioGroup;
import android.widget.Spinner;
import android.widget.Switch;
import android.widget.Toast;
import java.io.IOException;
import java.io.InputStream;
import java.util.Set;
import java.util.UUID;
public class Remote extends Activity implements AdapterView.OnItemSelectedListener {
private static final String TAG = "BlueTest5-Controlling";
private int mMaxChars = 50000;//Default//change this to string..........
private UUID mDeviceUUID;
private BluetoothSocket mBTSocket;
private ReadInput mReadThread = null;
private boolean mIsUserInitiatedDisconnect = false;
private boolean mIsBluetoothConnected = false;
private int mLastSpinnerPosition = 0;
private Button mBtnDisconnect;
private BluetoothDevice mDevice;
final static String on="92";//on
final static String off="79";//off
final static String subon="10";//subon
final static String suboff="15";//suboff
final static String zero="20";//zeroDB
final static String six="25";//sixDB
final static String twelwe="30";//twelweDB
final static String userBoost="40";
final static String softBoost="45";
final static String normalBoost="50";
final static String hardBoost="55";
final static String overloadOn="60";
final static String overloadOff="65";
Switch toggle; //outside oncreate
private ProgressDialog progressDialog;
Button btnon,btnoff, btnsubon, btnsuboff, btnzero, btnsix, btntwelwe;
Switch overloadSwitch;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_remote);
Spinner spinnerPresets = (Spinner) findViewById(R.id.spinnerPresets);
ArrayAdapter<String> adapterPresets = new ArrayAdapter<String>(Remote.this,
android.R.layout.simple_list_item_1, getResources().getStringArray(R.array.arrayPresets));
adapterPresets.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerPresets.setAdapter(adapterPresets);
spinnerPresets.setOnItemSelectedListener(this);
ActivityHelper.initialize(this);
// mBtnDisconnect = (Button) findViewById(R.id.btnDisconnect);
btnon = (Button) findViewById(R.id.on);
btnoff = (Button) findViewById(R.id.off);
btnsubon = (Button) findViewById(R.id.subon);
btnsuboff = (Button) findViewById(R.id.suboff);
btnzero = (Button) findViewById(R.id.zero);
btnsix = (Button) findViewById(R.id.six);
btntwelwe = (Button) findViewById(R.id.twelwe);
overloadSwitch = (Switch) findViewById(R.id.overloadSwitch);
Intent intent = getIntent();
Bundle b = intent.getExtras();
mDevice = b.getParcelable(MainActivity.DEVICE_EXTRA);
mDeviceUUID = UUID.fromString(b.getString(MainActivity.DEVICE_UUID));
mMaxChars = b.getInt(MainActivity.BUFFER_SIZE);
Log.d(TAG, "Ready");
btnon.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
try {
mBTSocket.getOutputStream().write(on.getBytes());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
btnoff.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
try {
mBTSocket.getOutputStream().write(off.getBytes());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
btnsubon.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
try {
mBTSocket.getOutputStream().write(subon.getBytes());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
btnsuboff.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
try {
mBTSocket.getOutputStream().write(suboff.getBytes());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
btnzero.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
try {
mBTSocket.getOutputStream().write(zero.getBytes());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
btnsix.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
try {
mBTSocket.getOutputStream().write(six.getBytes());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
btntwelwe.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
try {
mBTSocket.getOutputStream().write(twelwe.getBytes());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String text = parent.getItemAtPosition(position).toString();
if (mLastSpinnerPosition == position)
{
return;
}
mLastSpinnerPosition = position;
if (0 == position) {
Toast.makeText(parent.getContext(), "Boost controlled by user.", Toast.LENGTH_SHORT).show();
btnzero.setEnabled(true);
btnsix.setEnabled(true);
btntwelwe.setEnabled(true);
try {
mBTSocket.getOutputStream().write(userBoost.getBytes());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return; //do nothing
}
if (1 == position) {
try {
mBTSocket.getOutputStream().write(softBoost.getBytes());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Toast.makeText(parent.getContext(), "DynaBoost control.", Toast.LENGTH_SHORT).show();
btnzero.setEnabled(false);
btnsix.setEnabled(false);
btntwelwe.setEnabled(false);
return; //do nothing
}
if (2 == position) {
try {
mBTSocket.getOutputStream().write(normalBoost.getBytes());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Toast.makeText(parent.getContext(), "DynaBoost control.", Toast.LENGTH_SHORT).show();
btnzero.setEnabled(false);
btnsix.setEnabled(false);
btntwelwe.setEnabled(false);
return; //do nothing
}
if (3 == position) {
try {
mBTSocket.getOutputStream().write(hardBoost.getBytes());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Toast.makeText(parent.getContext(), "DynaBoost control.", Toast.LENGTH_SHORT).show();
btnzero.setEnabled(false);
btnsix.setEnabled(false);
btntwelwe.setEnabled(false);
return; //do nothing
}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
private class ReadInput implements Runnable {
private boolean bStop = false;
private Thread t;
public ReadInput() {
t = new Thread(this, "Input Thread");
t.start();
}
public boolean isRunning() {
return t.isAlive();
}
#Override
public void run() {
InputStream inputStream;
try {
inputStream = mBTSocket.getInputStream();
while (!bStop) {
byte[] buffer = new byte[256];
if (inputStream.available() > 0) {
inputStream.read(buffer);
int i = 0;
/*
* This is needed because new String(buffer) is taking the entire buffer i.e. 256 chars on Android 2.3.4 http://stackoverflow.com/a/8843462/1287554
*/
for (i = 0; i < buffer.length && buffer[i] != 0; i++) {
}
final String strInput = new String(buffer, 0, i);
/*
* If checked then receive text, better design would probably be to stop thread if unchecked and free resources, but this is a quick fix
*/
}
Thread.sleep(500);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void stop() {
bStop = true;
}
}
private class DisConnectBT extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
}
#Override
protected Void doInBackground(Void... params) {//cant inderstand these dotss
if (mReadThread != null) {
mReadThread.stop();
while (mReadThread.isRunning())
; // Wait until it stops
mReadThread = null;
}
try {
mBTSocket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
mIsBluetoothConnected = false;
if (mIsUserInitiatedDisconnect) {
finish();
}
}
}
private void msg(String s) {
Toast.makeText(getApplicationContext(), s, Toast.LENGTH_SHORT).show();
}
#Override
protected void onPause() {
if (mBTSocket != null && mIsBluetoothConnected) {
new DisConnectBT().execute();
}
Log.d(TAG, "Paused");
super.onPause();
}
#Override
protected void onResume() {
if (mBTSocket == null || !mIsBluetoothConnected) {
new ConnectBT().execute();
}
Log.d(TAG, "Resumed");
super.onResume();
}
#Override
protected void onStop() {
Log.d(TAG, "Stopped");
super.onStop();
}
#Override
protected void onSaveInstanceState(Bundle outState) {
// TODO Auto-generated method stub
super.onSaveInstanceState(outState);
}
private class ConnectBT extends AsyncTask<Void, Void, Void> {
private boolean mConnectSuccessful = true;
#Override
protected void onPreExecute() {
progressDialog = ProgressDialog.show(Remote.this, "", "Connecting");// http://stackoverflow.com/a/11130220/1287554
}
#Override
protected Void doInBackground(Void... devices) {
try {
if (mBTSocket == null || !mIsBluetoothConnected) {
mBTSocket = mDevice.createInsecureRfcommSocketToServiceRecord(mDeviceUUID);
BluetoothAdapter.getDefaultAdapter().cancelDiscovery();
mBTSocket.connect();
}
} catch (IOException e) {
// Unable to connect to device`
// e.printStackTrace();
mConnectSuccessful = false;
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
if (!mConnectSuccessful) {
Toast.makeText(getApplicationContext(), "Could not connect.Please turn on Sound bar", Toast.LENGTH_LONG).show();
finish();
} else {
msg("Connected to Sound bar");
mIsBluetoothConnected = true;
mReadThread = new ReadInput(); // Kick off input reader
}
progressDialog.dismiss();
}
}
#Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
}
public void toggle( View View) //outside oncreate
{
if( overloadSwitch.isChecked() ){
try {
mBTSocket.getOutputStream().write(overloadOn.getBytes());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return; //do nothing
}
else
{
try {
mBTSocket.getOutputStream().write(overloadOff.getBytes());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return; //do nothing
}
}
}
#Override
public void run() {
InputStream inputStream;
try {
inputStream = mBTSocket.getInputStream();
byte[] buffer = new byte[1024];
inputStream.read(buffer);
int BTvalue = buffer;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Problem solved.
I spent late night yesterday with no succes. Angry and frustrated I went to bed. Today I found out that none of the codes I was trying didn`t work, because code was already there. Reading and writing to string. Just used the string and done :)
The problem as seen in the title appears in line 102 of the code down below. Im very new to this topic and Im trying to make an app which can control an arduino... This part of code I show you is supposed to manage the connection to the Bluetooth Module and in my MainActivity I plan to send the letters to the other device.
I hope someone can help.
My code (BT_Classic.java):
package com.car.bluetooth.bluetoothcar;
import androidx.appcompat.app.AppCompatActivity;
import android.app.ProgressDialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Set;
import java.util.UUID;
public class BT_Classic extends AppCompatActivity {
private Button pairedButton;
private Button discoveredButton;
private Button btonButton;
private Button btoffButton;
private ProgressDialog progress;
ListView listView;
BluetoothSocket bluetoothSocket;
BluetoothDevice bluetoothDevice;
private final static UUID uuid = UUID.fromString("fc5ffc49-00e3-4c8b-9cf1-6b72aad1001a");
private ArrayList<String> mDeviceList = new ArrayList<String>();
BluetoothAdapter btAdapter = BluetoothAdapter.getDefaultAdapter();
//BLUETOOTH VERBINDUNG
private static final int REQUEST_ENABLED = 0;
private static final int REQUEST_DISCOVERABLE = 0;
private class ConnectingThread extends Thread {
public ConnectingThread(BluetoothDevice device) {
BluetoothSocket temp = null;
BluetoothDevice bluetoothDevice = device;
// Get a BluetoothSocket to connect with the given BluetoothDevice
try {
temp = bluetoothDevice.createRfcommSocketToServiceRecord(uuid);
} catch (IOException e) {
e.printStackTrace();
}
bluetoothSocket = temp;
}
public void run() {
// Cancel any discovery as it will slow down the connection
btAdapter.cancelDiscovery();
try {
// This will block until it succeeds in connecting to the device
// through the bluetoothSocket or throws an exception
bluetoothSocket.connect();
} catch (IOException connectException) {
connectException.printStackTrace();
try {
bluetoothSocket.close();
} catch (IOException closeException) {
closeException.printStackTrace();
}
}
// Code to manage the connection in a separate thread
/*
manageBluetoothConnection(bluetoothSocket);
*/
}
// Cancel an open connection and terminate the thread
public void cancel() {
try {
bluetoothSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_bt__classic);
pairedButton = (Button) findViewById(R.id.pairedButton);
discoveredButton = (Button) findViewById(R.id.discoveredButton);
btonButton = (Button) findViewById(R.id.btonButton);
btoffButton = (Button) findViewById(R.id.btoffButton);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String itemValue = (String) listView.getItemAtPosition(position);
String MAC = itemValue.substring(itemValue.length() - 17);
BluetoothDevice bluetoothDevice = btAdapter.getRemoteDevice(MAC);
// Initiate a connection request in a separate thread
ConnectingThread t = new ConnectingThread(bluetoothDevice);
t.start();
}
});
//Pairing Button
pairedButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Set<BluetoothDevice> pairedDevices = btAdapter.getBondedDevices();
ArrayList<String> devices = new ArrayList<String>();
for (BluetoothDevice bt : pairedDevices){
devices.add(bt.getName());
devices.add(bt.getAddress());
}
ArrayAdapter arrayAdapter = new ArrayAdapter(BT_Classic.this, android.R.layout.simple_list_item_1, devices);
listView.setAdapter(arrayAdapter);
}
});
discoveredButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(!btAdapter.isDiscovering()){
Intent bton = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
startActivityForResult(bton, REQUEST_DISCOVERABLE);
}
}
});
btonButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent bton = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(bton, REQUEST_ENABLED);
}
});
btoffButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
btAdapter.disable();
}
});
}
}
You have an extra } in this section
public void cancel() {
try {
bluetoothSocket.close();
} catch (IOException e) {
e.printStackTrace();
} // Close try
} // Close cancel()
} // Close ConnectingThread
} // DELETE THIS CURLY BRACE
First, it was problem with extra curly braces as Chris has mentioned.
Second, you haven't define your ListView as listView = findViewById(R.id.your_id);
That's it, and good luck. :)
First of all, I should say that I am a newbie on Java and Android programming. I am very experienced in C programming for embedded systems, but now I need to communicate one of my embedded projects with an Android app, in a very simple way. I am using one of those ESP8266, configured as default. Thus, it behaves as a basic telnet server. My microcontroller has to send a question (through a string, which is not constant) to my app, and receive a "Y" or "N" reply. I have tested it using a telnet client, and it is working fine. However, I want to have an app that pops up an alert dialog and/or show the message in a TextView element, and sends the reply after some button click. For this, I have adapted a telnet client code from:
http://android-er.blogspot.com.br/2014/08/simple-android-chat-application-client.html
I have put everything in one single panel, and reduced the number of elements to a textview element and 4 buttons (connect, disconnect, yes, and no). I am using a fixed IP and port to connect the app to my laptop, which is running a telnet server (hercules). The connection is confirmed, and the YES and NO buttons are sending the correct messages. However, the question string never shows up at the TextView element. I have also added an AlertDialog to pop up, because I think it is more appropriate to the kind of app I am developing.
Notice that the testing of the message income happens inside a thread, and I am calling the TextView update and the AlertDialog show using runOnUiThread.
Here is the Java code (not optimized yet):
package br.unicamp.smpci;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.support.v4.app.DialogFragment;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.support.v7.app.NotificationCompat;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends ActionBarActivity {
static final int SocketServerPORT = 80;
final Context context = this;
LinearLayout Panel;
Button buttonConnect;
TextView chatMsg;
Button buttonSendYes;
Button buttonSendNo;
Button buttonDisconnect;
String msgLog = "";
ChatClientThread chatClientThread = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Panel = (LinearLayout)findViewById(R.id.panel);
buttonConnect = (Button) findViewById(R.id.connect);
buttonDisconnect = (Button) findViewById(R.id.disconnect);
chatMsg = (TextView) findViewById(R.id.chatmsg);
buttonConnect.setOnClickListener(buttonConnectOnClickListener);
buttonDisconnect.setOnClickListener(buttonDisconnectOnClickListener);
buttonSendYes = (Button)findViewById(R.id.sendYes);
buttonSendYes.setOnClickListener(buttonSendYesOnClickListener);
buttonSendNo = (Button)findViewById(R.id.sendNo);
buttonSendNo.setOnClickListener(buttonSendNoOnClickListener);
}
OnClickListener buttonDisconnectOnClickListener = new OnClickListener() {
#Override
public void onClick(View v) {
if(chatClientThread==null){
return;
}
chatClientThread.disconnect();
}
};
OnClickListener buttonSendYesOnClickListener = new OnClickListener() {
#Override
public void onClick(View v) {
if(chatClientThread==null){
return;
}
chatClientThread.sendMsg("Y" + "\n");
}
};
OnClickListener buttonSendNoOnClickListener = new OnClickListener() {
#Override
public void onClick(View v) {
if(chatClientThread==null){
return;
}
chatClientThread.sendMsg("N" + "\n");
}
};
OnClickListener buttonConnectOnClickListener = new OnClickListener() {
#Override
public void onClick(View v) {
String textAddress = "192.168.1.11";
msgLog = "NO MESSAGES";
chatMsg.setText(msgLog);
chatClientThread = new ChatClientThread(
textAddress, SocketServerPORT);
chatClientThread.start();
}
};
private class ChatClientThread extends Thread {
String dstAddress;
int dstPort;
String msgToSend = "";
boolean goOut = false;
ChatClientThread(String address, int port) {
dstAddress = address;
dstPort = port;
}
#Override
public void run() {
Socket socket = null;
DataOutputStream dataOutputStream = null;
DataInputStream dataInputStream = null;
try {
socket = new Socket(dstAddress, dstPort);
dataOutputStream = new DataOutputStream(
socket.getOutputStream());
dataInputStream = new DataInputStream(socket.getInputStream());
while (!goOut) {
if (dataInputStream.available() > 0) {
msgLog = dataInputStream.readUTF();
MainActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
chatMsg.setText(msgLog);
chatMsg.invalidate();
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
context);
alertDialogBuilder.setTitle("ALERT");
alertDialogBuilder
.setMessage(MsgLog)
.setCancelable(false)
.setPositiveButton("Yes",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
if(chatClientThread==null){
return;
}
chatClientThread.sendMsg("Y" + "\n");
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
if (chatClientThread == null) {
return;
}
chatClientThread.sendMsg("N" + "\n");
}
});
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
}
});
}
if(!msgToSend.equals("")){
dataOutputStream.writeUTF(msgToSend);
dataOutputStream.flush();
msgToSend = "";
}
}
} catch (UnknownHostException e) {
e.printStackTrace();
final String eString = e.toString();
MainActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(MainActivity.this, eString, Toast.LENGTH_LONG).show();
}
});
} catch (IOException e) {
e.printStackTrace();
final String eString = e.toString();
MainActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(MainActivity.this, eString, Toast.LENGTH_LONG).show();
}
});
} finally {
if (socket != null) {
try {
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (dataOutputStream != null) {
try {
dataOutputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (dataInputStream != null) {
try {
dataInputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
MainActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
//loginPanel.setVisibility(View.VISIBLE);
//chatPanel.setVisibility(View.GONE);
}
});
}
}
private void sendMsg(String msg){
msgToSend = msg;
}
private void disconnect(){
goOut = true;
}
}
}
I have done extensive research on how to make sure that the UI thread updates my elements, and I am using the Show() method for the alertdialog, and invalidating the TextView element to force it to update. I have used debug, and I am sure that the instructions are being executed, but with no result on my app ( I am using a real device for debugging).
I have seen that maybe I could use AsyncTask for this purpose, but as a newbie I am facing difficulties to make the changes, and I believe that calling the updates with a runOnUiThread should do the work.
Can anyone explain why I cannot see my message, and maybe provide me a code correction?
Thanks in advance,
Antonio Quevedo
I have my major project on android based home automation system meaning that I have to control home appliances using android bluetooth. I am using HC-05 bluetooth module which receives the string sent to it through my application, sends it to PIC16f877a and the pic in turn depending upon the string received, controls the appliances. Now my problem is that I have been able to pair and connect the devices through my application but my application is not sending the characters which I want to send when I click the button. Note that PIC and the Bluetooth module are working fine. please help me. I am posting my code below hope you guys won't mind.
package com.chainedcat.splashscreen;
import java.io.IOException;
import java.io.OutputStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.UUID;
import android.app.Activity;
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.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivityActivity extends Activity{
private BluetoothAdapter BA;
private ArrayList<BluetoothDevice> devices;
private ListView lv;
private TextView text;
private BluetoothSocket btSocket=null;
private ArrayAdapter<String> btArrayAdapter;
private static final int REQUEST_ENABLE_BT = 1;
private UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34EB");
private OutputStream outStream=null;
public void Init(){
BA = BluetoothAdapter.getDefaultAdapter();
text =(TextView) findViewById(R.id.text);
lv = (ListView) findViewById(R.id.listView1);
devices = new ArrayList<BluetoothDevice>();
btArrayAdapter= new ArrayAdapter<String>this,android.R.layout.simple_list_item_1);
lv.setAdapter(btArrayAdapter);
}
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
Init();
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
BluetoothDevice selectedDevice = devices.get(arg2);
if(selectedDevice.getBondState()== BluetoothDevice.BOND_NONE){
pairDevice(selectedDevice);
}
else if(selectedDevice.getBondState()==BluetoothDevice.BOND_BONDED){
connect(selectedDevice);
}
}
});
}
public void bluetooth(View view){
if(!BA.isEnabled()){
Intent btIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(btIntent, REQUEST_ENABLE_BT);
Toast.makeText(getApplicationContext(), "Bluetooth turned on!!", Toast.LENGTH_LONG).show();
btExtra();
}else{
Toast.makeText(getApplicationContext(), "Bluetooth is already on!!", Toast.LENGTH_LONG).show();
btExtra();
}
}
public void btExtra(){
btArrayAdapter.clear();
BA.startDiscovery();
registerReceiver(btReceiver, new tentFilter(BluetoothDevice.ACTION_FOUND));
}
final BroadcastReceiver btReceiver = new BroadcastReceiver(){
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if(BluetoothDevice.ACTION_FOUND.equals(action)){
BluetoothDevice device=intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
devices.add(device);
String status=null;
if(device.getBondState()==BluetoothDevice.BOND_BONDED){
status="paired";
}else{status="not paired";}
btArrayAdapter.add(device.getName()+" : "+status+"\n"+device.getAddress());
btArrayAdapter.notifyDataSetChanged();
}
}
};
#Override
protected void onActivityResult(int requestCode,int resultCode, Intent data){
if(requestCode==REQUEST_ENABLE_BT){
if(BA.isEnabled()){
text.setText("Bluetooth Status:Enabled");
}else{
text.setText("Bluetooth Status:Disabled");
}
}
}
private void pairDevice(BluetoothDevice device) {
Method m=null;
try {
m = device.getClass().getMethod("createBond", (Class[]) null);
} catch (NoSuchMethodException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
m.invoke(device, (Object[]) null);
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
connect(device);
}
public void connect(BluetoothDevice device){
Toast.makeText(getApplicationContext(), "connecting....", Toast.LENGTH_LONG).show();
try {
btSocket=device.createInsecureRfcommSocketToServiceRecord(MY_UUID);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
BA.cancelDiscovery();
try {
Toast.makeText(getApplicationContext(), "entered in run", Toast.LENGTH_LONG).show();
btSocket.connect();
if(btSocket!=null){btSocket.close();}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void send(String s){
try {
outStream = btSocket.getOutputStream();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
byte[] bytes = s.getBytes();
try {
outStream.write(bytes);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void fan(View v){
send("f");
}
#Override
public void onDestroy(){
super.onDestroy();
BA.disable();
unregisterReceiver(btReceiver);
}
}
Hi I am creating a client-server application with an android device as the client. In my application, my client (android device) sends a request and the server has a response to the request.
I noticed that any method that causes the main thread to wait has to be done on a different thread. I am trying to do that but in my case use a ThreadExecutor. I implemented a helper Runnable class with I pass my ObjectInputStream to but for some reason, its always null. I have checked on a number of questions here but it seems most of them are about how to pass from one activity to another. However I would like to pass from my activity to my helper class and I am not sure of what to do.
Here is my code, I hope it makes more sense.
package com.dozie.service;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.StringWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import com.dcloud.common.Event;
import com.dcloud.common.Message;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class RegisterActivity extends Activity {
private Button registerButton;
private Button cancelButton;
private TextView errorText;
private EditText firstnameField, lastnameField, passwordField, cPasswordField, usernameField;
private String fname, lname, pword, cPword, uname;
private Socket socket;
private TextWatcher fnameWatcher, lnameWatcher, pwordWatcher, cPwordWatcher, unameWatcher;
protected ObjectOutputStream os;
protected ObjectInputStream is;
private ExecutorService threadPool;
private RegisterWorker worker;
public static final String PASSWORD_PATTERN = "((?=.*\\d)(?=.*[a-z])(?=.*[A-Z]).{6,20})";
public static final String USERNAME_PATTERN = "^[A-z0-9_-]{5,20}$";
public static final String TAG = RegisterActivity.class.getName();
public static final int SAMEFIRSTUSER = 100; //same first name and username,
public static final int SAMELASTUSER = 200; //same last name and username
public static final int SAMEPASSFIRST = 300; //same password and firstname
public static final int SAMEPASSLAST = 400; //same password and lastname
public static final int SAMEPASSUSER = 500; //same password and username
public static final int USERNOTMATCH = 600; //username does not match
public static final int PASSNOTMATCH = 700; //password does not match
public static final int CPASS_DIFF = 800; //password and confirm password are different
public static final int GOODINPUT = 1; //every input is good
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
registerButton = (Button) findViewById(R.id.register_id);
cancelButton = (Button) findViewById(R.id.cancel_id);
firstnameField = (EditText) findViewById(R.id.firstname_id);
lastnameField = (EditText) findViewById(R.id.lastname_id);
passwordField = (EditText) findViewById(R.id.rpassword_id);
cPasswordField = (EditText) findViewById(R.id.rcpassword_id);
usernameField = (EditText) findViewById(R.id.rusername_id);
errorText = (TextView) findViewById(R.id.errorText_id);
fname="";lname="";pword="";cPword="";uname="";
//initialize TextWatchers
initializeWatchers();
// add TextWatchers
firstnameField.addTextChangedListener(fnameWatcher);
lastnameField.addTextChangedListener(lnameWatcher);
passwordField.addTextChangedListener(pwordWatcher);
cPasswordField.addTextChangedListener(cPwordWatcher);
usernameField.addTextChangedListener(unameWatcher);
cancelButton.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
firstnameField.setText("");
lastnameField.setText("");
passwordField.setText("");
cPasswordField.setText("");
usernameField.setText("");
setResult(RESULT_CANCELED);
finish();
}
});
}
#Override
public void onStart()
{
super.onStart();
Log.d(TAG, "onStart()");
Intent intent = getIntent();
final String address = intent.getStringExtra("ipAddress");
final int port = intent.getIntExtra("port", 6060);
threadPool = Executors.newFixedThreadPool(2);
new Thread(new Runnable()
{
#Override
public void run() {
// TODO Auto-generated method stub
try {
Log.i(TAG, "Trying to Connect to "+ address + " on " + port);
socket = new Socket(address, port);
Log.i(TAG, "Connection established!");
os = new ObjectOutputStream(new DataOutputStream(socket.getOutputStream()));
is = new ObjectInputStream(new DataInputStream(socket.getInputStream()));
Log.i(TAG, "Client connected to server.");
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
Log.e(TAG, "UnknownHostException", e);
} catch (IOException e) {
// TODO Auto-generated catch block
Log.e(TAG, "I/O Exception", e);
}
}
}).start();
// threadPool.execute(worker = new RegisterWorker(is));;
}
#Override
public void onPause()
{
super.onPause();
Log.d(TAG, "onPause()");
threadPool.shutdown();
Message out = new Message("disconnect");
out.setRequest(Event.Request.DISCONNECT);
try {
os.writeObject(out);
} catch (IOException e) {
// TODO Auto-generated catch block
Log.e(TAG, "I/O Exception", e);
}
finally
{
try {
is.close();
os.close();
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Log.i(TAG, "socket closed");
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_register, menu);
return true;
}
public int validateInput(String [] input)
{
String firstname = input[0];
String lastname = input[1];
String password = input[2];
String cpassword = input[3];
String username = input[4];
Pattern pattern = Pattern.compile(PASSWORD_PATTERN);
Matcher matcher = pattern.matcher(password);
Pattern p = Pattern.compile(USERNAME_PATTERN);
Matcher m = p.matcher(username);
if(firstname.equals(username))
return RegisterActivity.SAMEFIRSTUSER;
if(lastname.equals(username))
return RegisterActivity.SAMELASTUSER;
if(firstname.equals(password))
return RegisterActivity.SAMEPASSFIRST;
if(lastname.equals(password))
return RegisterActivity.SAMEPASSLAST;
if(password.equals(username))
return RegisterActivity.SAMEPASSUSER;
if(!password.equals(cpassword))
return RegisterActivity.CPASS_DIFF;
if(!matcher.matches())
return RegisterActivity.PASSNOTMATCH;
if(!m.matches())
return RegisterActivity.USERNOTMATCH;
return RegisterActivity.GOODINPUT;
}
public void registerUser(View v)
{
String [] input = getUserInformation();
int result = validateInput(input);
switch(result)
{
case RegisterActivity.GOODINPUT:
Intent info = new Intent();
info.putExtra("username", input[4]);
registerUser(input);
if(worker.getServerResponse() != null)
{
if(worker.getServerResponse().getResponse() == Event.Response.REQUEST_SUCCESSFUL)
{
threadPool.shutdown();
setResult(RESULT_OK, info);
finish();
Log.i(TAG, "registerUser(): data input successful!");
}
else if(worker.getServerResponse().getResponse() == Event.Response.REQUEST_UNSUCCESSFUL)
{
threadPool.execute(worker);
Log.i(TAG, "registerUser(): data input unsuccessful!");
}
}
break;
case RegisterActivity.SAMEFIRSTUSER:
errorText.setText("username should not be the same as firstname");
Log.i(TAG, "registerUser(): username same as firstname");break;
case RegisterActivity.SAMELASTUSER:
errorText.setText("username should not be the same as lastname");
Log.i(TAG, "registerUser(): username same as lastname");break;
case RegisterActivity.SAMEPASSFIRST:
errorText.setText("password should not be the same as firstname");
Log.i(TAG, "registerUser(): password same as firstname");break;
case RegisterActivity.SAMEPASSLAST:
errorText.setText("password should not be the same as lastname");
Log.i(TAG, "registerUser(): password same as lastname");break;
case RegisterActivity.SAMEPASSUSER:
errorText.setText("password should not be the same as username");
Log.i(TAG, "registerUser(): password same as username");break;
case RegisterActivity.CPASS_DIFF:
errorText.setText("password and confirm password are not the same");
Log.i(TAG, "registerUser(): password and confirm password not the same");break;
case RegisterActivity.PASSNOTMATCH:
errorText.setText("password format wrong. Password should contain 6-20 characters\n" +
"characters containing at least 1 digit, 1 lower case alphabet and 1 upper case character");
Log.i(TAG, "registerUser(): password format not correct");break;
case RegisterActivity.USERNOTMATCH:
errorText.setText("username format wrong. username should contain 5-20 characters " +
"and should have to special characters");
Log.i(TAG, "registerUser(): username format not correct");break;
default:
Log.i(TAG, "registerUser(): Code not handled");break;
}
}
public String [] getUserInformation()
{
String firstname = firstnameField.getText().toString();
String lastname = lastnameField.getText().toString();
String password = passwordField.getText().toString();
String cpassword = cPasswordField.getText().toString();
String username = usernameField.getText().toString();
String [] input = {firstname, lastname, password, cpassword, username};
return input;
}
public void initializeWatchers()
{
fnameWatcher = new TextWatcher()
{
#Override
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
fname = firstnameField.getText().toString();
fname.trim();
updateButton();
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub
}
#Override
public void onTextChanged(CharSequence s, int start, int before,
int count) {
// TODO Auto-generated method stub
}
};
lnameWatcher = new TextWatcher()
{
#Override
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
lname = lastnameField.getText().toString();
lname.trim();
updateButton();
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub
}
#Override
public void onTextChanged(CharSequence s, int start, int before,
int count) {
// TODO Auto-generated method stub
}
};
pwordWatcher = new TextWatcher()
{
#Override
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
pword = passwordField.getText().toString();
pword.trim();
updateButton();
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub
}
#Override
public void onTextChanged(CharSequence s, int start, int before,
int count) {
// TODO Auto-generated method stub
}
};
cPwordWatcher = new TextWatcher()
{
#Override
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
cPword = cPasswordField.getText().toString();
cPword.trim();
updateButton();
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub
}
#Override
public void onTextChanged(CharSequence s, int start, int before,
int count) {
// TODO Auto-generated method stub
}
};
unameWatcher = new TextWatcher()
{
#Override
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
uname = usernameField.getText().toString();
uname.trim();
updateButton();
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub
}
#Override
public void onTextChanged(CharSequence s, int start, int before,
int count) {
// TODO Auto-generated method stub
}
};
}
public void updateButton()
{
boolean enabled = fname.length()>0 && lname.length()>0 && pword.length()>0
&& cPword.length()>0 && uname.length() >0;
registerButton.setEnabled(enabled);
}
public void registerUser(String [] input)
{
try {
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
Document doc = docBuilder.newDocument();
Element rootElement = doc.createElement("Register");
doc.appendChild(rootElement);
Element user = doc.createElement("user");
rootElement.appendChild(user);
Element firstname = doc.createElement("firstname");
firstname.appendChild(doc.createTextNode(input[0]));
user.appendChild(firstname);
Element lastname = doc.createElement("lastname");
lastname.appendChild(doc.createTextNode(input[1]));
user.appendChild(lastname);
Element password = doc.createElement("password");
password.appendChild(doc.createTextNode(input[2]));
user.appendChild(password);
Element username = doc.createElement("username");
username.appendChild(doc.createTextNode(input[4]));
user.appendChild(username);
StringWriter writer = new StringWriter();
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
transformer.transform(new DOMSource(doc), new StreamResult(writer));
String content = writer.toString();
Message out = new Message(content);
out.setRequest(Event.Request.REGISTER);
os.writeObject(out);
Log.d(TAG, "registerUser(): Register message sent");
} catch (ParserConfigurationException e) {
// TODO Auto-generated catch block
Log.e(TAG, "onActivityReturn(): ParserConfigurationException error", e);
} catch (TransformerException e) {
// TODO Auto-generated catch block
Log.e(TAG, "onActivityReturn(): TransformerException error", e);
} catch (IOException e) {
// TODO Auto-generated catch block
Log.e(TAG, "onActivityReturn(): IOException error", e);
}
}
}
<p>And for my runnable class</p>
package com.dozie.service;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.OptionalDataException;
import android.util.Log;
import com.dcloud.common.Event;
import com.dcloud.common.Message;
public class RegisterWorker implements Runnable{
private ObjectInputStream is;
private Message in;
public static final String TAG = RegisterWorker.class.getName();
public RegisterWorker(ObjectInputStream is)
{
this.is = is;
if(this.is == null)
System.out.println("null");
}
#Override
public void run() {
// TODO Auto-generated method stub
try {
while((in = (Message) is.readObject())!=null)
{
if(in.getResponse() == Event.Response.REQUEST_SUCCESSFUL)
{
Log.d(TAG, "Login Response: "+in.getMessage());
}
else if(in.getResponse() == Event.Response.REQUEST_UNSUCCESSFUL)
{
Log.d(TAG, "Login Response: "+in.getMessage());
//give reason for rejection
}
}
} catch (OptionalDataException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public Message getServerResponse()
{
return in;
}
}
I think the code you're writing is way more complicated than it needs to be. If you want to pass variables to a Thread, which is what I think you're trying to do, just do this:
public Worker extends AsyncTask<Arguments, Void, Void> {
// method names may be slightly incorrect, writing this from memory
public void runInBackground(Arguments...args) {
// do what you want to do in the background
}
}
Then start your thread:
Arguments args = new Arguments(arg1, arg2); // whatever you want to pass along
new Worker().execute(args);
Where Arguments can be any class, using this as an example.
Hope this helps.
Simple way is create a static variable and assign the value to it.
Other Solution is create an object with list of values to be carried between the runnable and activity, and pass this object when creating instance
in your case it may look like
MyObject myObject = null;
public RegisterWorker(ObjectInputStream is, MyObject myObject)
{
this.is = is;
this.myObject=myObject;
if(this.is == null)
System.out.println("null");
}
and when processing is finished you add a method where by you can return the object
so your activity class can call that method and use it for further processing.
public MyObject getMyObject(){
retunr myObject
}
But one more way you can try is, Use AsyncTask. Where by you can mention what to return while creating AsyncTask.