[在Android中使用Volley提取数据

问题描述 投票:0回答:2

我正在学习如何在Android应用程序中连接API。我开始使用Volley在Application中显示JSON数据,但我不知道我在哪里做错。我的JSON文件包含一个名称。JSON文件链接:http://www.mocky.io/v2/5e97251e3000006300b6dc2d

activity_main(.xml):

<TextView
        android:id="@+id/text_view_result1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="24dp" />

MainActivity.java

public class MainActivity extends AppCompatActivity {

    TextView  text1;
    RequestQueue mQueue;
    String name;
    String url = "http://www.mocky.io/v2/5e97251e3000006300b6dc2d";

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

       // mTextViewResult = findViewById(R.id.text_view_result);
        text1 = findViewById(R.id.text_view_result1);
        Button buttonParse = findViewById(R.id.button_parse);

        mQueue = Volley.newRequestQueue(this);
        sendjsonrequest();


    }

    public void sendjsonrequest(){
        JsonObjectRequest jsonObjectRequest= new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {
                try {
                    name=response.getString("name");
                    text1.setText(name);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {

            }
        });
        mQueue.add(jsonObjectRequest);
    }
}
java android android-volley
2个回答
1
投票
<uses-permission android:name="android.permission.INTERNET" />

0
投票
顺便说一句,仅使用https://www.npoint.io/来托管您的测试JSON。
© www.soinside.com 2019 - 2024. All rights reserved.