PullToRefreshListViewのアップロード、ドロップダウン・リフレッシュ・ネットワーク・データの簡単なListView表示ネットワーク・データの実現

30545 ワード

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 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() {
            @Override
            public void onRefresh(PullToRefreshBase 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 {
        public MJsonAsyncTask() {
            super();
        }
        //       ui
        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
            News news = new Gson().fromJson(s, News.class);

            List 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; } } }