You need to throw in the exception that you get in order to force the force to close before anyone can provide decent help.
But some suggestions that can solve the problem.
- Most likely the problem is, viewText.setText can only be called from the user interface thread. There are quite a few ways to handle this. You can use AsyncTask or if you have a link to activity, you can use runOnUIThread and pass to runnable, which calls setText.
- Move checkin = sk.getInputStream (); before the cycle. There is no reason to get strem every loop through a loop.
- Do not create a BufferedReader every loop through a loop. Move it before the loop
- .sleep (2000) does not guarantee exactly 2 seconds.
I'm having trouble formatting the code, so I apologize.
private class DownloadFilesTask extends AsyncTask<Void, String, Void> { protected Long doInBackground(Void... nothing) { try { sk=new Socket(server,port); publishProgress("connected"); flag = true; } catch (UnknownHostException e) { publishProgress("failed 1 socket"); flag = false; } catch (IOException e) { publishProgress("failed 2 socket"); flag = false; } while (flag == true){ try { checkin = sk.getInputStream(); checkint = checkin.available(); if (checkint > 0){ try { BufferedReader in = new BufferedReader(new InputStreamReader(sk.getInputStream())); received = in.readLine(); publishProgress(received); } catch (IOException e) { publishProgress("failed to receive"); } } Thread.sleep(2000); } catch (IOException e) { updateProgress( } catch (InterruptedException e) { e.printStackTrace(); } return; } protected void onProgressUpdate(String... progress) { viewsurface.setText(progress[0]); } protected void onPostExecute(Void result) { //nothing } }
Mike dg
source share