问题描述
- asynctask无法更新主线程集合内容
-
public class MainActivity extends Activity {
private ImageView iv;
public List data = new ArrayList();
private Bitmap[] res;
private int index;
static String URL="http://zhbj.qianlong.com/static/api/news/10007/list_1.json";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new AsyncUtil().execute(URL);
stratImage();
}private List<TestData> getJson(String url){ List<TestData> data = new ArrayList<TestData>(); try { InputStream is = new URL(url).openStream(); String json = readStream(is); JSONObject obj; TestData td; obj = new JSONObject(json); obj = obj.getJSONObject("data"); JSONArray array = obj.getJSONArray("topnews"); for(int i = 0; i < array.length(); i++){ obj = array.getJSONObject(i); td = new TestData(); td.icon = obj.getString("topimage"); td.dataTitle = obj.getString("title"); td.dataText = obj.getString("url"); data.add(td); } } catch (Exception e) { e.printStackTrace(); } return data; } private String readStream(InputStream is){ InputStreamReader isr = null; String result =""; try { String line = ""; isr = new InputStreamReader(is,"utf-8"); BufferedReader reader = new BufferedReader(isr); while((line = reader.readLine()) != null){ result += line; } } catch (IOException e) { e.printStackTrace(); } return result; } //TODO public void addBitmapArray(List<TestData> list){ Bitmap bit = null; InputStream is = null; for (int i = 0; i < list.size(); i++) { try { URL u = new URL(list.get(i).icon); HttpsURLConnection conn = (HttpsURLConnection) u.openConnection(); is = conn.getInputStream(); bit = BitmapFactory.decodeStream(is); conn.disconnect(); res[i] = bit; } catch (Exception e) { e.printStackTrace(); }finally{ try { is.close(); } catch (Exception e) { e.printStackTrace(); } } } } public Handler handler = new Handler(){ @Override public void handleMessage(Message msg) { super.handleMessage(msg); iv.setImageBitmap(res[(Integer)msg.obj]); } }; public void stratImage(){ new Thread(new Runnable(){ @Override public void run() { while(true){ Message msg = new Message(); msg.obj = index; handler.sendMessage(msg); index++; if(index >= data.size()){ index = 0; } try { Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); } } } }).start(); } //TODO class AsyncUtil extends AsyncTask<String, Void, List<TestData>>{ @Override protected List<TestData> doInBackground(String... params) { return getJson(params[0]); } @Override protected void onPostExecute(List<TestData> result) { data = result; addBitmapArray(result); super.onPostExecute(result); } }
}
解决方案
AsyncTask不能更新UI,必须用handler,looper,ruanable才行
时间: 2024-10-31 00:19:17