码迷,mamicode.com
首页 > 其他好文 > 详细

读取网上gson数据,展示到gridview上,然后上拉加载,下拉刷新

时间:2016-04-25 14:55:12      阅读:195      评论:0      收藏:0      [点我收藏+]

标签:

技术分享

NetWorkUtil.class

package com.example.liangminghui20160425;
import java.io.IOException;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.util.EntityUtils;

public class NetWorkUtil {

    public static String loginCheck_Get_HttpClient(String url) {
        // TODO Auto-generated method stub
String result = "";
        
        HttpGet get = new HttpGet(url);//创建httpClient的get请求对象
        //设置请求参数
        HttpParams params = new BasicHttpParams();
        HttpConnectionParams.setConnectionTimeout(params, 5*1000);
        HttpConnectionParams.setSoTimeout(params, 5*1000);
        
        HttpClient client = new DefaultHttpClient(params);//创建HttpClient对象
        
        try {
            HttpResponse res = client.execute(get);//执行请求,获得结果
            if(res.getStatusLine().getStatusCode() == 200){
                HttpEntity entity = res.getEntity();//获得相应结果,是一个HttpEntity对象
                result = EntityUtils.toString(entity, "utf-8");//转换为字符串
            }
        } catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return result;
    }

}

MainActivity.class:

package com.example.liangminghui20160425;


import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.format.DateUtils;
import android.util.Log;
import android.widget.BaseAdapter;
import android.widget.GridView;



import com.example.adapter.Mybase;
import com.example.vo.Data;
import com.example.vo.Demo;
import com.google.gson.Gson;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener2;
import com.handmark.pulltorefresh.library.PullToRefreshGridView;
//主页面
public class MainActivity extends Activity {

    private PullToRefreshGridView mPullRefreshListView;
    // 网址
  
    private String URL="http://apis.juhe.cn/goodbook/query?key=9d6ef8c31647a206e05fcaff70527182&catalog_id=246&rn=20&pn=";
//    private String URL = "http://apis.juhe.cn/goodbook/query?key=9d6ef8c31647a206e05fcaff70527182&catalog_id=246&rn=10&rn=10";
   private Mybase adapter;
  //设置初始值
    int z = 10;
    int p = 10;
    private List<Data> list;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        // 找控件
        mPullRefreshListView = (PullToRefreshGridView) findViewById(R.id.pull_refresh_grid);
        // 刚进入初次加载
        new GetDataTask().execute(URL + z);
        // 监听
        mPullRefreshListView
                .setOnRefreshListener(new OnRefreshListener2<GridView>() {
                    // 下拉刷新加载
                    @Override
                    public void onPullDownToRefresh(
                            PullToRefreshBase<GridView> refreshView) {
                        Log.e("TAG", "onPullDownToRefresh"); // Do work to
                        // 刷新时间
                        String label = DateUtils.formatDateTime(
                                getApplicationContext(),
                                System.currentTimeMillis(),
                                DateUtils.FORMAT_SHOW_TIME
                                        | DateUtils.FORMAT_SHOW_DATE
                                        | DateUtils.FORMAT_ABBREV_ALL);

                        // Update the LastUpdatedLabel
                        refreshView.getLoadingLayoutProxy()
                                .setLastUpdatedLabel(label);
                        // 页数
                        z = z - 1;
                        // AsyncTask异步交互加载数据
                        new GetDataTask().execute(URL + z);
                    }

                    // 上拉加载跟多
                    @Override
                    public void onPullUpToRefresh(
                            PullToRefreshBase<GridView> refreshView) {
                        Log.e("TAG", "onPullUpToRefresh"); // Do work to refresh

                        // 页数
                        p = p + 1;
                        // AsyncTask异步交互加载数据
                        new GetDataTask2().execute(URL + p);
                    }
                });
    }

    // 下拉刷新加载数据
    private class GetDataTask extends AsyncTask<String, Integer, String> {

        private String s;

        @Override
        protected String doInBackground(String... params) {

            String url = params[0];
            // 请求数据
            s = NetWorkUtil.loginCheck_Get_HttpClient(url);

            return s;
        }

       
        protected void onPostExecute(String result) {
            // 解析
            Gson gson = new Gson();

            Demo demo = gson.fromJson(result, Demo.class);
            List<Data> data =demo.getResult().getData();

            list = data;
            // 适配
            adapter = new Mybase(list, getApplicationContext());
            mPullRefreshListView.setAdapter(adapter);
            // 刷新适配器
            adapter.notifyDataSetChanged();
            // 关闭刷新下拉
            mPullRefreshListView.onRefreshComplete();

        }
    }

    // 上拉加载更多
    private class GetDataTask2 extends AsyncTask<String, Integer, String> {

        private String s;

        @Override
        protected String doInBackground(String... params) {

            String url = params[0];
            // 请求数据
            s = NetWorkUtil.loginCheck_Get_HttpClient(url);

            return s;
        }

        @Override
        protected void onPostExecute(String result) {
            // 解析
            Gson gson = new Gson();
            Demo demo = gson.fromJson(result, Demo.class);
            List<Data> data =demo.getResult().getData();

            list.addAll(data);
            // 刷新适配器
            adapter.notifyDataSetChanged();
            // Call onRefreshComplete when the list has been refreshed.
            // 关闭上拉加载
            mPullRefreshListView.onRefreshComplete();
        }
    }
}

Mybase.class

package com.example.adapter;

import java.util.List;

import com.example.liangminghui20160425.R;
import com.example.vo.Data;
import com.loopj.android.image.SmartImageView;
import com.nostra13.universalimageloader.core.ImageLoader;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView.FindListener;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

public class Mybase extends BaseAdapter{
    private List<Data> data;
    private Context context;
    
    public Mybase(List<Data> data, Context context) {
        super();
        this.data = data;
        this.context = context;
    }

    @Override
    public int getCount() {
        // TODO Auto-generated method stub
        return data.size();
    }

    @Override
    public Object getItem(int position) {
        // TODO Auto-generated method stub
        return data.get(position);
    }

    @Override
    public long getItemId(int position) {
        // TODO Auto-generated method stub
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        // TODO Auto-generated method stub
        Viehoder vh;
        if(convertView==null){
            vh=new Viehoder();
            convertView=LayoutInflater.from(context).inflate(R.layout.item, null);
            vh.image_view=(SmartImageView) convertView.findViewById(R.id.image_view);
            vh.text_view=(TextView) convertView.findViewById(R.id.text_view);
            vh.text_count=(TextView) convertView.findViewById(R.id.text_count);
            vh.text_time=(TextView) convertView.findViewById(R.id.text_time);
            convertView.setTag(vh);
        }else{
            vh=(Viehoder) convertView.getTag();
            
        }
        vh.text_view.setText(data.get(position).getTitle());
        vh.image_view.setImageUrl(data.get(position).getImg());
        vh.text_time.setText(data.get(position).getBytime());
        vh.text_count.setText(data.get(position).getReading());
        return convertView;
    }
class Viehoder{
    SmartImageView image_view;
    TextView text_view,text_time,text_count;
    
}
}

activity.xml:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity" >

   <com.handmark.pulltorefresh.library.PullToRefreshGridView
        xmlns:ptr="http://schemas.android.com/apk/res-auto"
        android:id="@+id/pull_refresh_grid"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:numColumns="2"
        ptr:ptrDrawable="@drawable/ic_launcher"
        ptr:ptrMode="both" />

</RelativeLayout>

item.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >
    
<com.loopj.android.image.SmartImageView
    android:id="@+id/image_view"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:src="@drawable/ic_launcher"
    />
<TextView 
    android:id="@+id/text_view"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    />
<LinearLayout 
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    >
    <TextView 
    android:id="@+id/text_time"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    />
    <TextView 
    android:id="@+id/text_count"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginRight="20dp"
    />
</LinearLayout>
</LinearLayout>

总结:这是项目二的第三次周考题,主要考察的是gridview的上拉加载,下拉刷新,通过集成libary类,获得其自定义的PullToRefreshGridView,然后通过以下方法设置,

读取网上gson数据,展示到gridview上,然后上拉加载,下拉刷新

标签:

原文地址:http://www.cnblogs.com/123p/p/5430820.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!