手记

json客户端,listview写不来服务器

http://www.imooc.com/video/8334
写不来服务器,url可以相应替换
主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"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.example.httptest3.MainActivity" >

    <ListView
        android:id="@+id/listView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true" >
    </ListView>

</RelativeLayout>

item xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <ImageView
        android:id="@+id/imageView"
        android:layout_width="150dp"
        android:layout_height="100dp"
        android:layout_alignParentLeft="true"

      />
    <RelativeLayout 
        android:padding="2dp"
        android:layout_toRightOf="@+id/imageView"
         android:layout_width="fill_parent"
        android:layout_height="100dp"

        >

        <TextView
            android:textSize="25sp"
            android:text="name"
            android:id="@+id/name"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            />
        <TextView
            android:textSize="25sp"
            android:layout_below="@+id/name"
            android:text="age"
            android:id="@+id/age"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            />

        <TextView
            android:layout_below="@+id/age"
            android:textSize="15sp"
            android:text="school1"
            android:id="@+id/school1"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            />

        <TextView
            android:layout_below="@+id/school1"
            android:text="school2"

            android:textSize="15sp"

            android:id="@+id/school2"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            />

    </RelativeLayout>

</RelativeLayout>

MainActivity:

package com.example.httptest3;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ListView;

public class MainActivity extends Activity {
    private ListView listView;
    private JsonAdapter adapter;
    private Handler handler = new Handler();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        listView = (ListView) findViewById(R.id.listView);
        adapter = new JsonAdapter(this);
        String url = "http://www.baidu.com";
        new HttpJson(url, listView, adapter, handler).start();

    }

}

person类

package com.example.httptest3;

import java.util.List;

public class Person {

    private String name;
    private int age;
    private String url;
    private List<SchoolInfo> schoolInfo;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    public List<SchoolInfo> getSchoolInfo() {
        return schoolInfo;
    }

    public void setSchoolInfo(List<SchoolInfo> schoolInfo) {
        this.schoolInfo = schoolInfo;
    }

}

result类

package com.example.httptest3;

import java.util.List;

public class Result {

    private int result;
    private List<Person> personData;

    public int getResult() {
        return result;
    }

    public void setResult(int result) {
        this.result = result;
    }

    public List<Person> getPersonData() {
        return personData;
    }

    public void setPersonData(List<Person> personData) {
        this.personData = personData;
    }

}

schoolinfo类

package com.example.httptest3;

import java.util.List;

public class Result {

    private int result;
    private List<Person> personData;

    public int getResult() {
        return result;
    }

    public void setResult(int result) {
        this.result = result;
    }

    public List<Person> getPersonData() {
        return personData;
    }

    public void setPersonData(List<Person> personData) {
        this.personData = personData;
    }

}

httpimage类

package com.example.httptest3;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Handler;
import android.widget.ImageView;

public class HttpImage extends Thread {
    private ImageView imageView;
    private String url;
    private Handler handler;

    public HttpImage(ImageView imageView, String url, Handler handler) {
        super();
        this.imageView = imageView;
        this.url = url;
        this.handler = handler;
    }

    @Override
    public void run() {
        try {
            URL hurl = new URL(url);
            HttpURLConnection conn = (HttpURLConnection) hurl.openConnection();
            conn.setReadTimeout(5000);
            conn.setRequestMethod("GET");
            InputStream in = conn.getInputStream();
            final Bitmap bitmap = BitmapFactory.decodeStream(in);
            handler.post(new Runnable() {

                @Override
                public void run() {
                    // TODO Auto-generated method stub
                    imageView.setImageBitmap(bitmap);
                }
            });

        } catch (MalformedURLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

}

httpjson类

package com.example.httptest3;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

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

import android.content.Context;
import android.os.Handler;
import android.widget.ListView;
import android.widget.Toast;

public class HttpJson extends Thread {

    private String url;

    private Context context;
    private ListView listView;
    private JsonAdapter adapter;
    private Handler handler;

    public HttpJson(String url, ListView listView, JsonAdapter adapter,
            Handler handler) {

        this.url = url;

        this.listView = listView;
        this.adapter = adapter;
        this.handler = handler;
    }

    @Override
    public void run() {

        URL hurl;
        try {
            hurl = new URL(url);
            HttpURLConnection conn = (HttpURLConnection) hurl.openConnection();
            conn.setReadTimeout(5000);
            conn.setRequestMethod("GET");
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    conn.getInputStream()));
            StringBuffer sb = new StringBuffer();
            String str;
            while ((str = reader.readLine()) != null) {
                sb.append(str);
            }
            final List<Person> data = pasJson(sb.toString());
            handler.post(new Runnable() {

                @Override
                public void run() {
                    // TODO Auto-generated method stub
                    adapter.setData(data);
                    listView.setAdapter(adapter);
                }
            });

        } catch (MalformedURLException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        } catch (ProtocolException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

    private List<Person> pasJson(String json) {
        try {
            JSONObject object = new JSONObject(json);
            List<Person> persons = new ArrayList<Person>();

            int result = object.getInt("result");
            if (result == 1) {
                JSONArray personData = object.getJSONArray("personData");
                for (int i = 1; i < personData.length(); i++) {
                    Person personObject = new Person();
                    persons.add(personObject);
                    JSONObject person = personData.getJSONObject(i);
                    String name = person.getString("name");
                    personObject.setName(name);
                    String url = person.getString("url");
                    personObject.setUrl(url);
                    int age = person.getInt("age");
                    personObject.setAge(age);
                    List<SchoolInfo> schin = new ArrayList<SchoolInfo>();
                    personObject.setSchoolInfo(schin);
                    JSONArray schoolInfos = person.getJSONArray("schoolInfo");
                    for (int j = 0; j < schoolInfos.length(); j++) {
                        JSONObject school = schoolInfos.getJSONObject(i);
                        String schoolName = school.getString("school_name");
                        SchoolInfo info = new SchoolInfo();
                        info.setSchool_name(schoolName);
                        schin.add(info);
                    }

                }

                return persons;

            } else {
                Toast.makeText(context, "error", 1500).show();
            }

        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
    }

}

jsonadapter类

package com.example.httptest3;

import java.util.List;

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

public class JsonAdapter extends BaseAdapter {
    private List<Person> list;
    private Context context;
    private LayoutInflater inflater;
    private Handler handler;

    public JsonAdapter(List<Person> list, Context context) {
        super();
        this.list = list;
        this.context = context;
        inflater = LayoutInflater.from(context);
    }

    public JsonAdapter(Context context) {

        this.context = context;
        inflater = LayoutInflater.from(context);

    }

    public void setData(List<Person> data) {
        this.list = data;

    }

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

    @Override
    public Object getItem(int position) {
        // TODO Auto-generated method stub
        return list.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
        Holder holder = null;
        if (convertView == null) {
            convertView = inflater.inflate(R.layout.item, null);
            holder = new Holder(convertView);
            convertView.setTag(holder);
        } else {
            holder = (Holder) convertView.getTag();
        }
        Person person = list.get(position);
        holder.name.setText(person.getName());
        holder.age.setText(""+person.getAge());
        List<SchoolInfo> schools = person.getSchoolInfo();

        holder.school1.setText((schools.get(0)).getSchool_name());
        holder.school2.setText((schools.get(1)).getSchool_name());
        new HttpImage(holder.imageView, person.getUrl(), handler).start();

        return null;
    }

    class Holder {
        private TextView name;
        private TextView age;
        private TextView school1;
        private TextView school2;
        private ImageView imageView;

        public Holder(View view) {
            name = (TextView) view.findViewById(R.id.name);
            age = (TextView) view.findViewById(R.id.age);
            school1 = (TextView) view.findViewById(R.id.school1);
            school2 = (TextView) view.findViewById(R.id.school2);
            imageView = (ImageView) view.findViewById(R.id.imageView);

        }

    }

}
2人推荐
随时随地看视频
慕课网APP