无法显示Json数据

时间:2018-12-10 16:19:01

标签: java android json parsing android-volley

我正在尝试显示json对象内部的json数组,但文本视图上未显示任何内容。我调试了一下,发现info.java类工作正常。如果我在info.java类中传递了简单的字符串值(在删除json解析后的java代码之后),它可以工作,但是我无法传递json数据。
Singleton.java

package com.example.osama.recyclerthug;

import android.content.Context;
import android.graphics.Bitmap;
import android.support.v4.util.LruCache;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.Volley;

public class Singleton {
    private static Singleton mInstance;
    private RequestQueue mRequestQueue;
    private ImageLoader mImageLoader;
    private static Context mCtx;

    private Singleton(Context context){
        mCtx = context;
        mRequestQueue =getRequestQueue();

                mImageLoader = new ImageLoader(mRequestQueue,
                        new ImageLoader.ImageCache() {
                    private final LruCache<String, Bitmap>
                            cache = new LruCache<String, Bitmap>(20);
                            @Override
                            public Bitmap getBitmap(String url) {
                                return cache.get(url);
                            }

                            @Override
                            public void putBitmap(String url, Bitmap bitmap) {

                                cache.put(url, bitmap);
                            }
                        });
    }

    public static synchronized Singleton getInstance(Context context){
        if (mInstance == null){
            mInstance = new Singleton(context);
        }
        return mInstance;
    }
    public RequestQueue getRequestQueue(){
        if (mRequestQueue == null){
            mRequestQueue = Volley.newRequestQueue(mCtx.getApplicationContext());
        }
        return mRequestQueue;
    }
    public <T> void addToRequestQueue(Request<T> request){
        getRequestQueue().add(request);
    }
    public ImageLoader getmImageLoader(){
        return mImageLoader;
    }

}

............................................... .................... ThugAdapter.java

 package com.example.osama.recyclerthug;

import android.net.Uri;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import java.util.ArrayList;


public class ThugAdapter extends RecyclerView.Adapter<ThugAdapter.ThugHolder> {

    ArrayList<Info> arrayList1;

    public ThugAdapter(ArrayList<Info> arrayList){
        this.arrayList1 = arrayList;
    }

    @NonNull
    @Override
    public ThugHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
        LayoutInflater inflater = LayoutInflater.from(viewGroup.getContext());
        View view = inflater.inflate(R.layout.appearance, viewGroup, false);
        ThugHolder thugHolder = new ThugHolder(view);
        return thugHolder;
    }

    @Override
    public void onBindViewHolder(@NonNull ThugHolder thugHolder, int i) {

        thugHolder.text.setText(arrayList1.get(i).getTxt1());
        thugHolder.text2.setText(arrayList1.get(i).getTxt2());
      /*  thugHolder.image.setImageURI(arrayList.get(i).getImageUri());*/

    }

    @Override
    public int getItemCount() {
        return arrayList1.size();
    }

    public class ThugHolder extends RecyclerView.ViewHolder{

        TextView text,text2;
        ImageView image;
        public ThugHolder(@NonNull View itemView) {
            super(itemView);
            text = itemView.findViewById(R.id.textView);
            text2 = itemView.findViewById(R.id.textView2);
            image = itemView.findViewById(R.id.imageView);
        }



    }
}

............................................... ...................................... Info.java

package com.example.osama.recyclerthug;

import android.net.Uri;

public class Info {
    private String txt1,txt2;
   // private Uri imageuri;
    public Info(String txt1, String txt2/*, Uri imageuri*/){
        this.setTxt1(txt1);
        this.setTxt2(txt2);
       /* this.setImageUri(imageuri);*/
    }

    public String getTxt1() {
        return txt1;
    }

    public void setTxt1(String txt1) {
        this.txt1 = txt1;
    }

    public String getTxt2() {
        return txt2;
    }

    public void setTxt2(String txt2) {
        this.txt2 = txt2;
    }

    /*public Uri getImageUri() {
        return imageuri;
    }

    public void setImageUri(Uri imageuri) {
        this.imageuri = imageuri;
    }*/
}

............................................... ...... BackgroundTask.java

package com.example.osama.recyclerthug;

import android.content.Context;
import android.net.Uri;
import android.util.Log;
import android.widget.Toast;

import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonArrayRequest;
import com.android.volley.toolbox.JsonObjectRequest;

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

import java.util.ArrayList;

public class BackgroundTask {
    Context context;
    ArrayList<Info> arrayList;
    String json_url = "http://cc97cf60.ngrok.io/api/note/";

    public BackgroundTask(Context context){
        this.context = context;
    }
    public ArrayList<Info> getArrayList(){

        arrayList = new ArrayList<>();
        JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, json_url, null,
                new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {
                        JSONArray jsonArray ;
                        try {
                            jsonArray = response.getJSONArray("objects");
                            int i;
                            for (i = 0; i < jsonArray.length(); i++){
                                JSONObject jsonObject = (JSONObject) jsonArray.get(i);
                           /*     Uri b = Uri.parse(jsonObject.getString("image")); //Type casting string to uri*/
                                String a = jsonObject.getString("title");
                                String b = jsonObject.getString("body");
                                Info info = new Info(a,b);
                                arrayList.add(info);

                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {



            }
        });
        Singleton.getInstance(context).addToRequestQueue(jsonObjectRequest);
        return arrayList;
    }
}

..................................... MainActivity.java

package com.example.osama.recyclerthug;

import android.app.DownloadManager;
import android.net.Uri;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;

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

import org.json.JSONObject;

import java.util.ArrayList;


public class MainActivity extends AppCompatActivity {

    RecyclerView recyclerView;
    RecyclerView.LayoutManager layoutManager;
    ThugAdapter thugAdapter;
    BackgroundTask backgroundTask;
    ArrayList<Info> arrayList;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        recyclerView = findViewById(R.id.recycler);
        layoutManager = new LinearLayoutManager(this);
        recyclerView.setLayoutManager(layoutManager);
        recyclerView.setHasFixedSize(true);
        backgroundTask = new BackgroundTask(this);
        arrayList = new ArrayList<>();
        arrayList= backgroundTask.getArrayList();
        thugAdapter = new ThugAdapter(arrayList);
        recyclerView.setAdapter(thugAdapter);


    }
}

编辑:以下是json数据:

{
  "meta": {
    "limit": 20,
    "next": null,
    "offset": 0,
    "previous": null,
    "total_count": 2
  },
  "objects": [
    {
      "body": "Breaking News:\r\nOsama Abrar is Iron Man.",
      "created_at": "2018-12-08T08:40:59.949776",
      "id": 1,
      "image": "https://wonderfulengineering.com/wp-content/uploads/2016/01/iron-man-wallpaper-6.jpg",
      "resource_uri": "/api/note/1/",
      "title": "Iron Man"
    },
    {
      "body": "Will Iron Man aka Osama Abrar survive?",
      "created_at": "2018-12-08T08:41:40.279677",
      "id": 2,
      "image": "https://marciokenobi.files.wordpress.com/2013/03/iron_man.jpg",
      "resource_uri": "/api/note/2/",
      "title": "End Game"
    }
  ]
}

1 个答案:

答案 0 :(得分:1)

JSON解析是可以的,但是您无法像这样检索数据,因为您在异步模式下使用了Volley。这意味着您不能假设将请求放入队列后就可以检索到数据。也许队列很长,您的请求可以稍后发送。因此,当您尝试检索数据时,您已经看到arrayList为null,这是正常的。为了处理异步方式,您必须告诉Volley:“在检索数据时告诉我”。您可以使用侦听器来做到这一点。

这里是一个例子。

public interface Listener {

    void onDataReceived(ArrayList<Info> list);
    void onError(int error);
}

BackgroundTask

public class BackgroundTask {
    Context context;
    ArrayList<Info> arrayList;
    Listener mListener; // listener to retrieve data
    String json_url = "http://cc97cf60.ngrok.io/api/note/";

    public BackgroundTask(Context context, Listener listener) {
        this.context = context;
        mListener = listener;
    }

    public void getArrayList() { // no return needed

        arrayList = new ArrayList<>();
        JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, json_url, null,
                new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {
                        JSONArray jsonArray;
                        try {
                            jsonArray = response.getJSONArray("objects");
                            int i;
                            for (i = 0; i < jsonArray.length(); i++) {
                                JSONObject jsonObject = (JSONObject) jsonArray.get(i);
                                /*     Uri b = Uri.parse(jsonObject.getString("image")); //Type casting string to uri*/
                                String a = jsonObject.getString("title");
                                String b = jsonObject.getString("body");
                                Info info = new Info(a, b);
                                arrayList.add(info);

                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                        // if listener has been set, send data
                        if (mListener != null) {
                            mListener.onDataReceived(arrayList);
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                // if listener has been set, send error
                if (mListener != null) {
                    mListener.onError(error.networkResponse.statusCode);
                }
            }
        });
        Singleton.getInstance(context).addToRequestQueue(jsonObjectRequest);
    }
}

在您的 MainActivity 中:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    recyclerView = findViewById(R.id.recycler);
    layoutManager = new LinearLayoutManager(this);
    recyclerView.setLayoutManager(layoutManager);
    recyclerView.setHasFixedSize(true);
    backgroundTask = new BackgroundTask(this, new Listener() {
        @Override
        public void onDataReceived(ArrayList<Info> list) {
            thugAdapter = new ThugAdapter(list);
            recyclerView.setAdapter(thugAdapter);
        }

        @Override
        public void onError(int error) {

        }
    });
    backgroundTask.getArrayList();
}

那就是!