使用GSON和Volley在Android上显示JSON数据 [英] Display JSON data on Android using GSON and Volley

查看:81
本文介绍了使用GSON和Volley在Android上显示JSON数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你好,我是android编程的新手,正在尝试学习它.我遵循了教程,它是工作正常,但是我不知道如何在列表视图中显示记录.

Hello I'm new to android programming and trying to learn it. I followed this tutorial and it's working fine however I don't know how to display the records in the listview.

PostActivity.java文件来自以下教程,

The PostActivity.java file is from the tutorial is below,

package com.kylewbanks.gsonvolleytutorial;

    import android.app.Activity;
    import android.os.Bundle;
    import android.util.Log;
    import android.widget.ArrayAdapter;

    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.StringRequest;
    import com.android.volley.toolbox.Volley;
    import com.google.gson.Gson;
    import com.google.gson.GsonBuilder;

    import java.util.ArrayList;
    import java.util.Arrays;
    import java.util.List;

    import static android.R.id.list;

    public class PostActivity extends Activity {

        private static final String ENDPOINT = "https://kylewbanks.com/rest/posts.json";

        private RequestQueue requestQueue;
        private Gson gson;

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

            requestQueue = Volley.newRequestQueue(getApplicationContext());
            GsonBuilder gsonBuilder = new GsonBuilder();
            gsonBuilder.setDateFormat("M/d/yy hh:mm a");
            gson = gsonBuilder.create();

            fetchPosts();
        }

        private void fetchPosts() {
            StringRequest request = new StringRequest(Request.Method.GET, ENDPOINT, onPostsLoaded, onPostsError);

            requestQueue.add(request);
        }

        private final Response.Listener<String> onPostsLoaded = new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                //Log.i(PostActivity.class.getSimpleName(), response);

                List<Post> posts = Arrays.asList(gson.fromJson(response, Post[].class));
                //Log.i(PostActivity.class.getSimpleName(), posts.size() + " posts loaded.");

                List listview = (List) findViewById(R.id.postListView);

                for (Post post : posts) {
                    //Log.i(PostActivity.class.getSimpleName(), post.ID + ": " + post.title);
                }
                ArrayAdapter adapter = new ArrayAdapter(this,R.layout.single_post_item, posts);
                listview.setAdapter(adapter);

            }
        };

        private final Response.ErrorListener onPostsError = new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Log.e(PostActivity.class.getSimpleName(), error.toString());
            }
        };
    }

Post.java

Post.java

import java.util.Date;
import com.google.gson.annotations.SerializedName;

public class Post {

    @SerializedName("id")
    long ID;

    @SerializedName("date")
    Date dateCreated;

    String title;
    String author;
    String url;
    String body;

}

activity_post.xml

activity_post.xml

<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin"
    tools:context=".PostActivity">

    <ListView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:id="@+id/postListView"
        android:layout_alignParentBottom="true" />
</RelativeLayout>

single_post_item.xml

single_post_item.xml

<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:text="TextView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/textView" />
</LinearLayout>

更新错误1:

:app:processDebugManifest
:app:processDebugResources
AGPBI: {"kind":"error","text":"Error parsing XML: XML or text declaration not at start of entity","sources":[{"file":"C:\\Users\\xxx\\Downloads\\GSONVolleyTutorial-master\\GSONVolleyTutorial-master\\app\\src\\main\\res\\layout\\activity_post.xml","position":{"startLine":0}}],"original":"","tool":"AAPT"}
AGPBI: {"kind":"error","text":"Error parsing XML: XML or text declaration not at start of entity","sources":[{"file":"C:\\Users\\xxx\\Downloads\\GSONVolleyTutorial-master\\GSONVolleyTutorial-master\\app\\src\\main\\res\\layout\\single_post_item.xml","position":{"startLine":0}}],"original":"","tool":"AAPT"}
C:\Users\xxx\Downloads\GSONVolleyTutorial-master\GSONVolleyTutorial-master\app\build\intermediates\res\merged\debug\layout\activity_post.xml:1: error: Error parsing XML: XML or text declaration not at start of entity

C:\Users\xxx\Downloads\GSONVolleyTutorial-master\GSONVolleyTutorial-master\app\build\intermediates\res\merged\debug\layout\single_post_item.xml:1: error: Error parsing XML: XML or text declaration not at start of entity

 FAILED

FAILURE: Build failed with an exception.

更新错误2:

C:\Users\xxx\Downloads\GSONVolleyTutorial-master\GSONVolleyTutorial-master\app\src\main\java\com\kylewbanks\gsonvolleytutorial\PostActivity.java:70: error: no suitable constructor found for ArrayAdapter(<anonymous Listener<String>>,int,int,List<String>)
                ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,R.layout.single_post_item,R.id.textView, posts_strs);
                                               ^
    constructor ArrayAdapter.ArrayAdapter(Context,int,int,String[]) is not applicable
      (argument mismatch; <anonymous Listener<String>> cannot be converted to Context)
    constructor ArrayAdapter.ArrayAdapter(Context,int,int,List<String>) is not applicable
      (argument mismatch; <anonymous Listener<String>> cannot be converted to Context)
Note: Some messages have been simplified; recompile with -Xdiags:verbose to get full output
1 error

:app:compileDebugJavaWithJavac FAILED

FAILURE: Build failed with an exception.

推荐答案

由于列表布局中只有一个TextView,因此您打算显示单个项目

Since there is only one TextView in your list layout mean you intended to display single item

1.)创建一个String数组列表并向其中添加元素

1.) Create a String arraylist and add elements to it

2.)在创建适配器时将@+id/textView"作为第三个参数

2.) Mention @+id/textView" as 3rd parameter while creating adapter

问题:

1.)在XMLsingle_post_item

2.)使用PostActivity.this代替this,因为this将引用匿名Response.Listener<String>类而不是PostActivity.

2.) Use PostActivity.this instead of this because this will refer to anonymous Response.Listener<String> class instead of PostActivity.

这篇关于使用GSON和Volley在Android上显示JSON数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆