JsonObject无法转换为jsonArray

时间:2016-11-10 10:47:07

标签: java android android-layout android-fragments

始终显示警告

E/RecyclerView: No adapter attached; skipping layout

当我尝试在片段内实现Recycler视图时  并显示错误

W/System.err: com.android.volley.ParseError: org.json.JSONException: Value 

{"Sales_Report":[{"id":"1","cash":"258","credit":"258","description":"","dates":"Nov-09-2016","camimg_path":""},{"id":"2","cash":"532","credit":"586","description":"","dates":"Nov-09-2016","camimg_path":"Gallery_images\/Test_gl.jpeg"},{"id":"3","cash":"214","credit":"980","description":"th","dates":"Nov-09-2016","camimg_path":"Gallery_images\/Test_gl.jpeg"},{"id":"4","cash":"123","credit":"321","description":"erp","dates":"Nov-09-2016","camimg_path":"Gallery_images\/Test_gl.jpeg"},{"id":"15","cash":"5","credit":"8","description":"5","dates":"Nov-09-2016","camimg_path":"Gallery_images\/galimg2016-11-09T14:44:21.483+05302516.jpeg"},{"id":"14","cash":"2","credit":"3","description":"","dates":"Nov-09-2016","camimg_path":"..\/Gallery_images\/galimg2016-11-09T14:42:56.857+05302620.jpeg"}]} of type org.json.JSONObject cannot be converted to JSONArray
W/System.err:     at com.android.volley.toolbox.JsonArrayRequest.parseNetworkResponse(JsonArrayRequest.java:55)
W/System.err:     at com.android.volley.NetworkDispatcher.run(NetworkDispatcher.java:121)
W/System.err: Caused by: org.json.JSONException: Value {"Sales_Report":[{"id":"1","cash":"258","credit":"258","description":"","dates":"Nov-09-2016","camimg_path":""},{"id":"2","cash":"532","credit":"586","description":"","dates":"Nov-09-2016","camimg_path":"Gallery_images\/Test_gl.jpeg"},{"id":"3","cash":"214","credit":"980","description":"th","dates":"Nov-09-     2016","camimg_path":"Gallery_images\/Test_gl.jpeg"},   {"id":"4","cash":"123","credit":"321","description":"erp","dates":"Nov-09-  2016","camimg_path":"Gallery_images\/Test_gl.jpeg"},  {"id":"15","cash":"5","credit":"8","description":"5","dates":"Nov-09-  2016","camimg_path":"Gallery_images\/galimg2016-11-  09T14:44:21.483+05302516.jpeg"},  {"id":"14","cash":"2","credit":"3","description":"","dates":"Nov-09-  2016","camimg_path":"..\/Gallery_images\/galimg2016-11-  09T14:42:56.857+05302620.jpeg"}]} of type org.json.JSONObject cannot be      converted to JSONArray
  W/System.err:     at org.json.JSON.typeMismatch(JSON.java:111) 
  W/System.err:     at org.json.JSONArray.<init>(JSONArray.java:96)
  W/System.err:     at org.json.JSONArray.<init>(JSONArray.java:108)
   /System.err:     at    com.android.volley.toolbox.JsonArrayRequest.parseNetworkResponse(JsonArrayReques     t.java:50)

帮帮我....   这是我的 fragment.java

public class MessageFragment extends Fragment {
private List<Content> listSuperHeroes;

//Creating Views
private RecyclerView recyclerView;
private RecyclerView.LayoutManager layoutManager;
private RecyclerView.Adapter adapter;

public MessageFragment() {
    // Required empty public constructor
}
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    View v= inflater.inflate(R.layout.fragment_message, container, false);
    recyclerView = (RecyclerView) v.findViewById(R.id.recyclerView);
    recyclerView.setHasFixedSize(true);
    layoutManager = new LinearLayoutManager(getActivity());
    recyclerView.setLayoutManager(layoutManager);



    //Adding adapter to recyclerview

    listSuperHeroes = new ArrayList<>();

    //Calling method to get data
    getData();
    return v;
}
private void getData(){
    //Showing a progress dialog
   // final ProgressDialog loading = ProgressDialog.show(getActivity(),"Loading Data", "Please wait...",false,false);

    //Creating a json array request

    JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Config.DATA_URL,
            new Response.Listener<JSONArray>() {


                @Override
                public void onResponse(JSONArray response) {
                    //Dismissing progress dialog
                   // loading.dismiss();

                    //calling method to parse json array
                    parseData(response);
                }
            },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {

                }
            });

    //Creating request queue
    RequestQueue requestQueue = Volley.newRequestQueue(getActivity().getApplicationContext());

    //Adding request to the queue
    requestQueue.add(jsonArrayRequest);
}

private void parseData(JSONArray array){
    for(int i = 0; i<array.length(); i++) {
        Content superHero = new Content();
        JSONObject json = null;
        try {
            json = array.getJSONObject(i);
            superHero.setImageUrl(json.getString(Config.TAG_IMAGE_URL));
            superHero.setName(json.getString(Config.TAG_NAME));
            superHero.setRank(json.getInt(Config.TAG_RANK));
            superHero.setRealName(json.getString(Config.TAG_REAL_NAME));
            superHero.setCreatedBy(json.getString(Config.TAG_CREATED_BY));
            superHero.setFirstAppearance(json.getString(Config.TAG_FIRST_APPEARANCE));

            ArrayList<String> powers = new ArrayList<String>();

            JSONArray jsonArray = json.getJSONArray(Config.TAG_POWERS);

            for(int j = 0; j<jsonArray.length(); j++){
                powers.add(((String) jsonArray.get(j))+"\n");
            }
            superHero.setPowers(powers);


        } catch (JSONException e) {
            e.printStackTrace();
        }
        listSuperHeroes.add(superHero);
    }
    adapter = new CardAdapter(listSuperHeroes, getActivity());
    //Finally initializing our adapter
    recyclerView.setAdapter(adapter);

}
}   

这是我的 Cardadapter.java

public class CardAdapter extends RecyclerView.Adapter<CardAdapter.ViewHolder> {

private ImageLoader imageLoader;
private Context context;

//List of superHeroes
List<Content> superHeroes;

public CardAdapter(List<Content> superHeroes, Context context){
    super();
    //Getting all the superheroes
    this.superHeroes = superHeroes;
    this.context = context;
}

@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View v = LayoutInflater.from(parent.getContext())
            .inflate(R.layout.content_list, parent, false);
    ViewHolder viewHolder = new ViewHolder(v);
    return viewHolder;
}

@Override
public void onBindViewHolder(ViewHolder holder, int position) {

    Content superHero =  superHeroes.get(position);

    imageLoader = CustomVolleyRequest.getInstance(context).getImageLoader();
    imageLoader.get(superHero.getImageUrl(),        ImageLoader.getImageListener(holder.imageView, R.mipmap.ic_launcher, android.R.drawable.ic_dialog_alert));

    holder.imageView.setImageUrl(superHero.getImageUrl(), imageLoader);
    holder.textViewName.setText(superHero.getName());
    holder.textViewRank.setText(String.valueOf(superHero.getRank()));
    holder.textViewRealName.setText(superHero.getRealName());
    holder.textViewCreatedBy.setText(superHero.getCreatedBy());
    holder.textViewFirstAppearance.setText(superHero.getFirstAppearance());

    String powers = "";

    for(int i = 0; i<superHero.getPowers().size(); i++){
        powers+= superHero.getPowers().get(i);
    }

    holder.textViewPowers.setText(powers);
}

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

class ViewHolder extends RecyclerView.ViewHolder{
    public NetworkImageView imageView;
    public TextView textViewName;
    public TextView textViewRank;
    public TextView textViewRealName;
    public TextView textViewCreatedBy;
    public TextView textViewFirstAppearance;
    public TextView  textViewPowers;

    public ViewHolder(View itemView) {
        super(itemView);
        imageView = (NetworkImageView) itemView.findViewById(R.id.imageViewHero);
        textViewName = (TextView) itemView.findViewById(R.id.textViewName);
        textViewRank= (TextView) itemView.findViewById(R.id.textViewRank);
        textViewRealName= (TextView) itemView.findViewById(R.id.textViewRealName);
        textViewCreatedBy= (TextView) itemView.findViewById(R.id.textViewCreatedBy);
        textViewFirstAppearance= (TextView) itemView.findViewById(R.id.textViewFirstAppearance);
        textViewPowers= (TextView) itemView.findViewById(R.id.textViewPowers);
    }
}
}

请帮助我找到此代码中的问题以及如何解决它...提前感谢。

2 个答案:

答案 0 :(得分:0)

将此代码移至getData()

下方
   adapter = new CardAdapter(listSuperHeroes, getActivity());
   recyclerView.setAdapter(adapter);

然后在parseData()

之后在OnResponse()中执行此操作
       adapter .notifyDataSetChanged();

答案 1 :(得分:0)

您收到错误,因为RecyclerViewVISIBLE时没有适配器。

目前,您正在使用Adapter Fragment方法设置parseData()。 AFAIK 设置Adapter没有任何缺点(只是发出警告错误)。但是,如果您不想要它,那么您可以在onCreateView()中添加适配器,如此

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                     Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    View v= inflater.inflate(R.layout.fragment_message, container, false);
    recyclerView = (RecyclerView) v.findViewById(R.id.recyclerView);

    // your code

    listSuperHeroes = new ArrayList<>();
    adapter = new CardAdapter(listSuperHeroes, getActivity());

    // Set adapter here so you don't get warning.
    recyclerView.setAdapter(adapter);

    // your code

    return v;
}

然后在您的parseData()方法中,只需通知Adapter数据已更改。

private void parseData(JSONArray array) {

    // Your code for parsing

    // Notify the adapter that data has changed and the Adapter will populate RecyclerView accordingly.
    adapter.notifyDataSetChanged();
}