JSON解析 將數(shù)據(jù)顯示到ListView上

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>
···
首先創(chuàng)建聯(lián)網(wǎng)對(duì)象,進(jìn)行數(shù)據(jù)連接獲取導(dǎo)數(shù)據(jù)课竣,
在通過Json解析嘉赎,將數(shù)據(jù)解析出來置媳,解析出的數(shù)據(jù)保存到Map集合 中,設(shè)置到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","抱歉公条,沒有搜索到相關(guān)信息...");
            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
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末拇囊,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子靶橱,更是在濱河造成了極大的恐慌寥袭,老刑警劉巖,帶你破解...
    沈念sama閱讀 216,372評(píng)論 6 498
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件关霸,死亡現(xiàn)場(chǎng)離奇詭異传黄,居然都是意外死亡,警方通過查閱死者的電腦和手機(jī)队寇,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,368評(píng)論 3 392
  • 文/潘曉璐 我一進(jìn)店門尝江,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人英上,你說我怎么就攤上這事∑「玻” “怎么了苍日?”我有些...
    開封第一講書人閱讀 162,415評(píng)論 0 353
  • 文/不壞的土叔 我叫張陵,是天一觀的道長(zhǎng)窗声。 經(jīng)常有香客問我相恃,道長(zhǎng),這世上最難降的妖魔是什么笨觅? 我笑而不...
    開封第一講書人閱讀 58,157評(píng)論 1 292
  • 正文 為了忘掉前任拦耐,我火速辦了婚禮,結(jié)果婚禮上见剩,老公的妹妹穿的比我還像新娘杀糯。我一直安慰自己,他們只是感情好苍苞,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,171評(píng)論 6 388
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著羹呵,像睡著了一般。 火紅的嫁衣襯著肌膚如雪歉铝。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 51,125評(píng)論 1 297
  • 那天太示,我揣著相機(jī)與錄音,去河邊找鬼先匪。 笑死,一個(gè)胖子當(dāng)著我的面吹牛呀非,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播猖败,決...
    沈念sama閱讀 40,028評(píng)論 3 417
  • 文/蒼蘭香墨 我猛地睜開眼降允,長(zhǎng)吁一口氣:“原來是場(chǎng)噩夢(mèng)啊……” “哼!你這毒婦竟也來了剧董?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 38,887評(píng)論 0 274
  • 序言:老撾萬榮一對(duì)情侶失蹤尉剩,失蹤者是張志新(化名)和其女友劉穎毅臊,沒想到半個(gè)月后理茎,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體皂林,經(jīng)...
    沈念sama閱讀 45,310評(píng)論 1 310
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡蚯撩,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,533評(píng)論 2 332
  • 正文 我和宋清朗相戀三年胎挎,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片呀癣。...
    茶點(diǎn)故事閱讀 39,690評(píng)論 1 348
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡项栏,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情币厕,我是刑警寧澤芽腾,帶...
    沈念sama閱讀 35,411評(píng)論 5 343
  • 正文 年R本政府宣布,位于F島的核電站阴绢,受9級(jí)特大地震影響,放射性物質(zhì)發(fā)生泄漏呻袭。R本人自食惡果不足惜腺兴,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,004評(píng)論 3 325
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望篓足。 院中可真熱鬧闰蚕,春花似錦、人聲如沸陪腌。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,659評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽强岸。三九已至砾赔,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間暴心,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 32,812評(píng)論 1 268
  • 我被黑心中介騙來泰國打工悯衬, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留檀夹,地道東北人策橘。 一個(gè)月前我還...
    沈念sama閱讀 47,693評(píng)論 2 368
  • 正文 我出身青樓丽已,卻偏偏與公主長(zhǎng)得像,于是被迫代替她去往敵國和親沛婴。 傳聞我的和親對(duì)象是個(gè)殘疾皇子策州,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,577評(píng)論 2 353

推薦閱讀更多精彩內(nèi)容