学习使用线程下载json数据,并使用ListView显示出来的总结

来源:互联网 发布:ue4是什么软件 编辑:程序博客网 时间:2024/04/30 03:43

1.首先要得到一个URL对象,把要访问的网页(json数据)得到

2 然后使用json解析,得到里面需要的对象

3 得到的对象封装成一个javabean形式,

4 使用适配器(adapter)显示到listview中,我使用的是baseadapter,simpleadapter也可以,但是baseadapter会比较通用一些,使用baseadapter要注意一下需要添加的方法

5 最后使用AsyncTask/Handler,将需要耗时间下载的json数据得到,防止主线程阻塞,也要注意使用AsyncTask/Handler时的一下具体使用方法,具体看代码

6 几个类都是在一个界面,希望大家多多包涵,分开的话就更好了,真是做的时候是简单的试一下

 

 

package com.example.personjson;

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

import org.json.JSONArray;
import org.json.JSONObject;

import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;

import com.example.domain.Person;
import com.example.service.HtmlService;

public class MainActivity extends Activity {
 //private TextView textView;
 private ListView listView;
  List<Person> persons;
  JSONPersonService JSservie;
  HtmlAsyncTask ht;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
       
            listView = (ListView)this.findViewById(R.id.listView);
            ht = new HtmlAsyncTask();//这里你忘了new对象
            ht.execute();
   //InputStream inStream = this.getClass().getClassLoader().getResourceAsStream("person.txt");
   
       /**try {
        
     JSONPersonService JSservice = new JSONPersonService();

     persons = JSservice.getJsonPersons();
     //InputStream instream = JSservice.getJsonPersons(inputStream);
    } catch (Exception e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
    }*/
      
           /** List<HashMap<String, Object>> data = new ArrayList<HashMap<String, Object>>();
            for(Person person : persons){
             HashMap<String, Object> item = new HashMap<String, Object>();
             item.put("title", person.getTitle());
             item.put("summary", person.getSummary());
             data.add(item);
            SimpleAdapter adapter = new SimpleAdapter(this, data, R.layout.listviewitem,
              new String[]{"title", "summary"}, new int[]{R.id.title, R.id.summary});
            listView.setAdapter(adapter);
          
      
            }*/
      
      
        }
   
   
    public class DemoAdapter extends BaseAdapter {
     private LayoutInflater myInflater;

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

  public Person getItem(int position) {
   // TODO Auto-generated method stub
   return persons.get(position);
  }

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

  public View getView(int position, View convertView, ViewGroup parent) {
   // TODO Auto-generated method stub
   //初始化item的xml文件
   myInflater = LayoutInflater.from(MainActivity.this);
   convertView = myInflater.inflate(R.layout.listviewitem, null);
   
   
   
   //初始化控件
   TextView textViewTitle = (TextView)convertView.findViewById(R.id.title);
   TextView textViewSumm = (TextView)convertView.findViewById(R.id.summary);
   
   
   //从list里面取出单个对象
   
   Person person = getItem(position);
  
   //把值设定到具体的控件上
   textViewTitle.setText(person.getTitle());
   textViewSumm.setText(person.getSummary());//person.getSummary(),这里有点不一样
   

   return convertView;
   
  }
  
 }
   
    public class HtmlAsyncTask extends AsyncTask<String, Integer, String> {
 
     public static final String TAG = "HtmlAsyncTask";

     //public HtmlAsyncTask(TextView textView) {
      //this.textView = textView;
     //}

     @Override
     protected String doInBackground(String... params) {
      // TODO Auto-generated method stub
      String html = "";
      persons = new ArrayList<Person>();
      try {
        html = HtmlService.getHtml("http://www.baike.com/api.php?datatype=json&m=article&a=new&baike_id=24669&start=0&limit=10&share=new");

        JSservie = new JSONPersonService();
        persons = JSservie.getJsonPersons(html);
      } catch (Exception e) {
       Log.e(TAG, e.toString());
      }

      
      
      
      return null;
     }

     @Override
     protected void onPostExecute(String result) {//result参数就是你doInBackground这个方法return的值
      //textView.setText(result);//更新UI
      DemoAdapter demoAdapter = new DemoAdapter();
      listView.setAdapter(demoAdapter);
     }

     @Override
     protected void onPreExecute() {
      // TODO Auto-generated method stub
      super.onPreExecute();
     }

     @Override
     protected void onProgressUpdate(Integer... values) {
      // TODO Auto-generated method stub
      super.onProgressUpdate(values);
     }
     
     

    }
   
    public class JSONPersonService {
     
     public  List<Person> getJsonPersons(String html) throws Exception{
       persons =  new ArrayList<Person>();
       
  
  
      
      
      
      JSONObject josnObject = new JSONObject(html);
      //value值后面是个大括号,所以也是一个JSONObject对象,通过这种方式获取这个对象
      JSONObject jsonValue = josnObject.getJSONObject("value");
      //articlelist值后面是个中括号,所以是个JSONArray,通过这种方式获取JSONArray
      JSONArray array = jsonValue.getJSONArray("articlelist");
      for (int i = 0; i < array.length(); i++) {
       //从JSONArray集合中挨个取出JSONObject对象
       JSONObject JsonPerson = array.getJSONObject(i);
       //title,summary对应的值为String类型的,所以用JsonPerson.getString("")这个方法
       Person person = new Person(JsonPerson.getString("title"),JsonPerson.getString("summary"));
       persons.add(person);
      }
      
      
      
//      JSONArray array = new JSONArray(json);
//      
//      for(int i=0; i < array.length() ; i++){
//       //JSONObject Person = (JSONObject) new JSONTokener(json).nextValue();
//       JSONObject Person = array.getJSONObject(i);
//       Person person = new Person(Person.getString("title"),Person.getString("summary"));
//       
//       persons.add(person);
//       
//       
//      }
      return persons;
     }
     
    }

 

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }

   
}

 

 

 

得到json的数据

 

 

package com.example.service;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class HtmlService {
 
 /**
  * 获取网页的源代码
  * @param path 网页路径
  * @return
  * @throws Exception
  */
 public static String getHtml(String path) throws Exception{
  URL url = new URL(path);
  HttpURLConnection conn = (HttpURLConnection)url.openConnection();
  conn.setConnectTimeout(5 * 1000);
  conn.setRequestMethod("GET");
  if(conn.getResponseCode()==200){
   InputStream inStream = conn.getInputStream();
   byte[] data = readInputStream(inStream);//html的二进制数据
   //return new String(data);这是直接返回的数据,跟下面两行是一样的意思
   String json = new String(data,"UTF-8");
   return json;
  }else{
   throw new Exception("请求失败");
  }  
 }
 
 /**
  * 从输入流读取数据
  * @param inStream
  * @return
  * @throws Exception
  */
 public static byte[] readInputStream(InputStream inStream) throws Exception{
  ByteArrayOutputStream outSteam = new ByteArrayOutputStream();
  byte[] buffer = new byte[1024];
  int len = 0;
  while( (len = inStream.read(buffer)) !=-1 ){
   outSteam.write(buffer, 0, len);
  }
  outSteam.close();
  inStream.close();
  return outSteam.toByteArray();
 }


}

 

javabean:

 

package com.example.domain;

public class Person {
 private String title;
 private String  summary;
 
 public Person(){}
 
 
 
 public Person(String title, String summary) {
  this.title = title;
  this.summary = summary;
 }

 

 public String getTitle() {
  return title;
 }

 

 public void setTitle(String title) {
  this.title = title;
 }

 

 public String getSummary() {
  return summary;
 }

 

 public void setSummary(String summary) {
  this.summary = summary;
 }

 

 @Override
 public String toString() {
  return "Person [title=" + title + ", summary=" + summary + "]";
 }

 

 
}

 

下面是两个XML文件和manifest文件

 

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
  <LinearLayout
   android:orientation="horizontal"
   android:layout_width="wrap_content"
   android:layout_height="wrap_content">
    />
   <TextView
    android:layout_width="150dip"
    android:layout_height="wrap_content"
    android:text="标签"
    />
   <TextView
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="明细"
    />
 </LinearLayout>
 <ListView
     android:layout_width="fill_parent"
     android:layout_height="wrap_content"
     android:id="@+id/listView"
     />
</LinearLayout>

 

 

 

 

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:orientation="horizontal"
  android:layout_width="fill_parent"
  android:layout_height="wrap_content">
  <TextView
   android:layout_width="150dip"
   android:layout_height="wrap_content"
   android:text="xxxxx"
   android:id="@+id/title"
   />
  <TextView
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="明细"
     android:id="@+id/summary"
    />
 
</LinearLayout>

 

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.personjson"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="15" />
     <!-- 访问internet权限 -->
<uses-permission android:name="android.permission.INTERNET"/>

    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".MainActivity"
            android:label="@string/title_activity_main" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>