I am trying to receive images over a network, I set up a server as follows
public class IServerActivity extends Activity {
ServerSocket ss = null;
Bitmap bp ;
Thread myCommsThread = null;
protected static final int MSG_ID = 0x1337;
public static final int SERVERPORT = 6000;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//TextView tv = (TextView) findViewById(R.id.TextView01);
this.myCommsThread = new Thread(new CommsThread());
this.myCommsThread.start();
}
#Override
protected void onStop() {
super.onStop();
try {
// make sure you close the socket upon exiting
ss.close();
} catch (IOException e) {
e.printStackTrace();
}
}
Handler myUpdateHandler = new Handler() {
public void handleMessage(Message msg) {
switch (msg.what) {
case MSG_ID:
ImageView iv = (ImageView) findViewById(R.id.imageView01);
iv.setImageBitmap(bp);;
break;
default:
break;
}
super.handleMessage(msg);
}
};
class CommsThread implements Runnable {
public void run() {
Socket s = null;
try {
ss = new ServerSocket(SERVERPORT );
} catch (IOException e) {
e.printStackTrace();
}
while (!Thread.currentThread().isInterrupted()) {
Message m = new Message();
m.what = MSG_ID;
try {
if (s == null)
s = ss.accept();
bp= BitmapFactory.decodeStream(s.getInputStream());
myUpdateHandler.sendMessage(m);
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
But it shows an error at runtime
java.lang.NullPointerException
E/AndroidRuntime(3047):atExample.IServer.IServerActivity$CommsThread.run(IServerActivity.java:68)
It shows null pointer exception at s=ss.accept(); line.
please help I don't know what is going wrong.
If you are getting a null pointer exception at that line, it can only mean that the earlier:
ss = new ServerSocket(SERVERPORT );
statement did not return normally. That is the only plausible way that ss could be null.
(Actually, there is one other possible explanation. Since the ss variable is package private and not final, some other class in the same package could reach in and assign null to it. But I wouldn't think that was plausible. Why would anyone write code to do that?)
Related
I'm trying to run a UDP connection with external equipment. I want it to send a message to the equipment every 3 second and read the response.
I created 3 classes: main, sender and receive.
I open a Runnable for both sender and receive and let them sleep for 3 seconds before continue.
My problem is, when i push the button on the screen, the messages are send and received, however they are not updated on my screen because the update line is not in a loop. How do i tell it to update the screen every 3 second? the code for reading the message and show it, is this:
textViewState.setText(udpReceive.receivedMessage);
Code
public class MainActivity extends AppCompatActivity {
public static TextView textViewState;
public static Context context;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textViewState = (TextView) findViewById(R.id.textView);
context = getApplicationContext();
}
public void buttonConnect(View v) {
(new Thread(new udpSender())).start();
(new Thread(new udpReceive())).start();
textViewState.setText(udpReceive.receivedMessage);
}
}
Class to send a message:
public class udpSender implements Runnable {
public void run() {
while (true) {
String messageStr = "Hello Android!";
int server_port = 8888;
DatagramSocket s = null;
try {
s = new DatagramSocket();
} catch (SocketException e) {
e.printStackTrace();
}
InetAddress local = null;
try {
local = InetAddress.getByName("192.168.43.159");
} catch (UnknownHostException e) {
e.printStackTrace();
}
int msg_length = messageStr.length();
byte[] message = messageStr.getBytes();
DatagramPacket p = new DatagramPacket(message, msg_length, local, server_port);
try {
s.send(p);
} catch (IOException e) {
e.printStackTrace();
}
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
Class to receive message from udp
public class udpReceive implements Runnable {
private static final int MAX_UDP_DATAGRAM_LEN = 100;
private static final int UDP_SERVER_PORT = 8888;
public static String receivedMessage;
public void run() {
while (true) {
String message;
byte[] lmessage = null;
lmessage = new byte[MAX_UDP_DATAGRAM_LEN];
DatagramPacket packet = null;
DatagramSocket socket = null;
try {
packet = new DatagramPacket(lmessage, lmessage.length);
socket = new DatagramSocket(UDP_SERVER_PORT);
socket.receive(packet);
message = new String(lmessage, 0, packet.getLength());
receivedMessage = message;
} catch (SocketException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (socket != null) {
socket.close();
}
}
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
In any class that is in another thread, try doing this
Handler handler = new Handler(getActivity().getMainLooper());
handler.post(new Runnable(){
// your TextView goes here
})
Only the UI thread (main thread) can access UI elements
// Your message receiving class
...
message = new String(lmessage, 0, packet.getLength());
final String message_received = new String(lmessage, 0, packet.getLength());
...
MainActivity.context.runOnUiThread(new Runnable() {
#Override
public void run() {
MainActivity.textViewState.setText(message_received);
}
});
...
I found a solution based on both of your answers :) Thank you
MainActivity class:
public static Handler UIHandler;
static {
UIHandler = new Handler(Looper.getMainLooper());
}
public static void runOnUI(Runnable runnable) {
UIHandler.post(runnable);
}
receive class
MainActivity.runOnUI(new Runnable() {
public void run() {
MainActivity.textViewState.setText(message_received);
}
});
I am creating an android application in which i am creating socket connection in one activity and using Shared Preferences and in another activity I am fetching the socket variables to do furthur jobs but its not working as i am expected
My question is how can i use my exixting socket connection in different actvities i have searched about it Got some terms like singltone class,Aysnc task, But i am not getting it,if singltone is proper way to use socket connetion in different activities then How can i use singlton class in following code please suggest me changes...!!!
Otherwise is it proper way am i doing Shared PRef as following??also suggest some changes!!!
UPDATE: Tagged singlton for suggestions
So here is First Activity
public class ipInfo extends AppCompatActivity {
EditText ipaddress;
String IPADD;
Integer PORT=null;
EditText portnum;
Button connect_btn;
StrictMode.ThreadPolicy policy;
Socket cs = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_ipinfo);
policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
ipaddress = (EditText)findViewById(R.id.editText);
portnum = (EditText)findViewById(R.id.editText2);
connect_btn =(Button)findViewById(R.id.button);
ip_check();
}
public void ip_check(){
connect_btn.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
IPADD=ipaddress.getText().toString();
PORT=Integer.parseInt(portnum.getText().toString());
try { cs = new Socket();
cs.connect(new InetSocketAddress(IPADD, PORT), 2000);
SharedPreferences sharedPreferences = getSharedPreferences("ipstore", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("ipadd",IPADD);
editor.putInt("port",PORT);
editor.commit();
if(cs.isConnected()) {
Toast.makeText(ipInfo.this, "Connected", Toast.LENGTH_SHORT).show();
Intent inst = new Intent(ipInfo.this,homeActivity.class);
startActivity(inst);
finish();
}
}catch (IOException e)
{Toast.makeText(ipInfo.this,"Server is disconnected\n",Toast.LENGTH_SHORT).show();
}catch (Exception e)
{Toast.makeText(ipInfo.this,e.getMessage(),Toast.LENGTH_SHORT).show();}
}
}
);
}
}
from this activity am fetching values in following activity
public class PowerActivity extends AppCompatActivity {
Button restart,shutdown,logof,sleep,abort;
StrictMode.ThreadPolicy policy;
Socket cs = null;
DataOutputStream out=null;
String SERVERIP;
int PORT;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_power);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
restart = (Button)findViewById(R.id.restart);
shutdown = (Button)findViewById(R.id.shutdown);
logof = (Button)findViewById(R.id.logof);
sleep = (Button)findViewById(R.id.sleep);
abort = (Button)findViewById(R.id.abort);
SharedPreferences sharedPreferences=getSharedPreferences("ipstore", Context.MODE_PRIVATE);
SERVERIP =sharedPreferences.getString("ipadd","");
PORT=sharedPreferences.getInt("port", 8002);
Toast.makeText(this,"Working"+SERVERIP+"\n"+PORT,Toast.LENGTH_LONG).show();//this line working fine
policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
remotecmnd();
}
public void remotecmnd(){
restart.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
//restart code
try{
cs = new Socket(SERVERIP,PORT);
try{
out = new DataOutputStream(cs.getOutputStream());
out.writeUTF("restart");
Toast.makeText(PowerActivity.this, "RESTART SUCCESS", Toast.LENGTH_LONG).show();
} catch (Exception ea) {
Toast.makeText(PowerActivity.this, ea.getMessage(), Toast.LENGTH_LONG).show();
}
}catch (IOException e) {
Toast.makeText(PowerActivity.this, e.getMessage(), Toast.LENGTH_LONG).show();
}
}
}
);
}
}
here is server part code
public class serverbackend extends Thread implements Runnable{
public static int SERVERPORT = 8002;
public boolean running = false;
public volatile boolean stop = false;
public Socket client = null;
ServerSocket sc = null;
String value;
public static void main(String[] args) {
mwcobj = new MainWindowController();
}
#Override
public void run() {
super.run();
running = true;
try {
System.out.println("Server Has Started........ \nWaiting for client........");
sc = new ServerSocket(SERVERPORT);
try {
while (!stop && running) {
client = sc.accept();
System.out.println("Connection Accepted......");
DataInputStream dis = new DataInputStream(client.getInputStream());
value = dis.readUTF();
switch (value) {
//Restart the system
case "restart":
System.out.println("Restarting");
Runtime.getRuntime().exec("shutdown -r -t 10");
break;
//some extra code
default:
break;
}
}
} catch (IOException e) {
System.out.println("Inner try catch "+e.getMessage());
}
} catch (IOException e) {
System.out.println("Final try catch error "+e.getMessage());
}
}
public void requestStop(){
try{
stop = true;
sc.close();
System.out.println("Server Has Stopped");
}catch(IOException e){System.out.println("Server Stopped "+e.getMessage());}
}
}
In my opinion, I created a bluetooth communication app,where I get the same problem,
The answer for the this is to use getter and setter methods. It is very easy to set socket and get socket from other java class rather than sending across activities , If I came across other methods I will definitely will tell you on that..
Using getter setter will work for you I beleive.
public class getset
{
static BluetoothSocket sock;
getset(BluetoothSocket sock)
{
this.sock=sock;
}
public static synchronized BluetoothSocket getSock() {
return sock;
}
public static synchronized void setSock(BluetoothSocket sock) {
getset.sock = sock;
}
}
In the place of using shared preference
setSock(socket); //socket is the Bluetoothsocket which you have to save
Bluetoothsocket socket=getSock(); // to get value from the socket
refer https://teamtreehouse.com/community/how-do-you-add-getters-and-setter-in-android-java
my ListeningThread is freezing the UI thread of the Barometer activity although it shouldn't. I have no idea why this is happening. Help needed :)
This is my ListeningThread:
public class ListeningThread extends Thread {
String TAG = "bluetoothThread";
private final BluetoothServerSocket bluetoothServerSocket;
BluetoothAdapter bl;
public ListeningThread(BluetoothAdapter bluetoothAdapter, String appName) {
BluetoothServerSocket temp = null;
bl = bluetoothAdapter;
try {
temp = bluetoothAdapter.listenUsingRfcommWithServiceRecord(appName, Constants.MY_UUID_SECURE);
} catch (IOException e) {
e.printStackTrace();
}
bluetoothServerSocket = temp;
}
public void start() {
Log.d(TAG, "ListeningThread running");
BluetoothSocket bluetoothSocket;
//This will block while listening until a BluetoothSocket is returned or an exception occurs
while (true) {
try {
bluetoothSocket = bluetoothServerSocket.accept();
Log.d(TAG, "ListeningThread connected");
} catch (IOException e) {
break;
}
// If a connection is accepted
if (bluetoothSocket != null) {
// Manage the connection in a separate thread
try {
bluetoothServerSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
break;
}
}
}
// Cancel the listening socket and terminate the thread
public void cancel() {
try {
bluetoothServerSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
And this is the activity using the thread and freezing:
public class BarometerActivity extends AppCompatActivity {
BluetoothAdapter bluetoothAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_barometer);
if (SingletonBluetoothAdapter.bluetoothAdapter == null) {
SingletonBluetoothAdapter.bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
}
bluetoothAdapter = SingletonBluetoothAdapter.bluetoothAdapter;
ListeningThread t = new ListeningThread(bluetoothAdapter, getString(R.string.app_name));
t.start();
}
}
I am sure the problem is somewhere in the run-method of the thread. I tried to surround this method with a comment and then everything runs fine.
You should put the while(true) code inside the method public void run(). Not in the public void start() as documented here https://docs.oracle.com/javase/tutorial/essential/concurrency/runthread.html
On the MainActivity.java I have a method that connect with a server:
private byte[] Get(String urlIn)
{
URL url = null;
String urlStr = urlIn;
if (urlIn!=null)
urlStr=urlIn;
try
{
url = new URL(urlStr);
} catch (MalformedURLException e)
{
e.printStackTrace();
return null;
}
HttpURLConnection urlConnection = null;
try
{
urlConnection = (HttpURLConnection) url.openConnection();
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
byte[] buf=new byte[10*1024];
int szRead = in.read(buf);
byte[] bufOut;
if (szRead==10*1024)
{
throw new AndroidRuntimeException("the returned data is bigger than 10*1024.. we don't handle it..");
}
else
{
bufOut = Arrays.copyOf(buf, szRead);
}
return bufOut;
}
catch (IOException e)
{
e.printStackTrace();
return null;
}
finally
{
if (urlConnection!=null)
urlConnection.disconnect();
}
}
I'm calling this method from onTouchEvent():
#Override
public boolean onTouchEvent(MotionEvent event)
{
float eventX = event.getX();
float eventY = event.getY();
float lastdownx = 0;
float lastdowny = 0;
switch (event.getAction())
{
case MotionEvent.ACTION_DOWN:
path.moveTo(eventX, eventY);
circlePath.addCircle(eventX, eventY, 50, Path.Direction.CW);
lastdownx = eventX;
lastdowny = eventY;
Thread t = new Thread(new Runnable()
{
#Override
public void run()
{
byte[] response = null;
if (is_start == true)
{
response = Get("http://10.0.0.2:8098/?cmd=start");
is_start = false;
}
else
{
response = Get("http://10.0.0.2:8098/?cmd=stop");
is_start = true;
}
if (response!=null)
{
String a = null;
try
{
a = new String(response,"UTF-8");
textforthespeacch = a;
MainActivity.currentActivity.initTTS();
} catch (UnsupportedEncodingException e)
{
e.printStackTrace();
}
Logger.getLogger("MainActivity(inside thread)").info(a);
}
}
});
t.start();
return true;
case MotionEvent.ACTION_MOVE:
path.lineTo(eventX, eventY);
break;
case MotionEvent.ACTION_UP:
circlePath.reset();
break;
default:
return false;
}
invalidate();
return true;
}
So now i'm connecting all the time to 10.0.0.2:8098
But that's when i connect my android device on my network on my pc room.
But if i move to the living room and connect to the network there a differenet network with another pc the pc ip is differenet in this case: 10.0.0.3:8099
So i added a button click event to the MainActivity.java:
public class MainActivity extends ActionBarActivity
{
private static final int MY_DATA_CHECK_CODE = 0;
public static MainActivity currentActivity;
TextToSpeech mTts;
private String targetURL;
private String urlParameters;
private Button btnClick;
private String clicking = "clicked";
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
addListenerOnButton();
currentActivity = this;
initTTS();
}
public void addListenerOnButton() {
btnClick = (Button) findViewById(R.id.checkipbutton);
btnClick.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View arg0)
{
}
});
}
Inside the button click event I want to check after connected to the network with a wifi if the pc ip is 10.0.0.3:8099 or 10.0.0.2:8098
I need that it will try to connect to this servers and if success then to set to a global variable global string the ip.
I added a global variable: string ipaddress
Now i use static address in my code but i need to check which ip address is correct and then to set this ip to the variable which i will use later in my code as the ip address.
How do I make the checking in the button click event ?
This is what i tried now:
At the top of my MainActivity i added:
private final String[] ipaddresses = new String[2];
private final Integer[] ipports = new Integer[2];
Socket socket = null;
Then in the onCreate:
ipaddresses[0] = "10.0.0.3";
ipaddresses[1] = "10.0.0.2";
ipports[0] = 8098;
ipports[1] = 8088;
addListenerOnButton();
new Thread(new ClientThread()).start();
Then
public void addListenerOnButton() {
btnClick = (Button) findViewById(R.id.checkipbutton);
btnClick.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View arg0)
{
try {
String str = btnClick.getText().toString();
PrintWriter out = new PrintWriter(new BufferedWriter(
new OutputStreamWriter(socket.getOutputStream())),
true);
out.println(str);
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
And the ClientThread
class ClientThread implements Runnable {
#Override
public void run() {
for (int i=0; i<ipaddresses.length; i++)
{
try
{
InetAddress serverAddr = InetAddress.getByName(ipaddresses[i]);
socket = new Socket(serverAddr, ipports[i]);
} catch (UnknownHostException e1)
{
e1.printStackTrace();
} catch (IOException e1)
{
e1.printStackTrace();
}
}
}
}
This is a screenshot of the exception message i'm getting:
The exception is on the line:
new OutputStreamWriter(socket.getOutputStream())),
You must open sockets to check server connectivity. Here is an example on you send strings to server on click event:
public class Client extends Activity {
private Socket socket;
private static final int SERVERPORT = 8099;
private static final String SERVER_IP = "10.0.0.3";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
new Thread(new ClientThread()).start();
}
public void onClick(View view) {
try {
EditText et = (EditText) findViewById(R.id.EditText01);
String str = et.getText().toString();
PrintWriter out = new PrintWriter(new BufferedWriter(
new OutputStreamWriter(socket.getOutputStream())),
true);
out.println(str);
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
class ClientThread implements Runnable {
#Override
public void run() {
try {
InetAddress serverAddr = InetAddress.getByName(SERVER_IP);
socket = new Socket(serverAddr, SERVERPORT);
} catch (UnknownHostException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
}
So if you get an exception trying to connect to server, it means you haven't connectivity.
I'm working on an android Quiz app with connection to a server over a socket. On the client side (Android device) I check in a while loop the answers which are given by a server (Java server). The connection and the receiving of the answer all goes good. The problem is that in my class to check for answers there's a bug. To give more information I will include a part of the code here:
public void startClient(){
checkValue = new Thread(new Runnable(){
#Override
public void run() {
try
{
final int PORT = 4444;
final String HOST = "192.168.1.118";
Socket SOCK = new Socket(HOST, PORT);
Log.e("success", "You connected to: " + HOST);
quizClient = new QuizClient(SOCK);
//Send the groupname to the list
PrintWriter OUT = new PrintWriter(SOCK.getOutputStream());
OUT.println(groupName);
OUT.flush();
Thread X = new Thread(quizClient);
X.start();
connected = true;
}
catch(Exception X)
{
Log.e("connection error", "Error: ", X);
}
}
});
checkValue.start();
}
public void testvalue(){
Thread thread = new Thread(new Runnable(){
#Override
public void run() {
try {
while(true){
if(message != null && !message.matches("")){
Thread.sleep(1000);
Log.e("receive", message);
buffer = message;
message = "";
Message msg = new Message();
String textTochange = buffer;
msg.obj = textTochange;
mHandler.sendMessage(msg);
Thread.sleep(3000);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
});
thread.start();
}
Handler mHandler = new Handler() {
#Override
public void handleMessage(Message msg) {
String text = (String)msg.obj;
//call setText here
//String[] myStringArray = new String[];
value.clear();
String[] items = text.split(";");
for (String item : items)
{
value.add(item);
Log.e("message", item);
//System.out.println("item = " + item);
}
if(value.get(0).equals("1")){
questionGroup.setVisibility(View.INVISIBLE);
sendAnswer.setVisibility(View.INVISIBLE);
answer.setVisibility(View.INVISIBLE);
question.setText("");
question.setText(value.get(2));
rad1.setText(value.get(3));
rad2.setText(value.get(4));
rad3.setText(value.get(5));
rad4.setText(value.get(6));
questionGroup.setVisibility(View.VISIBLE);
sendAnswer.setVisibility(View.VISIBLE);
} else if (value.get(0).equals("2")){
questionGroup.setVisibility(View.INVISIBLE);
sendAnswer.setVisibility(View.INVISIBLE);
answer.setVisibility(View.INVISIBLE);
question.setText("");
question.setText(value.get(2));
answer.setVisibility(View.VISIBLE);
sendAnswer.setVisibility(View.VISIBLE);
} else
{
questionGroup.setVisibility(View.INVISIBLE);
sendAnswer.setVisibility(View.INVISIBLE);
answer.setVisibility(View.INVISIBLE);
question.setText(text);
}
}
};
#Override
protected void onStop()
{
if (connected == true){
try {
quizClient.DISCONNECT();
} catch (IOException e) {
e.printStackTrace();
}
}
if(checkValue != null)
{
checkValue.interrupt();
}
super.onStop();
closeApplication();
}
So I make a new instance of this class (where I actually check the incoming stream of data)
public class QuizClient implements Runnable {
//Globals
Socket SOCK;
Scanner INPUT;
Scanner SEND = new Scanner(System.in);
PrintWriter OUT;
public QuizClient(Socket X)
{
this.SOCK = X;
}
public void run()
{
try
{
try
{
INPUT = new Scanner(SOCK.getInputStream());
OUT = new PrintWriter(SOCK.getOutputStream());
OUT.flush();
CheckStream();
}
finally
{
SOCK.close();
}
}
catch(Exception X)
{
Log.e("error", "error: ", X);
}
}
public void DISCONNECT() throws IOException
{
OUT.println("DISCONNECT");
OUT.flush();
SOCK.close();
}
public void CheckStream()
{
while(true)
{
RECEIVE();
}
}
public void RECEIVE()
{
if(INPUT.hasNext())
{
String MESSAGE = INPUT.nextLine();
if(MESSAGE.contains("#?!"))
{
}
else
{
QuizActivity.message = MESSAGE;
Log.e("test", MESSAGE);
}
}
}
public void SEND(String X)
{
OUT.println(X);
OUT.flush();
}
}
So the bug persist I think in the following class:
public void testvalue(){
Thread thread = new Thread(new Runnable(){
#Override
public void run() {
try {
while(true){
if(message != null && !message.matches("")){
Thread.sleep(1000);
Log.e("receive", message);
buffer = message;
message = "";
What I do here is make a thread and check if the "message" is not equals at null. The message come from the other class:
public void RECEIVE()
{
if(INPUT.hasNext())
{
String MESSAGE = INPUT.nextLine();
if(MESSAGE.contains("#?!"))
{
}
else
{
QuizActivity.message = MESSAGE;
Now most of the time this works good but there are 2 problems. When I go out of the page it disconnect from the server (works) I go back on the page and connect again to the server but this time I don't get any values on the screen (receiving is okj but for one of the other reason it does not go good in my handler). Also get an indexoutofboundexception after a time:
question.setText(value.get(2));
A second problem occurs some time while the program runs. There are moments that I also don't get a value on my interface while it correctly receive the input.
So my guess is that my solution of the thread to read in the values is not the best way to handle it. So now I ask to people with more experience what I can do to make this work without major problems? You need to know the connection works and I get the value in my QuizClient class. So the problem need to be in my main class.
My oncreate class:
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_quiz);
selectgroep = (Spinner) findViewById(R.id.groepen);
questionGroup = (RadioGroup) findViewById(R.id.QuestionGroup);
sendAnswer = (Button) findViewById(R.id.sendAnswer);
rad1 = (RadioButton) findViewById(R.id.radio0);
rad2 = (RadioButton) findViewById(R.id.radio1);
rad3 = (RadioButton) findViewById(R.id.radio2);
rad4 = (RadioButton) findViewById(R.id.radio3);
answer = (EditText) findViewById(R.id.textanswer);
questionGroup.setVisibility(View.INVISIBLE);
sendAnswer.setVisibility(View.INVISIBLE);
answer.setVisibility(View.INVISIBLE);
try {
connect();
} catch (InterruptedException e) {
e.printStackTrace();
}
//Code na het drukken op de knop
startserver = (Button) findViewById(R.id.startserver);
startserver.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
startClient();
getID();
testvalue();
}
});
sendAnswer.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// Stuur antwoord door en sluit alles af
questionGroup.setVisibility(View.INVISIBLE);
sendAnswer.setVisibility(View.INVISIBLE);
answer.setVisibility(View.INVISIBLE);
answer.setText("");
rad1.setChecked(true);
rad1.setText("");
rad2.setText("");
rad3.setText("");
rad4.setText("");
question.setText("Wachten op server ... ");
}
});
}
Thank you in advance,
Thomas Thooft