如何解析json url中的图像作为listview列表项android

时间:2017-04-19 18:55:28

标签: android listview

private class GetRecipe extends AsyncTask<Void, Void, Void> {

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        // Showing progress dialog
        pDialog = new ProgressDialog(Activity_Home_List.this);
        pDialog.setMessage("Please wait...");
        pDialog.setCancelable(false);
        pDialog.show();

    }
    @Override
    protected Void doInBackground(Void... arg0) {
        HttpHandler sh = new HttpHandler();

        // Making a request to url and getting response
        String jsonStr = sh.makeServiceCall(url);

        Log.e(TAG, "Response from url: " + jsonStr);

        if (jsonStr != null) {
            try {
                JSONObject jsonObj = new JSONObject(jsonStr);

                // Getting JSON Array node
                JSONArray hits = jsonObj.getJSONArray("hits");

                // looping through All recipe
                for (int i = 0; i < hits.length(); i++) {
                    JSONObject h = hits.getJSONObject(i);
                    JSONObject recipe = h.getJSONObject("recipe");
                    String Uri = recipe.getString("uri");
                    String Label = recipe.getString("label");
                    String Image = recipe.getString("image");

                    // tmp hash map for single recipe
                    HashMap<String, String> recipe_ = new HashMap<>();

                    // adding each child node to HashMap key => value
                    recipe_.put("uri", Uri);
                    recipe_.put("label", Label);
                    recipe_.put("image", Image);

                    // adding recipe to recipe list
                    recipeList.add(recipe_);
                }
            } catch (final JSONException e) {
                Log.e(TAG, "Json parsing error: " + e.getMessage());
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(getApplicationContext(),
                                "Json parsing error: " + e.getMessage(),
                                Toast.LENGTH_LONG)
                                .show();
                    }
                });

            }
        } else {
            Log.e(TAG, "Couldn't get json from server.");
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(getApplicationContext(),
                            "Couldn't get json from server. Check LogCat for possible errors!",
                            Toast.LENGTH_LONG)
                            .show();
                }
            });

        }

        return null;
    }
    @Override
    protected void onPostExecute(Void result) {
        super.onPostExecute(result);
        // Dismiss the progress dialog
        if (pDialog.isShowing())
            pDialog.dismiss();
        /**
         * Updating parsed JSON data into ListView
         * */
        ListAdapter adapter = new SimpleAdapter(
                Activity_Home_List.this, recipeList,
                R.layout.home_list_items, new String[]{"uri", "label",
                "image"}, new int[]{R.id.recipe,
                R.id.label, R.id.image});

        lv.setAdapter(adapter);

    }

}

这是我的处理程序类

公共类HttpHandler {

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

public HttpHandler() {
}

public String makeServiceCall(String reqUrl) {
    String response = null;
    try {
        URL url = new URL(reqUrl);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("GET");
        // read the response
        InputStream in = new BufferedInputStream(conn.getInputStream());
        response = convertStreamToString(in);
    } catch (MalformedURLException e) {
        Log.e(TAG, "MalformedURLException: " + e.getMessage());
    } catch (ProtocolException e) {
        Log.e(TAG, "ProtocolException: " + e.getMessage());
    } catch (IOException e) {
        Log.e(TAG, "IOException: " + e.getMessage());
    } catch (Exception e) {
        Log.e(TAG, "Exception: " + e.getMessage());
    }
    return response;
}

private String convertStreamToString(InputStream is) {
    BufferedReader reader = new BufferedReader(new InputStreamReader(is));
    StringBuilder sb = new StringBuilder();

    String line;
    try {
        while ((line = reader.readLine()) != null) {
            sb.append(line).append('\n');
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            is.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return sb.toString();
}

}

我正在获取字符串值,但图像不在列表项中。 我可以将图像作为列表项目。 这是我的json的整个解析代码,但静止图像不在列表项中。

2 个答案:

答案 0 :(得分:2)

我不知道“良好的编程习惯”是否正确,但你必须从Fragment创建Layout,使用另一个AsyncTask下载它然后Inflate使用您拥有的List

看看这里: it's great tutorial on YT

答案 1 :(得分:2)

尝试Glide

1. 将Glide依赖关系添加到app / build.gradle

$('body').on("a.close","click",function(){
      alert('click event fired !')
});

2. 使用Glide加载图片

repositories {
   mavenCentral() // jcenter() works as well because it pulls from Maven Central
}

dependencies {
   compile 'com.github.bumptech.glide:glide:3.7.0'
   compile 'com.android.support:support-v4:19.1.0'
 }

OR

Glide.with(context).load(url).placeholder(R.drawable.placeholder).into(imageView);