gpt4 book ai didi

android 无法解析方法 runonuithread

转载 作者:太空宇宙 更新时间:2023-11-03 10:38:31 24 4
gpt4 key购买 nike

我的应用程序应该连接到服务器并从中接收数据。但由于此错误而无法正常工作:

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);
}
});
}

}

最佳答案

在方法内部执行此操作:

new Handler().post(runnable);

然后像这样定义runnable:

Runnable runnable = new Runnable() {
public void run() {
runOnUiThread(new Runnable() {
public void run() {
textView.setText(value);
}
});

关于android 无法解析方法 runonuithread,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38777681/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com