【问题标题】:Consuming APIs with volley?使用 volley 使用 API?
【发布时间】:2015-06-01 21:41:19
【问题描述】:

我正在尝试通过库 volley 使用 API,但我不能,因为在我运行应用程序时它没有显示任何内容。

我认为问题在于 URL API 中有它(json):

{"books":[{"book":{PARAMETERS...}}]}

所以我无法访问我的参数。然后我的 URL API 在 URL 的末尾没有 .json,但我认为这不是问题。

public class MainActivity extends Activity {


private static final String TAG = MainActivity.class.getSimpleName();


private static final String url = "http://############";
private ProgressDialog pDialog;
private List<Books> booksList = new ArrayList<Books>();
private ListView listView;
private Adapter adapter;

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

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

    pDialog = new ProgressDialog(this);
    pDialog.setMessage("Loading...");
    pDialog.show();

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

    JsonArrayRequest booksReq = new JsonArrayRequest(url,
            new Response.Listener<JSONArray>() {
                @Override
                public void onResponse(JSONArray response) {
                    Log.d(TAG, response.toString());
                    hidePDialog();

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

                            JSONObject obj = response.getJSONObject(i);
                            Books books = new Books();
                            Books.setTitle(obj.getString("title"));
                            Books.setPhoto_url(obj.getString("image"));

                            booksList.add(books);

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                    adapter.notifyDataSetChanged();
                }
            }, new Response.ErrorListener() {

                public void onErrorResponse(VolleyError error) {
                    VolleyLog.d(TAG, "Error: " + error.getMessage());
                    hidePDialog();

                }
            });
    Controller.getInstance().addToRequestQueue(booksReq);
}
@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;
}
}

我在 URL API 中的 json:

{
    "books": [
        {
            "book": {
                "title": "namebook",
                "photo_url": {
                    "src": "http://######",
                    "alt": ""
                }
            }
        }
    ]
}

那我怎么才能给他们看呢?

【问题讨论】:

    标签: android arrays json rest android-volley


    【解决方案1】:

    尝试使用 JsonObjectRequest(int method, String url, JSONObject jsonRequest, Listener<JSONObject> listener, ErrorListener errorListener) 而不是JsonArrayRequest,因为您的回复似乎是JSONObject

    另外,您的回复中没有这样的密钥 image

    Books.setPhoto_url(obj.getString("image"));
    

    查看您的JSON 回复,如果您尝试以下代码,它应该可以工作:

    JsonObjectRequest artistReq = new JsonObjectRequest(Method.GET, url, null, new Listener<JSONObject>() {
        @Override
        public void onResponse(JSONObject response) {
            Log.d(TAG, response.toString());
            hidePDialog();
    
            try {
                if (response.optJSONArray("books") != null) {
                    JSONArray books = response.getJSONArray("books");
    
                    for (int i = 0; i < books.length(); i++) {
                        JSONObject book = books.getJSONObject(i);
    
                        String title = book.getString("title");
    
                        // next K,V pair consist of JSONObject photo_url
                        JSONObject photoUrl = book.getJSONObject("photo_url");
                        String photoSrc = photoUrl.getString("src");
                        String photoAlt = photoUrl.getString("alt");
                        // use extracted values in your Book object
                    }
                }
            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
    
            // notifying list adapter about data changes
            // so that it renders the list view with updated data
            adapter.notifyDataSetChanged();
        }
    }, new ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            VolleyLog.d(TAG, "Error: " + error.getMessage());
            hidePDialog();
    
        }
    });
    

    希望对您有所帮助!

    【讨论】:

    • 我的“Method.GET”有错误,我必须改变它吗?
    • 你必须import com.android.volley.Request.Method;。一般来说,如果您使用的是eclipsectrl+shift+o 会为您导入班级中的所有待处理项目
    • 是的,但所有的 JsonObjectRequest 都会出错:未定义
    • 你一定是错过了或者做了一些错误的导入,仔细检查所有的括号是否都关闭了......JsonObjectRequest应该没有任何问题......
    • 能否给我发个信息到zul19933@hotmail.com,这样你就可以看到了
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-07-08
    • 1970-01-01
    • 1970-01-01
    • 2020-05-24
    • 2021-10-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多