Stop httpConnection blackberry after time - java

i have a problem. I want to stop an httpconnection after x seconds, how can i do that? I thought something like a timertask that executes a httpconnection.close() after x seconds or something like that. Here is my code where i use my connection.
public void run() {
boolean hasCoverage = (RadioInfo.getState() == RadioInfo.STATE_ON)
&& (RadioInfo.getSignalLevel() != RadioInfo.LEVEL_NO_COVERAGE);
if (hasCoverage) {
UiApplication.getUiApplication().invokeLater(new Runnable() {
public void run() {
popup = new MyPopup("Cargando Incidentes...");
UiApplication.getUiApplication().pushModalScreen(popup);
}
});
try {
HttpConnection conn = null;
String URL = "anypage.php";
conn = (HttpConnection) Connector.open(URL);
InputStream contentIn = conn.openInputStream();
byte[] data = new byte[400];
int length = 0;
StringBuffer raw = new StringBuffer();
while (-1 != (length = contentIn.read(data))) {
raw.append(new String(data, 0, length));
str = raw.toString();
}
} catch (Exception e) {
e.printStackTrace();
mainScreen.add(new RichTextField(
"Error ThreadIncidentesConnection: " + e.toString()));
}
UiApplication.getUiApplication().invokeLater(new Runnable() {
public void run() {
try {
String datos[] = mainScreen.split(str, "ENDOFPAGE");
// mainScreen.add(new RichTextField(""+datos[0]));
datos[0] = datos[0].substring(2, datos[0].length());
mainScreen.vecRegistro = mainScreen
.split(datos[0], "$");
mainScreen.insertoEnBd();
mainScreen.insertoEnTablaDatosBD(_act);
UiApplication.getUiApplication().popScreen(popup);
} catch (Exception e) {
e.printStackTrace();
mainScreen.add(new RichTextField(
"Error ThreadIncidentes.run: " + e.toString()));
}
}
});
} else {
mainScreen.add(new RichTextField("No hay conexión disponible."));
}
}

Related

TCP socket in Android

My problem is I have implemented a TCP socket client in android which sends continuously "Hello" messages to the server to maintain a client-server connection and receives messages from the server.
In Android, I have initialized a boolean variable that is controlling the thread if my app is in the background I make the "AppConfig.finished" variable true inactivity on pause and on stop method to stop the socket thread and make it false when in on resume state.
But my app is consuming high CPU usage which is making my app slow, I have checked it in android's profiler. Please help me to optimize it.
The code is given below.
public class MyTcp extends Thread{
private BufferedInputStream inputStream;
private BufferedOutputStream outputStream;
private Socket MySock;
private static SocketStatus SS;
private int ConnectAttemptCount = 0;
private CheckConnectionStatus CheckStatus = null;
public boolean FirstAttempt = true;
public boolean Continue = true;
private boolean isDirectChecked = false;
String tempData = "";
private final ArrayBlockingQueue<String> Queue = new ArrayBlockingQueue<>(100);
public MyTcp(SocketStatus SS) {
MyTcp.SS = SS;
MyTcp.SS.isConnected = false;
setDaemon(true);
Thread t = new Thread(new DequeueMessageThread());
t.setName(SS.SocketName + " DequeqeMessageThread");
t.start();
setName(SS.SocketName);
}
public void Dispose() {
try {
Continue = false;
SS.isConnected = false;
if(inputStream != null) {
inputStream.close();
}
if(outputStream !=null) {
outputStream.close();
}
if(MySock != null) {
MySock.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void run() {
if(!Logs.isFinished) {
try {
while (Continue) {
if (SS.isConnected) {
String fromServer = ReceiveMsg();
if (fromServer.compareTo("") != 0) {
Queue.put(fromServer);
}
ConnectAttemptCount = 0;
} else {
if (ConnectAttemptCount < SS.ConnectAttempt) {
println("run>>" + "Connection Attempt" + ConnectAttemptCount);
ConnectAttemptCount++;
Connect();
} else {
println("run>>" + "Unable To Connect to server");
break;
}
}
}
} catch (Exception e) {
println("run Exception>>" + e);
}
}
}
public void Connect() {
if(!Logs.isFinished) {
try {
if (SS.isDoQueueEmptyOnConnect) {
Queue.clear();
tempData = "";
}
if (FirstAttempt) {
FirstAttempt = false;
} else {
Utilities.println("Trying to connect with " + SS.ServerIP + " on Port " + SS.Port);
_fireStatsEvent(Status.Reconnecting, "Trying to connect with " + SS.ServerIP);
Random generator = new Random();
long wait = (long) generator.nextInt(3000) + 500;
Thread.sleep(wait);
}
MySock = (Socket) AccessController.doPrivileged(new PrivilegedAction() {
public Object run() {
try {
// Start Secure Code
return (new Socket(SS.ServerIP, SS.Port));
// End Secure Code
} catch (Exception e) {
println("Connect Exception>>" + e.toString());
}
return null;
}
});
if (MySock != null) {
SS.isConnected = true;
SocketStatus.MySock = MySock;
inputStream = new BufferedInputStream(MySock.getInputStream());
outputStream = new BufferedOutputStream(MySock.getOutputStream());
Utilities.println("Connection established with " + SS.ServerIP + " on Port " + SS.Port);
if (SocketStatus.EnablePingPong) {
if (CheckStatus != null) {
CheckStatus.Dispose();
}
SS.LastMsgTime = new Date();
CheckStatus = new CheckConnectionStatus(SS, this);
CheckStatus.setName(SS.SocketName + "Connection Status Thread");
CheckStatus.start();
}
}
} catch (Exception e) {
println("Connect>>" + e);
}
int ConnectToIPCount = 0;
if (!SS.isConnected) {
while (!SS.isConnected && ConnectToIPCount < SS.ServerIPList.size()) {
final String IP_ = SS.ServerIPList.get(ConnectToIPCount).toString();
final int Port_ = SS.Port;
println("Connect>>" + "Trying to connect with " + IP_ + " on Port " + Port_);
ConnectToIPCount++;
try {
Thread.sleep(5000);
MySock = (Socket) AccessController.doPrivileged(new PrivilegedAction() {
public Object run() {
try {
// Start Secure Code
if (!isDirectChecked) {
isDirectChecked = true;
Socket tempSock = new Socket(Proxy.NO_PROXY);
tempSock.connect(new InetSocketAddress(IP_, Port_));
return tempSock;
} else {
return (new Socket(IP_, Port_));
}
// End Secure Code
} catch (Exception e) {
println("Connect Exception>>" + e.toString());
}
return null;
}
});
if (MySock != null) {
SocketStatus.MySock = MySock;
SS.isConnected = true;
inputStream = new BufferedInputStream(MySock.getInputStream());
outputStream = new BufferedOutputStream(MySock.getOutputStream());
Utilities.println("Connection established with " + IP_ + " on port " + Port_);
if (SocketStatus.EnablePingPong) {
if (CheckStatus != null) {
CheckStatus.Dispose();
}
SS.LastMsgTime = new Date();
CheckStatus = new CheckConnectionStatus(SS, this);
CheckStatus.setName(SS.SocketName + "Connection Status Thread");
CheckStatus.start();
}
}
} catch (UnknownHostException e) {
println("Connect UnknownHostException>>" + e.toString());
} catch (IOException e) {
println("Connect IOException>>" + e.toString());
} catch (Exception e) {
println("Connect Exception>>" + e.toString());
}
}
}
}
}
public void SendMsg(String sendMsg) {
if(!Logs.isFinished) {
try {
println("SendMsg>>" + sendMsg);
if (MySock != null && MySock.isConnected()) {
try {
byte[] b = null;
b = sendMsg.getBytes();
outputStream.write(b, 0, b.length);
outputStream.flush();
} catch (SocketException | SocketTimeoutException e) {
if (MySock != null) {
MySock.close();
}
SS.isConnected = false;
} catch (Exception e) {
println("SendMsg Exception>>" + e.toString());
}
}
} catch (Exception e) {
Log.d("TCP Client SendMsg >>", "Unable To Connect to server");
}
}
}
public String ReceiveMsg() {
String recvMsg = "";
if(!Logs.isFinished) {
try {
byte[] b = new byte[8092 * 6];
int recvsz = 0;
if (MySock != null && MySock.isConnected()) {
recvsz = inputStream.read(b, 0, b.length);
if (recvsz > 0) {
try {
byte[] b2 = new byte[recvsz];
System.arraycopy(b, 0, b2, 0, b2.length);
recvMsg = (new String(b2));
if (recvMsg.length() > 0) {
SS.LastMsgTime = new Date();
}
} catch (Exception e) {
println("ReceiveMsg Exception>>" + e.toString());
}
}
}
} catch (Exception e) {
if (SS.isConnected) {
Utilities.handleException(e);
}
SS.isConnected = false;
println("ReceiveMsg Exception>>>" + e.toString());
Log.d("RESPONSE FROM SERVER", "S: Received Message: '" + e.toString() + "'");
}
}
return recvMsg;
}
public void println(String msg) {
if (SS.Debug) {
String strDateFormat1 = "HH:mm:ss";
SimpleDateFormat sdf1 = new SimpleDateFormat(strDateFormat1);
Utilities.println(SS.SocketName + " (" + sdf1.format(new Date()) + ") " + msg);
}
}
private final List<MessageRecieveListner> _listeners = new ArrayList<>();
private final List<MessageRecieveListner> _listenersStrength = new ArrayList<>();
public synchronized void addListener(MessageRecieveListner l) {
_listeners.add(l);
_listenersStrength.add(l);
}
private synchronized void _fireMessageEvent(String msg) {
MessageRecieveEvent MsgEvent = new MessageRecieveEvent(this, msg);
for (MessageRecieveListner listener : _listeners) {
listener.MessageRecieved(MsgEvent);
}
}
public synchronized void _fireStatsEvent(Status status, String msg) {
MessageRecieveEvent MsgEvent = new MessageRecieveEvent(this, status, msg);
for (MessageRecieveListner listener : _listeners) {
listener.ConnectionStatus(MsgEvent);
}
}
private class DequeueMessageThread implements Runnable {
public DequeueMessageThread() {
}
#Override
public void run() {
if(!Logs.isFinished) {
while (Continue) {
if (!Queue.isEmpty()) {
try {
String data = Queue.take().trim();
if (SS.MessageParser.length() > 0) {
if (data.lastIndexOf(SS.MessageParser) == data.length() - 1) {
_fireMessageEvent(tempData + data);
tempData = "";
} else {
if (data.indexOf(SS.MessageParser) > 0) {
String particalCompleteData = tempData + data.substring(0, data.lastIndexOf(SS.MessageParser));
tempData = data.substring(data.lastIndexOf(SS.MessageParser) + 1);
_fireMessageEvent(particalCompleteData);
Utilities.println("incomplete data");
}
}
} else {
_fireMessageEvent(data);
}
} catch (Exception ex) {
ex.printStackTrace();
Continue = false;
}
}
}
}
}
}

Bluetooth Printing from Android not working as expected

I have been using the following code to send data to a bluetooth printer:
try {
BluetoothAdapter oBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
BluetoothDevice oDispositivo = oBluetoothAdapter.getRemoteDevice(cMAC);
Method oMethod = oDispositivo.getClass().getMethod("createRfcommSocket",new Class[] { int.class });
oSocket = (BluetoothSocket) oMethod.invoke(oDispositivo, Integer.valueOf(1));
oSocket.connect();
btoutputstream = new BufferedWriter(new OutputStreamWriter(oSocket.getOutputStream(),"ISO_8859_1"));
// Enviamos el mensaje
int off = 0;
while(off < nLength){
btoutputstream.write(msg,off,nBloque);
btoutputstream.flush();
Thread.sleep(nSleep);
off += nBloque;
if((off + nBloque) > nLength) nBloque = nLength - off;
}
btoutputstream.flush();
}catch(Exception e){
return cFail + " || Exception: " + e.toString();
}
finally{
try{
if(btoutputstream != null) btoutputstream.close();
if(oSocket != null) oSocket.close();
}catch(Exception e2){
return e2.toString();
}
}
The problem is that this code is not working on the same printer with a new Bluetooth device. It prints the first block of code and it doesn't print anymore.
So I've been looking for a way to make it work, and I ended up using this:
public static String BluetoothPrint()
{
try{
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
mmDevice = mBluetoothAdapter.getRemoteDevice(cMac);
UUID uuid = UUID.fromString("00001101-0000-1000-8000-00805f9b34fb");
mmSocket = mmDevice.createRfcommSocketToServiceRecord(uuid);
mmSocket.connect();
mmOutputStream = mmSocket.getOutputStream();
mmInputStream = mmSocket.getInputStream();
beginListenForData();
mmOutputStream.write(cText.getBytes());
} catch(Exception e) {
return "error: " + e.toString();
} finally {
// try{
// stopWorker = true;
// mmOutputStream.close();
// mmInputStream.close();
// mmSocket.close();
// } catch(Exception e) {
// return "error: " + e.toString()
// }
}
return "ok";
}
public static void beginListenForData(){
try {
final Handler handler = new Handler();
// This is the ASCII code for a newline character
final byte delimiter = 10;
stopWorker = false;
readBufferPosition = 0;
readBuffer = new byte[1024];
workerThread = new Thread(new Runnable() {
public void run() {
while (!Thread.currentThread().isInterrupted()
&& !stopWorker) {
try {
int bytesAvailable = mmInputStream.available();
if (bytesAvailable > 0) {
byte[] packetBytes = new byte[bytesAvailable];
mmInputStream.read(packetBytes);
for (int i = 0; i < bytesAvailable; i++) {
byte b = packetBytes[i];
if (b == delimiter) {
byte[] encodedBytes = new byte[readBufferPosition];
System.arraycopy(readBuffer, 0,
encodedBytes, 0,
encodedBytes.length);
final String data = new String(
encodedBytes, "US-ASCII");
readBufferPosition = 0;
handler.post(new Runnable() {
public void run() {
//myLabel.setText(data);
}
});
} else {
readBuffer[readBufferPosition++] = b;
}
}
}
} catch (Exception ex) {
stopWorker = true;
}
}
}
});
workerThread.start();
} catch (NullPointerException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
This code is working correct, but my main problem is that the printing is very slow (up to 1:30 min, while before it was printing in 15-20 seconds). I realized that it is going slow because of the empty lines. The printer is slow while printing them, but there's no problem with the lines which have text.
So I'm looking for a way to speed up that code, but I'm stuck. I tried to make the read buffer bigger, but doesn't seem to do nothing.
I've finally managed to get it working properly.
In the text that I was sending to print, the empty lines just had a linebreak (CRLF). As the other ones were printing OK, I tried to add a character on the empty lines (a space, so it prints the same) and it doesn't print slow anymore. I don't know what's the reason of this, but it is working faster, just like before the bluetooth changed.

A long time read body of request to http server with Socket

I'm using socket to create http socket server on Java android application.
Send and Get headers from client and server I'm getting fast. But get when trying read http body it takes a long time... why ?
MainActivity.class
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new Thread(new Runnable() {
public void run() {
try {
runProxy();
}catch (Throwable t){
}
};
}).start();
}
private void runProxy() throws Throwable{
try {
ServerSocket ss = new ServerSocket(8080);
while (true) {
Socket s = ss.accept();
System.err.println("Client accepted");
new Thread(new TestProxy(s)).start();
}
}catch (IOException e){
}
}
TestProxy.class
public class TestProxy implements Runnable{
private Socket s, c;
private InputStream is;
private OutputStream os;
ArrayList<String> requestList;
ArrayList<String> responseList;
private BufferedReader br;
public TestProxy(Socket s) throws Throwable{
this.s = s;
this.is = s.getInputStream();
this.os = s.getOutputStream();
this.requestList = new ArrayList<String>();
this.responseList = new ArrayList<String>();
this.run();
}
public void run(){
try {
this.readRequest();
this.forwardRequest();
this.forwardResponse(); //<--- this is trouble ??!
}catch (Throwable e){
}finally {
/*try {
s.close();
c.close();
}catch (IOException e) {}*/
}
}
private void readRequest() throws Throwable{
BufferedReader br = new BufferedReader(new InputStreamReader(is));
//int lengthBody = 0;
while(true) {
String s = br.readLine();
requestList.add(s + "\r\n");
/*if (s.startsWith("Content-Length: ")) { // get the
// content-length
int index = s.indexOf(':') + 1;
String len = s.substring(index).trim();
lengthBody = Integer.parseInt(len);
}*/
if(s == null || s.trim().length() == 0) {
break;
}
}
is.close();
}
private void forwardRequest(){
String firstSectionInProtocol = requestList.get(0); //GET http://example.com/?d=d HTTP/1.1
Pattern p = Pattern.compile("^\\w+\\s+(\\S+)");
Matcher m = p.matcher(firstSectionInProtocol);
if(m.find()) {
String URI = m.group(1); //http://example.com/?d=d
try {
URL aURL = new URL(URI);
try {
c = new Socket(aURL.getHost(), 80);
final OutputStream outToServer = c.getOutputStream();
String firstSection = "GET "+aURL.getFile()+" HTTP/1.1\r\n";
outToServer.write(firstSection.getBytes());
System.out.println(firstSection);
for(int i = 1; i < requestList.size(); i++){
outToServer.write(requestList.get(i).getBytes());
System.out.println(requestList.get(i));
}
outToServer.flush();
}catch (IOException e) {
}
}catch (MalformedURLException e){ }
}
}
private void forwardResponse() throws Throwable{
final InputStream inFromServer = c.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(inFromServer));
int lengthBody = 0;
while(true) {
String s = br.readLine();
System.out.println( s + "\r\n" );
if (s.startsWith("Content-Length: ")) { // get the
// content-length
int index = s.indexOf(':') + 1;
String len = s.substring(index).trim();
lengthBody = Integer.parseInt(len);
}
if(s.equals("")) {
break;
}
}
//
// Processing long time
//
if (lengthBody > 0) {
int read;
StringBuilder body = new StringBuilder();
while ((read = br.read()) != -1) {
body.append((char) read);
if (body.length() >= lengthBody)
break;
}
System.out.println(body.toString());
}
}
}
in the method forwardResponse(); i trying get a body response.
while(true) {
String s = br.readLine();
System.out.println( s + "\r\n" );
/*if (s.startsWith("Content-Length: ")) { // get the
// content-length
int index = s.indexOf(':') + 1;
String len = s.substring(index).trim();
lengthBody = Integer.parseInt(len);
}*/
if(s == null) {
break;
}
}

How to transmit of stream of data to multiple devices using sockets in Android?

I am trying to transmit a continuous stream of data to multiple devices over a portable hotspot connection using sockets.
I am facing two problems:
The message only gets displayed to the client AFTER all the messages are displayed in msg TextView on the server end. So if I use an infinite while(true) loop instead of for(int i = 0; i < 1000; i++), in ServerSocketReplyThread, the message never gets transmitted, and the client eventually crashes
I am unable to connect another client to the server until all the messages have been transmitted to the first client.
How do I structure the code to ensure simultaneous, real-time transmission to multiple clients?
Here's what the code looks like:
I am using an activity called Transmit activity, where I am instantiating the msg Textview, which replays the sent messages, and a server object.
msg = (TextView) findViewById(R.id.server_replayed_messages);
Server server = new Server(this);
The Server class is as follows:
public class Server {
TransmitActivity activity;
ServerSocket serverSocket;
String message = "";
static final int socketServerPORT = 8080;
ArrayList<Socket> socketList = new ArrayList<Socket>();
public Server(TransmitActivity a) {
this.activity = a;
Thread socketServerThread = new Thread(new SocketServerThread());
socketServerThread.start();
}
public int getPort() {
return socketServerPORT;
}
public void onDestroy() {
if (serverSocket != null) {
try {
serverSocket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
private class SocketServerThread extends Thread {
int count = 0;
#Override
public void run() {
try {
// create ServerSocket using specified port
serverSocket = new ServerSocket(socketServerPORT);
while (true) {
// block the call until connection is created and return
// Socket object
Socket socket = serverSocket.accept();
count++;
message += "#" + count + " from "
+ socket.getInetAddress() + ":"
+ socket.getPort() + "\n";
activity.runOnUiThread(new Runnable() {
#Override
public void run() {
activity.msg.setText(message);
}
});
SocketServerReplyThread socketServerReplyThread =
new SocketServerReplyThread(socket, count);
socketServerReplyThread.run();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
private class SocketServerReplyThread extends Thread {
private Socket hostThreadSocket;
int cnt;
SocketServerReplyThread(Socket socket, int c) {
hostThreadSocket = socket;
cnt = c;
}
#Override
public void run() {
OutputStream outputStream;
for(int i = 0; i < 1000; i++) {
String msgReply = DateFormat.getDateTimeInstance().format(new Date());
try {
outputStream = hostThreadSocket.getOutputStream();
PrintStream printStream = new PrintStream(outputStream);
printStream.print(msgReply);
printStream.flush();
message += "replayed: " + msgReply + "\n";
activity.runOnUiThread(new Runnable() {
#Override
public void run() {
activity.msg.setText(message);
}
});
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
message += "Something wrong in SocketServerReplyThread! " + e.toString() + "\n";
}
activity.runOnUiThread(new Runnable() {
#Override
public void run() {
activity.msg.setText(message);
}
});
}
}
}
}
On the client side I have a ReceiveActivity, where I am using the following code when a "Connect" button is clicked:
Client myClient = new Client(editTextAddress.getText()
.toString(), Integer.parseInt(editTextPort
.getText().toString()), response);
myClient.execute();
The Client class is as follows:
public class Client extends AsyncTask<Void, Void, Void> {
String dstAddress;
int dstPort;
String response = "";
TextView textResponse;
Client(String addr, int port, TextView textResponse) {
dstAddress = addr;
dstPort = port;
this.textResponse = textResponse;
}
#Override
protected Void doInBackground(Void... arg0) {
Socket socket = null;
try {
socket = new Socket(dstAddress, dstPort);
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(1024);
byte[] buffer = new byte[1024];
int bytesRead;
InputStream inputStream = socket.getInputStream();
/*
* notice: inputStream.read() will block if no data return
*/
while ((bytesRead = inputStream.read(buffer)) != -1) {
byteArrayOutputStream.write(buffer, 0, bytesRead);
response += byteArrayOutputStream.toString("UTF-8");
}
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
response = "UnknownHostException: " + e.toString();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
response = "IOException: " + e.toString();
} finally {
if (socket != null) {
try {
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
return null;
}
#Override
protected void onPostExecute(Void result) {
textResponse.setText(response);
super.onPostExecute(result);
}
}
Any help would be much appreciated.

Android UI from other thread

I'm creating an application that gets the get the homestatus from a server in json but this happens on another thread. this isn't a problem when i try to set most Items on the ui because i can set them in a static void. but when i try to create a new switch and space i can't call 'this' to create a new.
code for getting the homestatus:
public void loadHomeStatus()
{
if(socket != null) {`enter code here`
if (socket.isConnected()) {
Log.d("BtnUpdate","already connected");
return;
}
}
swAlarm = (Switch) findViewById(R.id.swAlarmState);
tvTemperature = (TextView) findViewById(R.id.tvTemprateur);
tvHumidity = (TextView) findViewById(R.id.tvHumidity);
llDevices = (LinearLayout) findViewById(R.id.llDevices);
new Thread() {
public void run() {
try
{
busyConnecting = true;
Log.d("loadHomeStatus","trying to connect to: " + host + ":" + port);
socket = new Socket(host, port);
uiConnected();
Log.d("loadHomeStatus","Connected");
DataOutputStream os = new DataOutputStream(socket.getOutputStream());
DataInputStream is = new DataInputStream(socket.getInputStream());
os.writeBytes(password);
Log.d("Connect", "send: " + password);
while (socket.isConnected()) {
byte[] data = new byte[500];
int count = is.read(data);
String recieved = new String(data).trim();
Log.d("loadHomeStatus","recieved " + recieved );
if(recieved.toLowerCase() == "failed")
{
Log.d("loadHomeStatus","failed to log in");
}
else
{
try
{
homeStatus = new Gson().fromJson(recieved, HomeStatus.class);
uiLoadStatus();
} catch (Exception e)
{
Log.d("Error", e.toString());
}
}
}//end of while loop
Log.w("loadHomeStatus", "end connection thread ");
//ends thread
Thread.currentThread().interrupt();
return;
}
catch (UnknownHostException e)
{
e.printStackTrace();
Log.w("loadHomeStatus", "no Failed to connect: " + host + "-" + 8001);
}
catch (IOException e)
{
e.printStackTrace();
Log.w("loadHomeStatus", "no Failed to connect: " + host + "-" + 8001);
}
Log.w("loadHomeStatus","Connection ended");
socket = null;
busyConnecting = false;
uiDisconnected();
}
}.start();
}`
Code for setting ui
public static void uiLoadStatus()
{
if (homeStatus != null)
{
try {
tvTemperature.post(new Runnable()
{
public void run()
{
//Log.d("uiLoadStatus to string",homeStatus.toString());
tvTemperature.setText(homeStatus.temperature + "°C");
tvHumidity.setText(homeStatus.humidity + "%");
}
});
}
catch(Exception e)
{
Log.d("uiLoadStatus status fragment", e.toString());
}
try {
swAlarm.post(new Runnable()
{
public void run() {
swAlarm.setChecked(homeStatus.alarmState);
}
});
}
catch (Exception e)
{
Log.d("uiLoadStatus alarm fragment", e.toString());
}
}
try {
llDevices.post(new Runnable()
{
public void run() {
uiLoadDevices(); //this gives and error because it's not static
}
});
}
catch (Exception e)
{
Log.d("uiLoadStatus alarm fragment", e.toString());
}
}
public void uiLoadDevices()
{
for (int i = 0; i < homeStatus.lstDevices.size(); i++) {
String deviceAdd = homeStatus.lstDevices.get(i);
Space mySpace = new Space(this);
Switch mySwitch = new Switch(this);
mySpace.setMinimumHeight(50);
mySwitch.setText(homeStatus.getName(deviceAdd));
mySwitch.setChecked(homeStatus.getState(deviceAdd));
mySwitch.setTextSize(18);
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
lp.gravity = Gravity.LEFT;
llDevices.addView(mySpace, lp);
llDevices.addView(mySwitch, lp);
}
}
You should use AsyncTask and put the network interaction part in the doInBackground() method. To update the UI components, implement those logics in the onPostExecute() method
uiLoadStatus is a static method (not sure why or if it has to be without looking at all of your code) and therefore you cannot call non-static methods from within it, such as uiLoadDevices
I would advise taking a look at your code and update your uiLoadStatus to not be static if at all possible. Abusing static can lead to sloppy code.

Categories

Resources