关闭

HttpUrlConnection + AsyncTask请求xml格式,HttpClient + Thread + Handler请求json

115人阅读 评论(0) 收藏 举报

布局activity_main.xml

<ListView 
      android:id="@+id/lv"
      android:layout_width="fill_parent"
      android:layout_height="wrap_content"
      ></ListView>

MainActivity

package com.example.lainxidemo;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.util.Xml;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;

import com.example.adapter.Myadapter;
import com.example.bean.Book;

public class MainActivity extends Activity {

    private ProgressDialog dialog;
    private String url;
    private String json;
    private HttpURLConnection connection;
    private InputStream in;
    private List<Book> list;
    private String pname;
    private Book b;
    private ListView lv;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        lv = (ListView) findViewById(R.id.lv);
        MyAsyntask task=new MyAsyntask();
        task.execute(url);
        lv.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                    int position, long id) {
                Intent intent =new Intent(MainActivity.this,TwoActivity.class);
                intent.putExtra("id", list.get(position).getId());
                startActivity(intent);

            }
        });
    }

     class MyAsyntask extends AsyncTask<String, Void, List<Book>>{

        @Override
        protected List<Book> doInBackground(String... params) {
            url = "http://apis.juhe.cn/goodbook/catalog?key=eb487dc80b175790e914b7f62e94c478&dtype=xml";
            list = pulldemo();
            return list;
        }
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
             dialog=new ProgressDialog(MainActivity.this);
             dialog.setTitle("提示信息");
             dialog.setMessage("正在加载......");
             dialog.show();
        }

        @Override
        protected void onPostExecute(List<Book> result) {
            // TODO Auto-generated method stub
            super.onPostExecute(result);
            dialog.cancel();

            Myadapter adapter=new Myadapter(MainActivity.this,list);
            Log.i("list", list.toString());
            lv.setAdapter(adapter);

        }
     }

       private List<Book> pulldemo() {
            boolean flag = true;
            try {
               // url = "http://apis.juhe.cn/goodbook/query?key=9d6ef8c31647a206e05fcaff70527182&catalog_id=244&pn=2&rn="+rn+"&dtype=xml";
                // StringBufferInputStream in=new StringBufferInputStream(url);
                URL u = new URL(url);
                HttpURLConnection conn = (HttpURLConnection) u.openConnection();
                conn.setReadTimeout(5000);
                conn.setRequestMethod("GET");
                conn.setRequestProperty("encoding", "utf-8");
                conn.connect();
                if (conn.getResponseCode() == 200) {
                    in = conn.getInputStream();
                }
                XmlPullParser parser = Xml.newPullParser();
                parser.setInput(in, "UTF_8");
                int event = parser.getEventType();
                while (flag) {
                    switch (event) {
                    case XmlPullParser.START_DOCUMENT:
                        list = new ArrayList<>();
                        break;
                    case XmlPullParser.START_TAG:
                        pname = parser.getName();
                        if (pname.equals("item")) {
                          b = new Book();
                        }
                        break;
                    case XmlPullParser.TEXT:
                        if (pname.equals("id")) {
                          b.setId(parser.getText());
                        } else if (pname.equals("catalog")) {
                            b.setCatalog(parser.getText());
                        }
                        break;
                    case XmlPullParser.END_TAG:
                        pname = parser.getName();
                        if (pname.equals("item")) {
                            list.add(b);
                        }
                        pname = "";
                        break;
                    case XmlPullParser.END_DOCUMENT:
                        flag = false;
                        break;
                    }
                    event = parser.next();
                }
                Log.i("listddd", list.toString());
            } catch (XmlPullParserException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            return list;
        }
}

PullToRefreshGridView布局

 <com.handmark.pulltorefresh.library.PullToRefreshGridView 
      android:id="@+id/gi"
      android:layout_width="fill_parent"
      android:layout_height="fill_parent"
      android:numColumns="3"
      ></com.handmark.pulltorefresh.library.PullToRefreshGridView>

TwoActivity

package com.example.lainxidemo;

import java.io.IOException;
import java.util.List;

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.util.EntityUtils;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.widget.GridView;

import com.example.adapter.Sadapter;
import com.example.bean.Data;
import com.example.bean.Example;
import com.example.bean.Res;
import com.google.gson.Gson;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshBase.Mode;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener2;
import com.handmark.pulltorefresh.library.PullToRefreshGridView;

public class TwoActivity extends Activity {

    private String id;
    private String json;
    private List<Data> dlist;
    private int pn=0;
    private Sadapter adapter;
    private Handler handler=new Handler(){



        public void handleMessage(Message msg) {
            Gson g=new Gson();
            Example fromJson = g.fromJson(json, Example.class);
            Res result = fromJson.getResult();
            dlist = result.getData();
            Log.i("dlsit", dlist.toString());
            adapter = new Sadapter(TwoActivity.this,dlist);
            gi.setAdapter(adapter);
            if(msg.what==0){
                adapter.notifyDataSetChanged();
                gi.onRefreshComplete();
            }
        };
    };
    private PullToRefreshGridView gi;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.view);
        Intent intent = getIntent();
        id = intent.getStringExtra("id");

        jiexi(pn);
        gi = (PullToRefreshGridView) findViewById(R.id.gi);
        gi.setMode(Mode.BOTH);
        gi.setOnRefreshListener(new OnRefreshListener2<GridView>() {

            @Override
            public void onPullDownToRefresh(
                    PullToRefreshBase<GridView> refreshView) {
                pn=40;
                jiexi(pn);
                handler.sendEmptyMessageDelayed(0, 2000);

            }

            @Override
            public void onPullUpToRefresh(
                    PullToRefreshBase<GridView> refreshView) {
                pn=20;
                jiexi(pn);
                handler.sendEmptyMessageDelayed(0, 2000);
            }
        });
    }

    private void jiexi(final int pn) {
        new Thread(){

            public void run() {

                String urls="http://apis.juhe.cn/goodbook/query?key=eb487dc80b175790e914b7f62e94c478&catalog_id="+id+"&pn="+pn+"&rn=20";
                json = getjson(urls);
                Message msg=new Message();
                msg.what=1;
                handler.sendMessage(msg);
            };
        }.start();
    }

    protected String getjson(String urls) {
        String js=null;
        try {
            HttpClient client=new DefaultHttpClient();
            HttpGet get=new HttpGet(urls);
            HttpResponse  response=client.execute(get);
            int statusCode = response.getStatusLine().getStatusCode();
            if(statusCode==200){
                HttpEntity entity = response.getEntity();
                 js = EntityUtils.toString(entity, "UTF_8");
                 Log.i(js, js);
            }
        } catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return js;
    }
}

Myadapter

package com.example.adapter;

import java.util.List;

import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

import com.example.bean.Book;
import com.example.lainxidemo.R;

public class Myadapter extends BaseAdapter {

    private Context context;
    private List<Book> list;
    public Myadapter(Context context,List<Book> list){
        this.context=context;
        this.list=list;
    }
    @Override
    public int getCount() {
        // TODO Auto-generated method stub
        return list.size();
    }

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

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

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        if(convertView==null){
            convertView=View.inflate(context, R.layout.listview_item, null);
        }
        TextView tx=(TextView) convertView.findViewById(R.id.tx);
        tx.setText(list.get(position).getCatalog());
        return convertView;
    }

}

Sadapter

package com.example.adapter;

import java.util.List;

import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.example.bean.Data;
import com.example.lainxidemo.R;
import com.lidroid.xutils.BitmapUtils;

public class Sadapter extends BaseAdapter {

    private Context context;
    private  List<Data> dlist;
    public Sadapter (Context context, List<Data> dlist){
        this.context=context;
        this.dlist=dlist;
    }
    @Override
    public int getCount() {
        // TODO Auto-generated method stub
        return dlist.size();
    }

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

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

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        if(convertView==null){
            convertView=View.inflate(context, R.layout.g_item, null);
        }
        ImageView im=(ImageView) convertView.findViewById(R.id.im);
        TextView tname=(TextView) convertView.findViewById(R.id.tname);
        TextView t1=(TextView) convertView.findViewById(R.id.t1);
        TextView t2=(TextView) 
        convertView.findViewById(R.id.t2);
        BitmapUtils utils=new BitmapUtils(context);
        utils.display(im, dlist.get(position).getImg());
        tname.setText(dlist.get(position).getTitle());
        t1.setText(dlist.get(position).getReading());
        t2.setText(dlist.get(position).getBytime());
        return convertView;
    }

}
1
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:2285次
    • 积分:107
    • 等级:
    • 排名:千里之外
    • 原创:8篇
    • 转载:0篇
    • 译文:0篇
    • 评论:0条
    文章存档