Android开发-Volley-解析Json使用方法-4-完整Demo-AndroidStudio

52 篇文章 0 订阅
9 篇文章 1 订阅

AndroidManifest.xml:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.iwanghang.volleydemo">

    <!-- 网络权限 -->
    <uses-permission android:name="android.permission.INTERNET" />

    <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>
MainActivity.java:

package com.iwanghang.volleydemo;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

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

import com.iwanghang.volleydemo.Volley4Json.VolleyCallBack;

public class MainActivity extends Activity implements OnClickListener{

    private Button button_volley_1; // 测试按钮一 解析标题和简介
    private Button button_volley_2; // 测试按钮二 解析标题
    private Button button_volley_3; // 测试按钮三 显示原始json串
    private TextView textView_content; // 显示结果

    private String title;
    private String allTitle = "";
    private String desc;
    private String allDesc = "";
    private String td;
    private String allTd = "";

    private Volley4Json volley4Json;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        button_volley_1 = (Button) findViewById(R.id.button_volley_1); // 测试按钮一 解析标题和简介
        button_volley_2 = (Button) findViewById(R.id.button_volley_2); // 测试按钮二 解析标题
        button_volley_3 = (Button) findViewById(R.id.button_volley_3); // 测试按钮三 显示原始json串
        textView_content = (TextView) findViewById(R.id.textView_content); // 显示结果

        button_volley_1.setOnClickListener(this); // 测试按钮一 解析标题和简介 点击监听
        button_volley_2.setOnClickListener(this); // 测试按钮二 解析标题 点击监听
        button_volley_3.setOnClickListener(this); // 测试按钮三 显示原始json串 点击监听

        volley4Json = new Volley4Json(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.button_volley_1: // 测试按钮一 解析标题和简介
                // 获取Json
                volley4Json.getJsonResult(new VolleyCallBack() {
                    @Override
                    public void onSuccess(JSONObject result) {
                        // 测试按钮一 解析标题和简介
                        try {
                            JSONArray jsonArray = result.getJSONArray("data");
                            for (int i = 0; i < jsonArray.length(); i++) {
                                JSONObject object2 = jsonArray.getJSONObject(i);
                                Log.e("TAG", object2.getString("title"));
                                title = object2.getString("title");
                                desc = object2.getString("desc");
                                td = "《" + object2.getString("title") + "》" + object2.getString("desc");
                                allTd = allTd + "" + i + "." +  td  + "\n\n";
                            }
                            textView_content.setText(allTd);
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                });
                break;
            case R.id.button_volley_2: // 测试按钮二 解析标题
                // 获取Json
                volley4Json.getJsonResult(new VolleyCallBack() {
                    @Override
                    public void onSuccess(JSONObject result) {
                        // 测试按钮二 解析标题
                        try {
                            JSONArray jsonArray = result.getJSONArray("data");
                            for (int i = 0; i < jsonArray.length(); i++) {
                                JSONObject obj2 = jsonArray.getJSONObject(i);
                                Log.e("TAG", obj2.getString("title"));
                                title = obj2.getString("title");
                                allTitle = allTitle + "" + i + "." +  title  + "\n\n";
                            }
                            textView_content.setText(allTitle);
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                });
                break;
            case R.id.button_volley_3: // 测试按钮三 显示原始json串
                // 获取Json
                volley4Json.getJsonResult(new VolleyCallBack() {
                    @Override
                    public void onSuccess(JSONObject result) {
                        textView_content.setText(result.toString());
                    }
                });
                break;
        }
    }

}

Volley4Json.java:

package com.iwanghang.volleydemo;

import android.content.Context;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;

import org.json.JSONObject;

public class Volley4Json {

    public static Context context;
    public Volley4Json(Context context){
        this.context = context;
    }

    /**
     * 获取Json
     */
    public static void getJsonResult(final VolleyCallBack volleyCallBack) {
        // 初始化一个请求队列
        RequestQueue requestQueue = Volley.newRequestQueue(context);
        // json串: http://www.ytiantuan.com//api.php/index/index.html
        String jsonUrl = "http://api.zsreader.com/v2/pub/channel/list?&page=1&tp=1&size=20";
        // 根据给定的URL新建一个请求
        JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, jsonUrl, null, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {
                // 在这里操作UI组件是安全的,因为响应返回时这个函数会被post到UI线程来执行
                // 在这里尽情蹂躏响应的response。

                volleyCallBack.onSuccess(response);

                //成功的回调
                //System.out.println("成功返回:"+ response.toString());
            }
        }, new Response.ErrorListener(){
            @Override
            public void onErrorResponse(VolleyError error) {
                // 出错了怎么办?凉拌!并且在这里拌。
                System.out.println("发生了一个错误!");
                error.printStackTrace();
            }
        });
        // 把这个请求加入请求队列
        requestQueue.add(jsonObjectRequest);
    }

    /**
     * VolleyCallback
     */
    public interface VolleyCallBack{
        void onSuccess(JSONObject result);
    }
}
activity_main.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">

    <!-- 测试按钮 -->
    <RelativeLayout
        android:id="@+id/button_layout"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content">
        <Button
            android:id="@+id/button_volley_1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="解析标题和简介"/>
        <Button
            android:id="@+id/button_volley_2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="解析标题"
            android:layout_alignParentTop="true"
            android:layout_centerHorizontal="true" />
        <Button
            android:id="@+id/button_volley_3"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="显示原始json串"
            android:layout_alignParentTop="true"
            android:layout_alignParentRight="true"
            android:layout_alignParentEnd="true" />
    </RelativeLayout>

    <TextView
        android:id="@+id/textView_content"
        android:layout_below="@+id/button_layout"
        android:text="内容"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</RelativeLayout>

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值