所以我在一个单独的服务中使用OkHttp从twitter API获取数据。 我一直试图警告用户没有互联网连接就无法加载推文。但是当我尝试这个时,应用程序崩溃。错误是:java.lang.RuntimeException:无法在未调用Looper.prepare()的线程内创建处理程序。这是代码
private void getTweets(final String topic) {
final TwitterService twitterService = new TwitterService();
twitterService.findTweets(topic, new Callback() {
@Override
public void onFailure(Request request, IOException e) {
e.printStackTrace();
Log.e("Traffic Activity", "Failed to make API call");
Toast.makeText(getApplicationContext(), "Bigger fail", Toast.LENGTH_LONG).show();
}
答案 0 :(得分:2)
可能你是从错误的线程调用Toast.makeText。它需要从UI线程调用。试试这个
activity.runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(activity, msg, Toast.LENGTH_SHORT).show();
}
});
此处有更多信息Can't create handler inside thread that has not called Looper.prepare()
答案 1 :(得分:0)
您正在从工作线程中调用它。您需要从主线程中调用Toast.makeText()(以及处理UI的大多数其他函数)。您可以使用处理程序,例如
//在UI线程
中设置它mHandler = new Handler(Looper.getMainLooper()) {
@Override
public void handleMessage(Message message) {
// This is where you do your work in the UI thread.
// Your worker tells you in the message what to do.
}
};
void workerThread() {
// And this is how you call it from the worker thread:
Message message = mHandler.obtainMessage(command, parameter);
message.sendToTarget();
}