【搞错了,没看到后面的视频在onPostExecute加绑定adapter】程序无报错,但是页面显示空白,无法加载
【搞错了,没看到后面的视频在onPostExecute加绑定adapter】
【MainActivity代码】
package com.example.asynctask;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.widget.ListView;
public class MainActivity extends Activity {
private ListView mListView;
private static String URL = "http://www.imooc.com/api/teacher?type=4&num=30";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mListView = (ListView) findViewById(R.id.lv_main);
mListView.setAdapter(new NewsAdapter(MainActivity.this,getJsonData(URL)));
new NewAsyncTask().execute(URL);
}
// 将url//
private List<NewsBean> getJsonData(String url) {
List<NewsBean> newsBeanList = new ArrayList<>();
try {
String jsonString = readStream(new URL(url).openStream());
// logcat打印,未解析数据
// Log.d("xys",jsonString);
/* 解析JSON数据到List中 */
JSONObject jsonObject;
NewsBean newsBean;
try {
jsonObject= new JSONObject(jsonString);
JSONArray jsonArray = jsonObject.getJSONArray("data");
for (int i = 0; i < jsonArray.length(); i++) {
jsonObject = jsonArray.getJSONObject(i);
newsBean = new NewsBean();
newsBean.newsIconUrl = jsonObject.getString("picSmall");
newsBean.newsTitle = jsonObject.getString("name");
newsBean.newsContent = jsonObject.getString("description");
newsBeanList.add(newsBean);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (IOException e) {
// TODO: handle exception
e.printStackTrace();
}
return newsBeanList;
}
private String readStream(InputStream is) {
InputStreamReader isr;
String result = "";
try {
String line = "";
isr = new InputStreamReader(is, "utf-8"); // 字节流转字符流
BufferedReader br = new BufferedReader(isr);
while ((line = br.readLine()) != null) {
result += line;
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
class NewAsyncTask extends AsyncTask<String, Void, List<NewsBean>> {
@Override
protected List<NewsBean> doInBackground(String... params) {
// TODO Auto-generated method stub
return getJsonData(params[0]);
}
}
}
/*
已经排查过权限及工程其他类,觉得MainActivity存在Bug的问题比较大,故只贴了MainActivity
*/