如何用volley解析新意图中的json文件

时间:2018-06-04 06:47:19

标签: android json android-intent android-volley android-json

我正在开发一个Android应用程序,我需要从互联网上获取一些数据,如名称和链接,我看了一些关于如何使用volley来解析JSON文件并从互联网上获取数据的教程现在我想在创建新意图时显示一些数据,但它似乎不起作用我的Textview保持不变,这是代码:

    public class Main2Activity extends AppCompatActivity {

    private String radioName;
    private TextView radionametxt;
    private String radioLink;
    private TextView radiolinktxt;
    private String urlJsonArry;

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

        Intent i = getIntent();
        final String radioname = i.getStringExtra("radioname");
        setTitle(radioname);

        urlJsonArry = "https://api.myjson.com/bins/1f7y96";

        JsonArrayRequest req = new JsonArrayRequest(urlJsonArry,
                new Response.Listener<JSONArray>() {
                    @Override
                    public void onResponse(JSONArray response) {

                        try {
                            // Parsing json array response
                            // loop through each json object
                            //jsonResponse = "";
                            for (int i = 0; i < response.length(); i++) {

                                JSONObject radio = (JSONObject) response
                                        .get(i);

                               // String name = radio.getString("name");
                               // String link = radio.getString("email");

                                //radioName = name;
                               // radioLink = link;

                                radioName = radio.getString("name");
                                radioLink = radio.getString("email");

                            }
                            radionametxt = (TextView) findViewById(R.id.name);
                            radionametxt.setText(radioName);

                            radiolinktxt = (TextView) findViewById(R.id.link);
                            radiolinktxt.append(radioLink);


                        } catch (JSONException e) {
                            e.printStackTrace();
                            Toast.makeText(getApplicationContext(),
                                    "Error: " + e.getMessage(),
                                    Toast.LENGTH_LONG).show();
                        }


                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                VolleyLog.d("Error", "Error: " + error.getMessage());
                Toast.makeText(getApplicationContext(),
                        error.getMessage(), Toast.LENGTH_SHORT).show();
            }
        });
    }
}

xml代码:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.radline.radapp.radapp.Main2Activity">

<TextView
    android:id="@+id/name"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="name"
    android:textSize="40sp"
    tools:layout_constraintTop_creator="1"
    android:layout_marginTop="62dp"
    tools:layout_constraintLeft_creator="1"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    android:layout_below="@+id/link"
    android:layout_alignStart="@+id/link" />

<TextView
    android:id="@+id/link"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="link"
    android:textSize="40sp"
    tools:layout_constraintTop_creator="1"
    tools:layout_constraintBottom_creator="1"
    android:layout_marginStart="108dp"
    app:layout_constraintBottom_toBottomOf="parent"
    tools:layout_constraintLeft_creator="1"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    android:layout_marginLeft="108dp"
    app:layout_constraintVertical_bias="0.321" />

Json代码

    [
  {
    "name": "radone",
    "link": "ravi8x@gmail.com"
  }
]

1 个答案:

答案 0 :(得分:0)

我获取了JsonObject而不是JsonArray并且记得添加我之前忘记的请求队列的代码:

package com.radline.radapp.radapp;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;

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

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

public class Main2Activity extends AppCompatActivity {

    private String radioName;
    private TextView radionametxt;
    private String radioLink;
    private TextView radiolinktxt;
    private String urlJsonArry;
    private String urlJsonObj;
    private RequestQueue requestQueue;
    private static String TAG = Main2Activity.class.getSimpleName();

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

        Intent i = getIntent();
        final String radioname = i.getStringExtra("radioname");
        setTitle(radioname);


        radionametxt = (TextView) findViewById(R.id.name);
        radiolinktxt = (TextView) findViewById(R.id.link);
        requestQueue = Volley.newRequestQueue(this);
        urlJsonObj = "https://api.myjson.com/bins/t92sy";


        JsonObjectRequest jsonObjReq = new JsonObjectRequest(Method.GET,
                urlJsonObj, null, new Response.Listener<JSONObject>() {

            @Override
            public void onResponse(JSONObject response) {
                Log.d(TAG, response.toString());

                try {
                    // Parsing json object response
                    // response will be a json object
                    radioName = response.getString("name");
                    radioLink = response.getString("audiolink");


                    radionametxt.setText(radioName);
                    radiolinktxt.setText(radioLink);


                } catch (JSONException e) {
                    e.printStackTrace();
                    Toast.makeText(getApplicationContext(),
                            "Error: " + e.getMessage(),
                            Toast.LENGTH_LONG).show();
                }
               // hidepDialog();
            }
        }, new Response.ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError error) {
                VolleyLog.d(TAG, "Error: " + error.getMessage());
                Toast.makeText(getApplicationContext(),
                        error.getMessage(), Toast.LENGTH_SHORT).show();
                // hide the progress dialog
               // hidepDialog();
            }
        });

        // Adding request to request queue
        requestQueue.add(jsonObjReq);

    }
}

还将xml更改为:

 {
  "name": "Cyntric Station",
  "audiolink": "http://111.223.51.8:8000",
  "picturelink": "https://cdn.pixabay.com/photo/2018/01/04/08/04/people-3060107_960_720.jpg",
  "motto": "Your number 1 online radio station"
}