Android----通过接口从网上拿数据(一)

package www.wulian15.com.websitetest;

import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.ListView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.json.JSONObject;

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

public class Phpactivity extends AppCompatActivity  {
       List<Stu> stulist=null;
ListView listView;
    //定义一个在主线程和子线程直接进行通信的一个**东西  handler
    private Handler handler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what)
            {
                case 200:
                    //完成数据绑定
                if(stulist!=null)
                {
                    //绑定数据
                    StuAdapter stuAdapter=new StuAdapter(stulist,Phpactivity.this);
                    listView.setAdapter(stuAdapter);
                }

                    break;
                case  -1:
                    //获取失败
                    Toast.makeText(Phpactivity.this,"获取失败",Toast.LENGTH_SHORT).show();
                    break;
                case -2:
                    //获取发生异常
                    Toast.makeText(Phpactivity.this,"获取发生异常",Toast.LENGTH_SHORT).show();
                    break;
                default:
                   //其他情况
                    Toast.makeText(Phpactivity.this,"获取发生异常",Toast.LENGTH_SHORT).show();
            }

        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_phpctivity);
        listView=(ListView)findViewById(R.id.lv_stus);

        //从缓存获取数据
        if(getDataFromCache())
        {
            //绑定数据
            StuAdapter stuAdapter=new StuAdapter(stulist,Phpactivity.this);
            listView.setAdapter(stuAdapter);
        }
        else
        {
            //从服务器获取数据
            getDataFromService();

        }

    }
    private  String inputstream2string(InputStream inputStream)
    {
        try {
            ByteArrayOutputStream baos=new ByteArrayOutputStream();
            int length=0;
            byte[] buffer=new byte[1024];
            while((length=inputStream.read(buffer))!=-1){
                baos.write(buffer, 0, length);
            }
            inputStream.close();
            baos.close();
            //或者用这种方法
            //byte[] result=baos.toByteArray();
            //return new String(result);
            return baos.toString();
        } catch (Exception e) {
            e.printStackTrace();
            return "获取失败";
        }
    }
    ///返回true 说明成功从cache拿到数据 返回false 说明没有拿到
    private boolean getDataFromCache()
    {
        try {
            SharedPreferences sp = Phpactivity.this.getSharedPreferences("person", MODE_PRIVATE);
            String data = sp.getString("studata", "");  //所有信息
            JSONObject jsonObject=new JSONObject(data);
            String studata= jsonObject.getString("data");
            //是否过期

            if (data != "") {
                Gson gson = new Gson();
                stulist = gson.fromJson(data, new TypeToken<List<Stu>>() {
                }.getType());
                //暂时没有时间过期的判断
                return true;
            } else {
                stulist=null;
                return false;
            }
        }catch (Exception ex)
        {
            ex.printStackTrace();
            stulist=null;
            return false;
        }

    }
    private  void getDataFromService()
    {
        final String  path="http://192.168.1.108/index.php";
        // 开线程
        new Thread(){
            @Override
            public void run() {
                super.run();
                //获取数据
                try {
                    URL url = new URL(path);
                    HttpURLConnection conn=(HttpURLConnection)url.openConnection();
                    conn.setRequestMethod("GET");  //必须大写
                    conn.setConnectTimeout(5000);
                    Log.d("zh","try -1 ");
                    int code=conn.getResponseCode();
                    if(code==200)
                    {
                        Log.d("zh","code==200 ");
                        //请求成功
                        InputStream inputStream=conn.getInputStream();
                        //然后把输入流转为字符串 。上网找一个把流转为字符串的函数
                        String abc=inputstream2string(inputStream);
                        //解析json字符串
                        //先拿到code 。 判断code是否等于200
                        //  {"code":200,"pageindex":10,"isover":1,"data":[{"name":"\u5f20\u5b8f90","age":91},{"name":"\u5f20\u5b8f91","age":92},{"name":"\u5f20\u5b8f92","age":93},{"name":"\u5f20\u5b8f93","age":94},{"name":"\u5f20\u5b8f94","age":95},{"name":"\u5f20\u5b8f95","age":96},{"name":"\u5f20\u5b8f96","age":97},{"name":"\u5f20\u5b8f97","age":98},{"name":"\u5f20\u5b8f98","age":99},{"name":"\u5f20\u5b8f99","age":100}]}

                        JSONObject jsonObject=new JSONObject(abc);
                        if(jsonObject.getString("code").equals("200"))
                        {
                            //如果等于200。 服务器数据有效的

                            String studata= jsonObject.getString("data");
                            Gson gson=new Gson();

                            //studata=[{"name":"\u5f20\u5b8f90","age":91},。。。。]
                            List<Stu> stulist = gson.fromJson(studata, new TypeToken<List<Stu>>(){}.getType());
                            // 程序如果走到这个位置 。说明数据符合json格式。这时候我要把数据使用sharedpreference保存起来
                            //android 内存缓存
                            SharedPreferences sp=getSharedPreferences("person",MODE_PRIVATE); //person是文件名.
                            SharedPreferences.Editor  editor=sp.edit();
                            editor.putString("studata",abc);//按照关键字 studata。  把字符串保存起来

                            Log.d("zh","stulist 获取数据正常");
                            Message message=new Message();
                            message.obj=abc;  //定义带有数据的消息
                            message.what=200; //200代码获取数据正常
                            handler.sendMessage(message);
                            Log.d("zh","发送消息正常");
                        }
                        else
                        {
                            //返回码不是200的情况
                            Message message=new Message();
                            message.obj=abc;  //定义带有数据的消息
                            message.what=202; //200代码获取数据正常
                            handler.sendMessage(message);
                            Log.d("zh","发送消息正常");
                        }


                    }
                    else
                    {
                        //请求失败
                        Message message=new Message();
                        message.what=-1; //-1  代码获取数据失败
                        handler.sendMessage(message);
                        Log.d("zh","请求失败");
                    }
                }
                catch (Exception ex)
                {
                    Message message=new Message();
                    message.what=-2; //-1  代码获取数据时发生异常情况
                    //发送消息
                    handler.sendMessage(message);
                    Log.d("zh","Exception");

                }
            }
        }.start();

    }
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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=".Phpactivity">
    <ListView
        android:id="@+id/lv_stus"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

    </ListView>
</LinearLayout>
package www.wulian15.com.websitetest;

import android.app.Activity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

import java.util.List;

/**
 * Created by Administrator on 2017/5/15.
 */
public class StuAdapter extends BaseAdapter {
    public  List<Stu> list;
    public Activity activity;
    public StuAdapter(List<Stu> list,Activity activity)
    {
        this.list=list;
        this.activity=activity;
    }
 public void setList(List<Stu> list)
 {
     this.list=list;
 }
    @Override
    public int getCount() {
        return list.size();
    }

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

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

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        //数据放到模版中
        View view=View.inflate(activity,R.layout.item_listview,null);
        TextView textView_name=(TextView) view.findViewById(R.id.tv_name);
        TextView textView_age=(TextView) view.findViewById(R.id.tv_age);

        //放数据到控件上
        textView_age.setText(list.get(position).getAge()+"");
        textView_name.setText(list.get(position).getName());

        return view;
    }
}
package www.wulian15.com.websitetest;

/**
 * Created by Administrator on 2017/5/15.
 */
public class Stu {
    String name;
    int age;

    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;
    }
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">
<TextView
    android:id="@+id/tv_name"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" />
 <TextView
        android:id="@+id/tv_age"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
</LinearLayout>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值