进入应用,一片空白,什么也没有显示,请各位帮忙看看,谢谢!
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.widget.ListView;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
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);
// new NewsAsyncTask().execute(URL);
}
//将url对应的JSON格式数据转化为我们所封装的NewsBean
private List<NewsBean> getJsonDate (String url) {
List<NewsBean> newsBeanList=new ArrayList<NewsBean>();
try {
String jsonString=readStream(new URL(url).openStream());
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) {
e.printStackTrace();
}
} catch (IOException e) {
e.printStackTrace();
}
return newsBeanList;
}
//通过is解析网页返回的数据
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 (Exception e) {
e.printStackTrace();
}
return result;
}
//实现网络的异步访问
class NewsAsyncTask extends AsyncTask<String,Void,List<NewsBean>>{
@Override
protected List<NewsBean> doInBackground(String... params) {
return getJsonDate(params[0]);
}
@Override
protected void onPostExecute(List<NewsBean> newsBeans) {
super.onPostExecute(newsBeans);
NewsAdapter adapter=new NewsAdapter(MainActivity.this,newsBeans,mListView);
mListView.setAdapter(adapter);
}
}
}
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import java.util.List;
public class NewsAdapter extends BaseAdapter implements AbsListView.OnScrollListener {
private List<NewsBean>mList;
private LayoutInflater mInflater;
private ImageLoader mImageLoader;
private int mStart,mEnd;
public static String[] URLS;
private boolean mFirstIn;
public NewsAdapter(Context context, List<NewsBean>data, ListView listView){
mList=data;
mInflater=LayoutInflater.from(context);
mImageLoader=new ImageLoader(listView);
URLS=new String[data.size()];
for (int i = 0; i <data.size() ; i++) {
URLS[i]=data.get(i).newsIconUrl;
}
mFirstIn=true;
//一定要注册对应的事件
listView.setOnScrollListener(this);
}
@Override
public int getCount() {
return mList.size();
}
@Override
public Object getItem(int position) {
return mList.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder viewHolder=null;
if (convertView == null) {
viewHolder=new ViewHolder();
convertView=mInflater.inflate(R.layout.item_layout,null);
viewHolder.ivIcon= (ImageView) convertView.findViewById(R.id.iv_icon);
viewHolder.tvTitle= (TextView) convertView.findViewById(R.id.tv_title);
viewHolder.tvContent= (TextView) convertView.findViewById(R.id.tv_content);
convertView.setTag(viewHolder);
}else{
viewHolder= (ViewHolder) convertView.getTag();
}
// viewHolder.ivIcon.setImageResource(R.mipmap.ic_launcher);
String url=mList.get(position).newsIconUrl;
viewHolder.ivIcon.setTag(url);
// new ImageLoader().showImageByThread(viewHolder.ivIcon,url);
mImageLoader.showImageByAsyncTask(viewHolder.ivIcon,url);
viewHolder.tvTitle.setText(mList.get(position).newsTitle);
viewHolder.tvContent.setText(mList.get(position).newsContent);
return convertView;
}
@Override
public void onScrollStateChanged(AbsListView absListView, int scrollState) {
if(scrollState==SCROLL_STATE_IDLE){
//加载可见项
mImageLoader.loadImages(mStart,mEnd);
}else{
//停止任务
mImageLoader.cancelAllTasks();
}
}
@Override
public void onScroll(AbsListView absListView, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
mStart=firstVisibleItem;
mEnd=firstVisibleItem+visibleItemCount;
//第一次显示的时候调用
if (mFirstIn&&visibleItemCount>0){
mImageLoader.loadImages(mStart,mEnd);
mFirstIn=false;
}
}
class ViewHolder{
public TextView tvTitle,tvContent;
public ImageView ivIcon;
}
}
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Handler;
import android.os.Message;
import android.util.LruCache;
import android.widget.ImageView;
import android.widget.ListView;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashSet;
import java.util.Set;
public class ImageLoader{
private ImageView mImageView;
private String mUrl;
//创建Cache
private LruCache<String,Bitmap> mCaches;
private ListView mListView;
private Set<NewsAsyncTask> mTask;
public ImageLoader(ListView listview){
mListView=listview;
mTask=new HashSet<NewsAsyncTask>();
//获取最大可用内存
int maxMemory= (int) Runtime.getRuntime().maxMemory();
int cachSize=maxMemory/4;
mCaches=new LruCache<String,Bitmap>(cachSize){
@Override
protected int sizeOf(String key, Bitmap value) {
//在每次存入缓存的时候调用
return value.getByteCount();
}
};
}
//增加到缓存
public void addBitmapToCaChe(String url,Bitmap bitmap){
if(getBitmapFromURL(url)==null){
mCaches.put(url,bitmap);
}
}
//从缓存中获取数据
public Bitmap getBitmapFromCaChe(String url){
return mCaches.get(url);
}
private Handler mHandler=new Handler(){
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
if (mImageView.getTag().equals(mUrl)) {
mImageView.setImageBitmap((Bitmap) msg.obj);
}
}
};
public void showImageByThread(ImageView imageView, final String url){
mImageView=imageView;
mUrl=url;
new Thread(){
@Override
public void run() {
super.run();
Bitmap bitmap=getBitmapFromURL(url);
Message message=Message.obtain();
message.obj=bitmap;
mHandler.sendMessage(message);
}
}.start();
}
public Bitmap getBitmapFromURL(String urlString) {
Bitmap bitmap;
InputStream is = null;
try {
URL url=new URL(urlString);
HttpURLConnection connection= (HttpURLConnection) url.openConnection();
is =new BufferedInputStream(connection.getInputStream());
bitmap= BitmapFactory.decodeStream(is);
connection.disconnect();
return bitmap;
} catch (Exception e) {
e.printStackTrace();
}finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
public void showImageByAsyncTask(ImageView imageView,String url){
//从缓存中取出对应的图片
Bitmap bitmap=getBitmapFromCaChe(url);
//如果缓存中没有,那么必须去下载
if (bitmap==null){
imageView.setImageResource(R.mipmap.ic_launcher);
}else{
imageView.setImageBitmap(bitmap);
}
}
public void cancelAllTasks(){
if (mTask!=null)
{
for (NewsAsyncTask task:mTask) {
task.cancel(false);
}
}
}
//用来加载从start到end的所有图片
public void loadImages(int start,int end){
for (int i = start; i < end; i++) {
String url=NewsAdapter.URLS[i];
//从缓存中取出对应的图片
Bitmap bitmap=getBitmapFromURL(url);
//如果缓存中没有,那么必须去下载
if (bitmap==null){
NewsAsyncTask task=new NewsAsyncTask(url);
task.execute(url);
mTask.add(task);
}else{
ImageView imageView= (ImageView) mListView.findViewWithTag(url);
imageView.setImageBitmap(bitmap);
}
}
}
private class NewsAsyncTask extends AsyncTask<String,Void,Bitmap>{
// private ImageView mImageView;
private String mUrl;
public NewsAsyncTask(String url){
// mImageView=imageView;
mUrl=url;
}
@Override
protected Bitmap doInBackground(String... params) {
String url=params[0];
//从网络获取图片
Bitmap bitmap=getBitmapFromURL(url);
if (bitmap!=null){
//将不在缓存的图片加入缓存
addBitmapToCaChe(url,bitmap);
}
return bitmap;
}
@Override
protected void onPostExecute(Bitmap bitmap) {
super.onPostExecute(bitmap);
ImageView imageView= (ImageView) mListView.findViewWithTag(mUrl);
if (imageView!=null&&bitmap!=null){
imageView.setImageBitmap(bitmap);
}
mTask.remove(this);
}
}
}