Android: Only the original thread that created a view hierarchy can touch its views 异常
最近自己再写一个小项目练手,创建一个线程从网络获取数据然后显示在 recyclerView 上。写好后发现页面能够显示,但是有时候会把请求的数据显示过来,有时候不会。点开 android monitor 一看,有一个提示 :
Only the original thread that created a view hierarchy can touch its views.
异常的意思是说只有创建这个view的线程才能操作这个 view,普通会认为是将view创建在非UI线程中才会出现这个错误。
本来我想将就下,能看到算了的,说明我会简单使用 fragment 了。不过作为程序员我们肯定要寻根问底的啊。
这段请求数据代码如下所示:
new Thread(new Runnable() {
@Override
public void run() {
try {
String url = "";
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder().url(url).method("GET", null).build();
okhttp3.Response response = client.newCall(request).execute();
if (response.isSuccessful()) {
String responseString = (response.body() == null ? "" : response.body().string());
......解析数据
WidgetActionEvent event = new WidgetActionEvent(WidgetActionEvent.ACTION_CLICK);
event.object = feedModel;
EventBus.getDefault().post(event);
//iLoadData.loadData(feedModel);
} else {
Log.i(TAG, "okHttp is request error");
}
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
数据请求之后,解析,并采用 eventbus 来传送数据。
ps :如果你是在 mainActivity 中调用上述代码,是不会产生的异常的,因为都是运行在主线程中。
变形一 : 崩溃
于是我换了一种形式来传递数据,这次采用回调的方式,也就是上面被注释掉的那行代码:
iLoadData.loadData(feedModel);
这次不用 eventbus 竟然崩溃了......我能怎么办,我也很无奈啊。
FATAL EXCEPTION: Thread-932
Process: example.hope.mvpwithrecyclerview, PID: 4916
android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.
解决办法:采用 handle
实现代码如下:
/**
* 发起网络请求
*/
public static void okHttp_synchronousGet(final Handler handler) {
new Thread(new Runnable() {
@Override
public void run() {
try {
String url = "url";
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder().url(url).method("GET", null).build();
okhttp3.Response response = client.newCall(request).execute();
if (response.isSuccessful()) {
String responseString = (response.body() == null ? "" : response.body().string());
......解析数据
handler.sendMessage(handler.obtainMessage(22, feedModel));
} else {
Log.i(TAG, "okHttp is request error");
}
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
}
然后再 fragment 添加下面代码用来处理传过来的数据:
/**
* 接收解析后传过来的数据
*/
Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
Object model = (Object) msg.obj;
showPictures(model);
}
};
这样就能后完美的解决这个问题了。
Android: Only the original thread that created a view hierarchy can touch its views 异常的更多相关文章
- 浅析Android中的消息机制-解决:Only the original thread that created a view hierarchy can touch its views.
在分析Android消息机制之前,我们先来看一段代码: public class MainActivity extends Activity implements View.OnClickListen ...
- 开发错误记录1:解决:Only the original thread that created a view hierarchy can touch its views.
今天在项目中要使用圆角头像,导入开源 CircleImageView ,然后setImageBitmap()时 运行时就会发现,它会报一个致命性的异常:: · ERROR/AndroidRuntime ...
- Only the original thread that created a view hierarchy can touch its views
在调试软件的时候出现如下的错误: 01-05 20:53:36.492: E/ZZShip(2043): android.view.ViewRootImpl$CalledFromWrongThread ...
- Only the original thread that created a view hierarchy can touch its views解决办法
这周操作系统作业布置了一个作业,内容是做个小软件,来模拟消费者生产者问题,作业实现起来不来,因为之前写过这个算法,所以关键步骤就是在消费和生产的时候更新缓存区的UI控件就行,之后问题就来了,出现了标题 ...
- 错误:Only the original thread that created a view hierarchy can touch its views——Handler的使用
在跟随教程学习到显示web页面的html源码时报错:Only the original thread that created a view hierarchy can touch its views ...
- 子线程调用invalidate()产生“Only the original thread that created a view hierarchy can touch its views.”原因分析
目录 1.异常出处 2.从View.invalidate()方法开始分析 3.ViewRootImpl如何与View进行关联:从Activity的setContentView开始分析 3.1 最顶层的 ...
- andriod 错误:Only the original thread that created a view hierarchy can touch its views——Handler的使用
package com.example.yanlei.myapplication; import android.media.MediaMetadataRetriever; import androi ...
- 解决Only the original thread that created a view hierarchy can touch its views
这种异常出现在子线程中处理UI操作产生的异常,将UI操作放在主线程中就OK了
- "Only the original thread that created a view hierarchy can touch its views.” 解决方法
这个主要总是,开启的线程和 UI 线程(主线程)不是同一个线程.可以Runnable方式避免,如下例所示就可以解决这个问题了. public static void updateText(Activi ...
随机推荐
- Java学习笔记三---unable to launch
环境配置好后,在eclipse下编写HelloWorld程序: ①创建新工程 ②创建.java文件,命名为HelloWorld ③在源文件中添加main方法,代码如下: public void mai ...
- JavaScript一些常用方法一
整理以前的笔记,在学习JavaScript时候,经常会用到一些方法,但是有时忘掉了具体用法,因此记下.方便以后查阅. 这篇博文先说明这些方法的用途: splice().push().pop() .sh ...
- CentOS7的一些初始化
默认最小化安装 [root@GVMCET001 ~]# nmtui 设置网络,主机名等 [root@GVMCET001 ~]# yum update 更新系统 SSH [root@GVMCET001 ...
- XML的序列化(Serializer)
步骤: //1获取XmlSerializer 类的实例 通过Xml这个工具类去获取 XmlSerializer xmlSerializer = Xml.newSerializer(); try { / ...
- JVM读书笔记PART3
一.早期(编译器)优化 语法糖 c#和java的泛型截然不同看似相同,c#是真实的泛型 编译运行一直存在 List<string> 和List<int> 就完全是两个类 而Ja ...
- String.getBytes(),源码之下,了无秘密
@Deprecated public void getBytes(int srcBegin, int srcEnd, byte dst[], int dstBegin) { if (srcBegin ...
- .Net 内存对象分析
在生产环境中,通过运行日志我们会发现一些异常问题,此时,我们不能直接拿VS远程到服务器上调试,同时日志输出的信息无法百分百反映内存中对象的状态,比如说我们想查看进程中所有的Socket连接状态.服务路 ...
- http://codeforces.com/contest/349
A. Cinema Line time limit per test 2 seconds memory limit per test 256 megabytes input standard inpu ...
- Python实战之int学习笔记及简单练习
['__abs__', '__add__', '__and__', '__bool__', '__ceil__', '__class__', '__delattr__', '__dir__', '__ ...
- Python二维数据分析
一.numpy二维数组 1.声明 import numpy as np #每一个[]代表一行 ridership = np.array([ [ 0, 0, 2, 5, 0], [1478, 3877, ...