In my android app I'm creating a Socket and a BufferedReader. If i just read one line of the BufferedReader I'm getting the response from the server. But if I'm trying it with while((message = br.readLine()) != null)
The application crashes. Any ideas what could be the problem?
public void connecting(String uid) {
uuid = uid;
try {
client = new Socket("127.0.0.1", 8234);
try {
tv = (TextView) chat.findViewById(R.id.textView);
pw = new PrintWriter(client.getOutputStream());
br = new BufferedReader(new InputStreamReader(client.getInputStream()));
new Thread(new Runnable() {
@Override
public void run() {
try {
// If i just try this, it works
tv.append("\n"+br.readLine());
// If I'm trying this, it crashes
String message = "";
while((message = br.readLine()) != null) {
tv.append("\n"+message);
}
} catch (IOException e) {
tv.append(e.getMessage());
}
}
}).start();
tv.append("Connected!");
pw.println(uuid+":B31TR1TT");
pw.flush();
} catch (IOException e) {
tv.append(e.getMessage());
}
} catch (IOException e) {
tv.append(e.getMessage());
}
}
As algui91 said move the network calls to a separate thread. that strict mode error (violation=4) indicates network calls on ui thread.
Just refactor the network calls into a background task (service, asynctask , or whaetever ) , and the issue should go away.
Separate the UI from the business logic or network communication. Its always better and easier to test/debug.
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(1024); byte[] buffer = new byte[1024]; int bytesRead; InputStream inputStream = socket.getInputStream(); while ((bytesRead = inputStream.read(buffer)) != -1){ byteArrayOutputStream.write(buffer, 0, bytesRead); response += byteArrayOutputStream.toString("UTF-8"); }
而不是 while 循环代码尝试使用此代码或访问此链接http://hastebin.com/inecerakes.java
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.