Android 实现json网络数据通过BaseAdapter加载到ListView中

效果图,有点没有设计美感,哈哈,凑合着看吧

Android 实现json网络数据通过BaseAdapter加载到ListView中_第1张图片

关于json,我对json有一定的了解,所以这个项目我用自己构建的服务器输出json数据,文件名json.php
php代码如下

"{'data':1,'students':[{'name':'张三','age':22,'url':'http://192.168.1.103/pictures/pic1.jpg'},{'name':'李四','age':23,'url':'http://192.168.1.103/pictures/pic2.jpg'},{'name':'王五','age':26,'url':'http://192.168.1.103/pictures/pic3.jpg'},{'name':'刘流','age':32,'url':'http://192.168.1.103/pictures/pic4.jpg'},{'name':'陈曦','age':22,'url':'http://192.168.1.103/pictures/pic5.jpg'}]}"; 
echo $json; 
?>

Android文件目录图:

Android 实现json网络数据通过BaseAdapter加载到ListView中_第2张图片

Android配置页AndroidMenifests.xml代码如下


<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.imooc.capton.json">
<uses-permission android:name="android.permission.INTERNET">uses-permission>
    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

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

manifest>

activity_main.xml


<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_main"
    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.imooc.capton.json.MainActivity">

    <ListView
        android:id="@+id/listview"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
    ListView>


RelativeLayout>

student.xml


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:orientation="horizontal"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <ImageView
        android:layout_width="180dp"
        android:layout_height="120dp"
        android:src="@mipmap/ic_launcher"
        android:layout_gravity="center"
        android:id="@+id/imageView" />

    <LinearLayout
        android:orientation="vertical"
        android:layout_gravity="center"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <TextView
            android:text="TextView"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:textSize="20dp" 
            android:id="@+id/name" />

        <TextView
            android:text="TextView"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@+id/age" />
    LinearLayout>
LinearLayout>

MainActivity.java

package com.imooc.capton.json;

import android.content.Context;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ListView;

public class MainActivity extends AppCompatActivity {
    Context context=this;
    ListView listView;
    Handler handler;
    JsonAdapter jsonAdapter;
    String url="http://192.168.1.103/json.php";//这个url随你设置的php页面而变动。
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        listView= (ListView) findViewById(R.id.listview);
        handler=new Handler();//获得一个handler对象,为后面的各个线程提供处理UI的依据
        new JsonThread(context, listView, url,handler).start();
    }
}

JsonThread.java

package com.imooc.capton.json;

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

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

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;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by CAPTON on 2016/11/25.
 */
//访问目标网址,得到json数据,保存List数据,等待传入JsonAdapter
public class JsonThread extends Thread {
    Context context;
    ListView listView;
    String url;
    Handler handler;//关键参数 整个小项目中的核心之一,会在JsonThread和JsonAdapter,ImageThread中传递,用于更新UI界面
    List students;
    JsonAdapter jsonAdapter;

    public JsonThread(Context context, ListView listView, String url,Handler handler ) {
        this.context=context;
        this.listView=listView;
        this.url=url;
        this.handler=handler;
    } 
    //从String中解析所需数据,如name,age,url,将他们装入Student中,再将Student逐条加入List
    private  List getStudents(String data){
        List students=new ArrayList();
        try {
            JSONObject object=new JSONObject(data);
            if(object.getInt("data")==1){
                JSONArray jsonArray=object.getJSONArray("students");
                for(int i=0;inew Student();
                    student.name=studentObject.getString("name");
                    System.out.println(student.name);
                    student.age=studentObject.getInt("age");
                    System.out.println(student.age);
                    student.url=studentObject.getString("url");
                    System.out.println(student.url);
                    students.add(student);
                }
            }
        } catch (JSONException e) {
            e.printStackTrace();
        } 
        return  students;
    }

    @Override
    public void run() {

        //从网络中获取数据,转换为String类型
        StringBuffer result=new StringBuffer();
        try {
            URL Url=new URL(url);
            HttpURLConnection connection= (HttpURLConnection) Url.openConnection();
            connection.setRequestMethod("GET");
            connection.setReadTimeout(5000);
            InputStream inputStream=connection.getInputStream();
            BufferedReader bufferedReader=new BufferedReader(new   InputStreamReader(inputStream));
            String line;
            while ((line=bufferedReader.readLine())!=null){
                result.append(line);
            }
            System.out.println(result);
            students=getStudents(result.toString());//调用解析方法
            inputStream.close();
            bufferedReader.close();

            handler.post(new Runnable() {
                @Override
                public void run() {

                    jsonAdapter=new JsonAdapter(context,handler,students); //传递关键参数MainActivity上下文对象context,MainActivity主线程的handler对象,处理好的List对象
                    listView.setAdapter(jsonAdapter);
                }
               }); 
           } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } 
        super.run();
    } 
}

JsonAdapter.java

package com.imooc.capton.json;

import android.content.Context;
import android.graphics.Bitmap;
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.ListView;
import android.widget.TextView;

import java.util.List;

/**
 * Created by CAPTON on 2016/11/25.
 */
// 适配器,等待被JsonThread调用

public class JsonAdapter extends BaseAdapter {

    List students;
    Context context;
    LayoutInflater inflater;
    Handler handler;

    public JsonAdapter(Context context,Handler handler,List students) {
        this.handler=handler;
        this.context=context;
        this.students=students;
        inflater=LayoutInflater.from(context);//从MainActivity中上下文对象中获取LayoutInflater;所以说这个context,和handler对象很重要,贯穿整项目
    }

    @Override
    public int getCount() {
        return students.size();
    }

    @Override
    public Object getItem(int position) {
        return students.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    //重写getView方法,即设置ListView每一项的视图
    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder holder=null;

       if(convertView==null){
           convertView=inflater.inflate(R.layout.student,null);
           holder=new ViewHolder(convertView);
           convertView.setTag(holder);//设置tag
       }else {
           holder= (ViewHolder) convertView.getTag(); //获取tag
       }
        System.out.println(String.valueOf(students.get(position).age));//测试数据是否正常
        holder.age.setText(String.valueOf(students.get(position).age));
        holder.name.setText(students.get(position).name);
        System.out.println(students.get(position).name);
        new ImageThread(students.get(position).url, handler,holder.image).start();//开启新线程下载图片并在新线程中更新UI,所以要传递handler对象
        return convertView;
     }

//用于暂时保存视图对象
     class ViewHolder{
         public TextView name;
         public TextView age;
         public ImageView image;

          public ViewHolder(View view){
              name= (TextView) view.findViewById(R.id.name);
              age= (TextView) view.findViewById(R.id.age);
              image= (ImageView) view.findViewById(R.id.imageView);
          } 
     }
}

ImageThread.java

package com.imooc.capton.json;

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

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;

/**
 * Created by CAPTON on 2016/11/25.
 */
//根据url读取图片数据,把图片Bitmap保存下来等待 JsonAdapter调用

public class ImageThread extends Thread {
    String url;
    ImageView imageView;
    Handler handler;
    public ImageThread(String url, Handler handler,ImageView imageView) {
        this.url = url;
        this.imageView=imageView;
        this.handler=handler;
    }


    @Override
    public void run() {
        try {
            final Bitmap bitmap= BitmapFactory.decodeStream(new URL(url).openStream());//简单粗暴,可能有问题,自己做的时候注意
            handler.post(new Runnable() {
                @Override
                public void run() { 
                    imageView.setImageBitmap(bitmap);
                }
            });
        } catch (IOException e) {
            e.printStackTrace();
        } 
        super.run();
    }
}

Student.java

package com.imooc.capton.json;

/**
 * Created by CAPTON on 2016/11/25.
 */
// bean数据
public class Student { 
    public String name;
    public String url;
    public int age; 
}

到此整个项目代码如上,根据慕课网nate老师的视频教程纯手打实现,感觉比他的代码要简洁一些,毕竟没有源码,鄙人在此献上代码,欢迎各位指导评论

你可能感兴趣的:(Android)