美文网首页需要使用
JSON解析 将数据显示到ListView上

JSON解析 将数据显示到ListView上

作者: Summer_27d1 | 来源:发表于2018-07-12 10:37 被阅读140次

    MainActivity的布局:

    image.png
    item_xml:
    ···
    <?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/text_title"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="TextView"
        android:textColor="@android:color/background_dark"
        android:textSize="25sp" />
    
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">
    
        <TextView
            android:id="@+id/text_date"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="TextView" />
    
        <TextView
            android:id="@+id/text_src"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:gravity="right"
            android:text="TextView" />
    </LinearLayout>
    

    </LinearLayout>
    ···
    首先创建联网对象,进行数据连接获取导数据,
    在通过Json解析,将数据解析出来,解析出的数据保存到Map集合 中,设置到ListView中:
    ********具体代码如下********
    *********MainActivity中*******************
    ···
    package com.example.wangye.jsontest;

    import android.os.Bundle;
    import android.os.Handler;
    import android.os.Message;
    import android.support.v7.app.AppCompatActivity;
    import android.view.View;
    import android.widget.Button;
    import android.widget.EditText;
    import android.widget.ListView;

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

    import java.io.ByteArrayOutputStream;
    import java.io.InputStream;
    import java.net.HttpURLConnection;
    import java.net.URL;
    import java.util.ArrayList;
    import java.util.HashMap;

    public class MainActivity extends AppCompatActivity {
    ArrayList<HashMap<String,String>> arrayList = new ArrayList<>();
    Button bt;
    EditText ed;
    ListView listView;
    MyAdapter adapter;
    Handler handler = new Handler(){
    @Override
    public void handleMessage(Message msg) {
    if(msg.what == 1){
    adapter = new MyAdapter(MainActivity.this,arrayList);
    listView.setAdapter(adapter);
    }
    }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        init();
    }
    
    public void init(){
        bt = (Button) findViewById(R.id.button);
        bt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //清空集合
                arrayList.clear();
                new Thread(){
                    @Override
                    public void run() {
                        getDataByNet();
                    }
                }.start();
    
            }
        });
        ed = (EditText) findViewById(R.id.editText);
        listView = (ListView) findViewById(R.id.listview);
    }
    
    public void getDataByNet(){
        try {
            URL url = new URL("http://op.juhe.cn/onebox/news/query?q="
                    +ed.getText().toString()+"&dtype=&key=477bff0267dcc1db7dfa8771c77235b2");
            HttpURLConnection con = (HttpURLConnection) url.openConnection();
            con.setRequestMethod("GET");
            con.setDoInput(true);
            con.setDoOutput(true);
            con.setConnectTimeout(10000);
            con.setReadTimeout(10000);
            con.connect();
            if(con.getResponseCode() == 200){
                InputStream is = con.getInputStream();
                ByteArrayOutputStream bs = new ByteArrayOutputStream();
                byte buffer [] = new byte[512];
                int length = -1;
                while( (length = is.read(buffer)) != -1){
                    bs.write(buffer,0,length);
                    bs.flush();
                }
                is.close();
                bs.close();
                parseJson(bs.toString());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    
    public void parseJson(String json){
        try {
            JSONObject jsonObject = new JSONObject(json);
            int code = jsonObject.getInt("error_code");
            if(code == 213802){
                HashMap<String,String> map = new HashMap<>();
                map.put("title","抱歉,没有搜索到相关信息...");
                map.put("pdate","");
                map.put("src","");
                arrayList.add(map);
            }else{
                JSONArray jsonArray = jsonObject.getJSONArray("result");
                for (int i = 0; i < jsonArray.length(); i++) {
                    HashMap<String,String> map = new HashMap<>();
                    JSONObject jo = jsonArray.getJSONObject(i);
                    map.put("title",jo.getString("title"));
                    map.put("pdate",jo.getString("pdate"));
                    map.put("src",jo.getString("src"));
                    arrayList.add(map);
                }
            }
    
    
            handler.sendEmptyMessage(1);
    
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    

    }

    ···
    -------------MyAdapter中-------
    ···
    package com.example.wangye.jsontest;

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

    import java.util.ArrayList;
    import java.util.HashMap;

    /**

    • Created by wangye on 2018/7/9.
      */

    public class MyAdapter extends BaseAdapter {
    Context c;
    ArrayList<HashMap<String, String>> arrayList;

    public MyAdapter(Context c, ArrayList<HashMap<String, String>> arrayList) {
        this.c = c;
        this.arrayList = arrayList;
    }
    
    @Override
    public int getCount() {
        return arrayList.size();
    }
    
    @Override
    public Object getItem(int i) {
        return arrayList.get(i);
    }
    
    @Override
    public long getItemId(int i) {
        return 0;
    }
    
    @Override
    public View getView(int i, View view, ViewGroup viewGroup) {
        view = View.inflate(c,R.layout.adapter,null);
        TextView txTitle = view.findViewById(R.id.text_title);
        txTitle.setText(arrayList.get(i).get("title"));
        TextView txDate = view.findViewById(R.id.text_date);
        txDate.setText(arrayList.get(i).get("pdate"));
        TextView txSrc = view.findViewById(R.id.text_src);
        txSrc.setText(arrayList.get(i).get("src"));
        return view;
    }
    

    }

    ···
    效果图:


    image.png
    image.png

    相关文章

      网友评论

        本文标题:JSON解析 将数据显示到ListView上

        本文链接:https://www.haomeiwen.com/subject/foylpftx.html