一开始没有本地数据,gridview应该为空,之后它开始使用okhttp获取数据,如果有效,则更新gridview内容。
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
v = inflater.inflate(R.layout.fragment_blog_list, container, false);
gridView = (GridView) v.findViewById(R.id.gridview);
try {
get_data(Constant.get_cat_list);
} catch (Exception e) {
e.printStackTrace();
}
return v;
}
public void get_data(String url) throws Exception {
Request request = new Request.Builder()
.url(url)
.build();
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Request request, IOException e) {
}
@Override
public void onResponse(Response response) throws IOException {
if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
Log.d("test1", response.body().string());
gridView.setAdapter(new MyAdapter(getActivity()));
}
});
}
问题是Only the original thread that created a view hierarchy can touch its views exception
,我找到了解决方案,但是,我担心我可以通过重新排序代码来实现相同的结果,而不是在下载后执行更新任务时将以下代码添加到任何地方数据?
runOnUiThread(new Runnable() {
@Override
public void run() {
//stuff that updates ui
}
});
非常感谢