【问题标题】:Custom List View with thumbnail using Android Volley Library will not load any results使用 Android Volley 库的带有缩略图的自定义列表视图将不会加载任何结果
【发布时间】:2015-05-08 10:37:44
【问题描述】:

我正在尝试使用 Volley Networking 库加载自定义列表视图,但在运行应用程序时没有结果,代码也没有错误。数据来自 JSON 文件

JSON OUTPUT HERE

以下是我的课程:

MainActivity.java

package info.androidhive.customlistviewvolley;

import info.androidhive.customlistviewvolley.adater.CustomListAdapter;
import info.androidhive.customlistviewvolley.app.AppController;
import info.androidhive.customlistviewvolley.model.CaseStudy;

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

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

import android.app.Activity;
import android.app.ProgressDialog;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.widget.ListView;

import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.VolleyLog;
import com.android.volley.toolbox.JsonArrayRequest;

public class MainActivity extends Activity {
    // Log tag
    private static final String TAG = MainActivity.class.getSimpleName();

    // Movies json url
    private static final String url = "http://178.62.67.237/api/v1/residential/?format=json";
    private ProgressDialog pDialog;
    private List<CaseStudy> caseList = new ArrayList<CaseStudy>();
    private ListView listView;
    private CustomListAdapter adapter;

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

        listView = (ListView) findViewById(R.id.list);
        adapter = new CustomListAdapter(this, caseList);
        listView.setAdapter(adapter);

        pDialog = new ProgressDialog(this);
        // Showing progress dialog before making http request
        pDialog.setMessage("Loading...");
        pDialog.show();

        // changing action bar color
        getActionBar().setBackgroundDrawable(
                new ColorDrawable(Color.parseColor("#1b1b1b")));

        // Creating volley request obj
        JsonArrayRequest movieReq = new JsonArrayRequest(url,
                new Response.Listener<JSONArray>() {
                    @Override
                    public void onResponse(JSONArray response) {
                        Log.d(TAG, response.toString());
                        hidePDialog();

                        // Parsing json
                        for (int i = 0; i < response.length(); i++) {
                            try {

                                JSONObject obj = response.getJSONObject(i);
                                CaseStudy reference = new CaseStudy();
                                reference.setTitle(obj.getString("title"));
                                reference.setThumbnailUrl(obj.getString("image"));
                                reference.setPostcode(obj.getString("postcode"));


                                // adding movie to movies array
                                caseList.add(reference);

                            } catch (JSONException e) {
                                e.printStackTrace();
                            }

                        }

                        // notifying list adapter about data changes
                        // so that it renders the list view with updated data
                        adapter.notifyDataSetChanged();
                    }
                }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        VolleyLog.d(TAG, "Error: " + error.getMessage());
                        hidePDialog();

                    }
                });

        // Adding request to request queue
        AppController.getInstance().addToRequestQueue(movieReq);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        hidePDialog();
    }

    private void hidePDialog() {
        if (pDialog != null) {
            pDialog.dismiss();
            pDialog = null;
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

}

CaseStudy.java:

package info.androidhive.customlistviewvolley.model;



public class CaseStudy {
    private String title;
    private String thumbnailUrl;
    private String postcode;

    public CaseStudy() {
    }

    public CaseStudy(String name, String thumbnailUrl, String postcode) {
        this.title = name;
        this.thumbnailUrl = thumbnailUrl;
        this.postcode = postcode;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String name) {
        this.title = name;
    }

    public String getThumbnailUrl() {
        return thumbnailUrl;
    }

    public void setThumbnailUrl(String thumbnailUrl) {
        this.thumbnailUrl = thumbnailUrl;
    }

    public void setPostcode(String postcode) {
        this.postcode =  postcode;
    }

    public String getPostcode() {
        return postcode;
    }



}

CustomListAdapter.java:

package info.androidhive.customlistviewvolley.adater;

import info.androidhive.customlistviewvolley.R;
import info.androidhive.customlistviewvolley.app.AppController;
import info.androidhive.customlistviewvolley.model.CaseStudy;

import java.util.List;

import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.NetworkImageView;

public class CustomListAdapter extends BaseAdapter {
    private Activity activity;
    private LayoutInflater inflater;
    private List<CaseStudy> caseItems;
    ImageLoader imageLoader = AppController.getInstance().getImageLoader();

    public CustomListAdapter(Activity activity, List<CaseStudy> caseItems) {
        this.activity = activity;
        this.caseItems = caseItems;
    }

    @Override
    public int getCount() {
        return caseItems.size();
    }

    @Override
    public Object getItem(int location) {
        return caseItems.get(location);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {

        if (inflater == null)
            inflater = (LayoutInflater) activity
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        if (convertView == null)
            convertView = inflater.inflate(R.layout.list_row_custom, null);

        if (imageLoader == null)
            imageLoader = AppController.getInstance().getImageLoader();
        NetworkImageView thumbNail = (NetworkImageView) convertView
                .findViewById(R.id.thumbnail);
        TextView title = (TextView) convertView.findViewById(R.id.title);
        TextView postcode = (TextView) convertView.findViewById(R.id.postcode);
        //TextView genre = (TextView) convertView.findViewById(R.id.genre);
        //TextView year = (TextView) convertView.findViewById(R.id.releaseYear);

        // getting movie data for the row
        CaseStudy c = caseItems.get(position);

        // thumbnail image
        thumbNail.setImageUrl(c.getThumbnailUrl(), imageLoader);

        // title
        title.setText(c.getTitle());
        postcode.setText(c.getPostcode());      
        // rating
        //rating.setText("Rating: " + String.valueOf(m.getRating()));

        // genre
        //String genreStr = "";
        //for (String str : m.getGenre()) {
        //  genreStr += str + ", ";
        //}
        //genreStr = genreStr.length() > 0 ? genreStr.substring(0,
        //      genreStr.length() - 2) : genreStr;
        //genre.setText(genreStr);

        // release year
        //year.setText(String.valueOf(m.getYear()));

        return convertView;
    }

}

ist_row_custom.xml:

    <?xml version="1.0" encoding="utf-8"?>
    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:background="@drawable/list_row_selector"
    android:padding="8dp" >

    <!-- Thumbnail Image -->
    <com.android.volley.toolbox.NetworkImageView
        android:id="@+id/thumbnail"
        android:layout_width="80dp"
        android:layout_height="80dp"
        android:layout_alignParentLeft="true"
        android:layout_marginRight="8dp" />

    <!--  Title -->
    <TextView
        android:id="@+id/title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignTop="@+id/thumbnail"
        android:layout_toRightOf="@+id/thumbnail"
        android:textSize="@dimen/title"
        android:textStyle="bold" />

    <!-- Postcode-->
    <TextView
        android:id="@+id/postcode"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/title"
        android:layout_marginTop="1dip"
        android:layout_toRightOf="@+id/thumbnail"
        android:textSize="@dimen/rating" />

    <!-- Genre -->

    <!-- Release Year -->

</RelativeLayout>

任何想法我做错了什么?

【问题讨论】:

    标签: java android json android-listview android-volley


    【解决方案1】:

    您在 MainActivity 中引用了错误的 xml。请为 ex activity_main.xml 创建一个新的 xml 并在那里启动您的列表视图。

    同样在您的代码中,您正在调用 JSONArray,但是您的 Json 输出显示它是 Json 对象。请将您的代码更改为 JSONObject,如下所示

    JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Method.GET, url, null, new Response.Listener<JSONObject>() {
    
                @Override
                public void onResponse(JSONObject jsonObject) {
                    hidePDialog();
                    System.out.println("JsonObject++===---"+jsonObject);
                    try {
                        JSONArray response = jsonObject.getJSONArray("objects");
    
                        for(int i=0; i <response.length(); i++){
                            JSONObject obj = response.getJSONObject(i);
                            CaseStudy reference = new CaseStudy();
                            reference.setTitle(obj.getString("title"));
                            reference.setThumbnailUrl(obj.getString("image_path"));
                            reference.setPostcode(obj.getString("postcode"));
    
    
                            // adding movie to movies array
                            caseList.add(reference);
                        }
    
                    } catch (JSONException e) {
                        // TODO Auto-generated catch block
                        System.out.println("error");
                        e.printStackTrace();
                    }
                    adapter.notifyDataSetChanged();
                }
            }, new Response.ErrorListener() {
    
                @Override
                public void onErrorResponse(VolleyError arg0) {
                    hidePDialog();
                }
            });
            AppController.getInstance().addToRequestQueue(jsonObjectRequest, TAG);
    

    【讨论】:

    • 我已经更新了答案,请按照答案你会得到输出
    【解决方案2】:

    根据您的 Json,您应该得到 'image_path' 而不是 'image' 。

         reference.setThumbnailUrl(obj.getString("image"));
    

    使用

        reference.setThumbnailUrl(obj.getString("image_path"));
    

    【讨论】:

    • 清单中声明了 Internet 权限,因此该方面是正确的。现在我正在尝试 Log.d("Thumbnail", c,.getThumbnailUrl());但 logCat 上什么也没有打印出来
    • 你的 json 解析有问题。这就是为什么它是 null 或空的。
    • 根据您的 Json,您应该得到 'image_path' 而不是 'image' 。
    • 您好,感谢您帮我发现这个...我更改了我的代码,但仍然无法得到结果..一定还有其他东西丢失了!
    猜你喜欢
    • 1970-01-01
    • 2014-04-05
    • 1970-01-01
    • 1970-01-01
    • 2016-03-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多