我的应用应该连接到服务器并从中接收数据。但由于这个错误,它无法正常工作:
android cannot resolve method runOnUiThread(anonymous java.lang.Runnable)
我该如何解决这个问题?
代码:
package com.example.chudnofsky.myapplication;
import android.app.Activity;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final TextView textview = (TextView) findViewById(R.id.textView);
Button button = (Button) findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
new Thread(new Runnable() {
@Override
public void run() {
try {
InetAddress serverAddr = InetAddress.getByName("192.168.190.47");
Socket socket = new Socket(serverAddr, 15000);
PrintWriter out = null;
BufferedReader in = null;
//out = new PrintWriter(String.valueOf(new BufferedReader(new InputStreamReader(socket.getInputStream()))));
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
if (socket.isConnected()) {
String text = "";
String finalText = "";
while ((text = in.readLine()) != null) {
finalText += text;
}
WriteText(textview, finalText);
Log.d("TCP", "Connected");
}
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
}
});
}
public void WriteText(final TextView textView, final String value ){
runOnUiThread(new Runnable() {
@Override
public void run() {
textView.setText(value);
}
});
}
}
答案 0 :(得分:1)
在方法内部执行此操作:
new Handler().post(runnable);
并像这样定义runnable:
Runnable runnable = new Runnable() {
public void run() {
runOnUiThread(new Runnable() {
public void run() {
textView.setText(value);
}
});