PullToRefreshListView上拉加载,下拉刷新 刷新网络数据 简单实现ListView显示网络数据

1、依赖:

compile 'com.google.code.gson:gson:2.6.2'
compile 'com.github.userswlwork:pull-to-refresh:1.0.0'

2、权限:
	
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
3、主页面布局:
	
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
    android:layout_height="match_parent" tools:context="com.example.myapplication.MainActivity">

   
<com.handmark.pulltorefresh.library.PullToRefreshListView
    android:id="@+id/lv"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_gravity="start"
    android:choiceMode="singleChoice"
    android:dividerHeight="1px"
    android:divider="#ff3660"
    android:background="#33000000"
    android:layout_alignParentTop="true" />
</android.support.constraint.ConstraintLayout>
4、item布局:
	
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">

    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/iv"/>
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/tv"/>
</LinearLayout>
5、封装News(接口中的数据)
6、网络请求类:NetWordUtils
  	
package com.example.myapplication;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
/**
 *  2017-09-27.
 */
public class NetWordUtils {

    private static String  tag = "NetWordUtils";
    /**
     * 获取网络json
     *
     * @param urlString
     * @return
     */
    public static String getNetjson(String urlString) {

        try {
            URL url = new URL(urlString);
            HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
            urlConnection.setRequestMethod("GET");//若果是get请求可以不用配置; 其他请求必须配置
            urlConnection.setConnectTimeout(8000);//设置链接超时间

            InputStream inputStream = urlConnection.getInputStream();//获取网络返回的输入流;
            //可拼接的字符串
            StringBuilder stringBuilder = new StringBuilder();
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
            String temp = "";
            while ((temp = bufferedReader.readLine()) != null) {
                stringBuilder.append(temp);
                temp = "";
            }
            //这个是网络获取的数据
            String data = stringBuilder.toString();
            Log.e(tag, "getData: " + data);
            return data;
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "";
    }
    /**
     * 获取网络图片的工具类
     */
    public static Bitmap getNetBitmap(String urlString) {
        try {
            //用URL封装链接地址;
            URL url = new URL(urlString);
            //用url打开链接
            HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
            //联网的状态码
            int responseCode = urlConnection.getResponseCode();
            if(responseCode ==200){
                //链接上获取输入流
                InputStream inputStream = urlConnection.getInputStream();
                //把流直接转换成bitmap(系统提供的BitmapFactory)
                Bitmap bitmap = BitmapFactory.decodeStream(inputStream);//BitmapFactory是个工具类,系统提供的
                return bitmap;
            }else {
                Log.e(tag, "网络状态码:: "+responseCode );
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}


7、MainActivity主页面代码:
	
package com.example.myapplication;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;

import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {

    
private PullToRefreshListView lv;
    String urlTotal = "http://api.expoon.com/AppNews/getNewsList/type/1/p/1";
    private MAdapter mAdapter;
    private List<News.DataBean> list = new ArrayList<>();


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        lv= (PullToRefreshListView) findViewById(R.id.lv);


        mAdapter = new MAdapter();
        lv.setAdapter(mAdapter);
        initData();

        lv.setMode(PullToRefreshBase.Mode.BOTH);

        lv.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener<ListView>() {
            @Override
            public void onRefresh(PullToRefreshBase<ListView> pullToRefreshBase) {
                Toast.makeText(MainActivity.this, "下拉刷新", Toast.LENGTH_SHORT).show();
                initData();
                lv.postDelayed(new Runnable() {
                    public void run() {
                        //停止刷新
                      lv.onRefreshComplete();
		//	  i = 0;
              //  new MyAsyncTask().execute("http://www.93.gov.cn/93app/data.do?channelId=0&startNum=" + i);
                    }
                },1000);

            }
        });

        lv.setOnLastItemVisibleListener(new PullToRefreshBase.OnLastItemVisibleListener() {
            @Override
            public void onLastItemVisible() {
	//	  i = i + 20;
             //   new MyAsyncTask().execute("http://www.93.gov.cn/93app/data.do?channelId=0&startNum=" + i);
                Toast.makeText(MainActivity.this, "上拉加载", Toast.LENGTH_SHORT).show();

            }
        });

    }
    private void initData() {
        new MJsonAsyncTask().execute(urlTotal);
    }
    class MJsonAsyncTask extends AsyncTask<String, Void, String> {
        public MJsonAsyncTask() {
            super();
        }
        //主线程可以更新ui
        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
            News news = new Gson().fromJson(s, News.class);

            List<News.DataBean> temp = news.getData();
            list.addAll(temp);
            mAdapter.notifyDataSetChanged();

        }
        //这个回调方法是子线程;
        @Override
        protected String doInBackground(String... strings) {
            //取第0个元素,就是url;
            String netjson = NetWordUtils.getNetjson(strings[0]);//调用网络请求工具类
            return netjson;
        }
    }
    class MAdapter extends BaseAdapter {
        @Override
        public int getCount() {
            return list.size();
        }
        @Override
        public Object getItem(int i) {
            return list.get(i);
        }
        @Override
        public long getItemId(int i) {
            return i;
        }
        @Override
        public View getView(int i, View containerView, ViewGroup viewGroup) {
            View view = View.inflate(MainActivity.this, R.layout.item, null);
            TextView tv_name = (TextView) view.findViewById(R.id.tv);
            ImageView iv = (ImageView) view.findViewById(R.id.iv);
            tv_name.setText(list.get(i).getNews_title());
            /**
             * getView方法每个条目显示的时候都会调用,所以我们在这个请求图片,并设置
             *  把图片url传递给asyncTask
             */
            
		ImageLoader.getInstance().displayImage(list.get(i).getPic_url(),iv);
return view; } } }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值