1

我制作了一个程序,其中我使用 PHP 将数据编码为 JSON。我的程序运行良好,没有显示任何错误或问题;我得到了我想要的,但我面临的问题非常小。

在这里,我无法在其中显示项目的图像,ListView但是每当我单击其中一个项目行以查看完整的项目详细信息时,我都会获得所选项目的图像。这意味着我应该得到图像ListView,但我无法显示,所以有人可以帮忙解决这个错误吗?

public class AlbumsActivity extends ListActivity {
// Connection detector
ConnectionDetector cd;

// Alert dialog manager
AlertDialogManager alert = new AlertDialogManager();

// Progress Dialog
private ProgressDialog pDialog;

// Creating JSON Parser object
JSONParser jsonParser = new JSONParser();

ArrayList<HashMap<String, String>> albumsList;

// albums JSONArray
JSONArray albums = null;

String imagepath;

// albums JSON url
private static final String URL_ALBUMS = "MY URL";

// ALL JSON node names
private static final String TAG_ID = "id";
private static final String TAG_NAME = "name";
private static final String TAG_DESCRIPTION = "description";
private static final String TAG_IMAGEPATH = "imagepath";
private static final String TAG_SONGS_COUNT = "songs_count";

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_albums);

    cd = new ConnectionDetector(getApplicationContext());

// Check for internet connection
if (!cd.isConnectingToInternet()) {
    // Internet Connection is not present
    alert.showAlertDialog(AlbumsActivity.this, "Internet Connection Error",
            "Please connect to working Internet connection", false);
    // stop executing code by return
    return;
}

    // Hashmap for ListView
    albumsList = new ArrayList<HashMap<String, String>>();

    // Loading Albums JSON in Background Thread
    new LoadAlbums().execute();

    // get listview
    ListView lv = getListView();

    /**
     * Listview item click listener
     * TrackListActivity will be lauched by passing album id
     * */
    lv.setOnItemClickListener(new android.widget.AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> arg0, View view, int arg2,
                long arg3) {
            // on selecting a single album
            // TrackListActivity will be launched to show tracks inside the album
            Intent i = new Intent(getApplicationContext(), TrackListActivity.class);

            // send album id to tracklist activity to get list of songs under that album
            String album_id = ((TextView) view.findViewById(R.id.album_id)).getText().toString();
            i.putExtra("album_id", album_id);               

            startActivity(i);
        }
    });     
}

/**
 * Background Async Task to Load all Albums by making http request
 * */
class LoadAlbums extends AsyncTask<String, String, String> {

    /**
     * Before starting background thread Show Progress Dialog
     * */
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        pDialog = new ProgressDialog(AlbumsActivity.this);
        pDialog.setMessage("Listing Albums ...");
        pDialog.setIndeterminate(false);
        pDialog.setCancelable(false);
        pDialog.show();
    }

    /**
     * getting Albums JSON
     * */
    protected String doInBackground(String... args) {
        // Building Parameters
        List<NameValuePair> params = new ArrayList<NameValuePair>();

        // getting JSON string from URL
        String json = jsonParser.makeHttpRequest(URL_ALBUMS, "GET",
                params);

        // Check your log cat for JSON reponse
        Log.d("Albums JSON: ", "> " + json);

        try {               
            albums = new JSONArray(json);

            if (albums != null) {
                // looping through All albums
                for (int i = 0; i < albums.length(); i++) {
                    JSONObject c = albums.getJSONObject(i);

                    // Storing each json item values in variable
                    String id = c.getString(TAG_ID);
                    String name = c.getString(TAG_NAME);
                    String description = c.getString(TAG_DESCRIPTION);
                    String imageurl = c.getString(TAG_IMAGEPATH);
                    String songs_count = c.getString(TAG_SONGS_COUNT);

                    // creating new HashMap
                    HashMap<String, String> map = new HashMap<String, String>();

                    // adding each child node to HashMap key => value
                    map.put(TAG_ID, id);
                    map.put(TAG_NAME, name);
                    map.put(TAG_DESCRIPTION, description);
                    map.put(TAG_IMAGEPATH,imageurl);
                    map.put(TAG_SONGS_COUNT, songs_count);

                    // adding HashList to ArrayList
                    albumsList.add(map);
                }
            }else{
                Log.d("Albums: ", "null");
            }

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

        return null;
    }

    /**
     * After completing background task Dismiss the progress dialog
     * **/
    protected void onPostExecute(String file_url) {
        // dismiss the dialog after getting all albums
        pDialog.dismiss();
        // updating UI from Background Thread
        runOnUiThread(new Runnable() {
            public void run() {
                /**
                 * Updating parsed JSON data into ListView
                 * */
                ListAdapter adapter = new SimpleAdapter(
                        AlbumsActivity.this, albumsList,
                        R.layout.list_item_albums, new String[] 
                                {
                                TAG_ID, TAG_NAME, TAG_DESCRIPTION, TAG_IMAGEPATH, TAG_SONGS_COUNT 
                                }, 
                                new int[] 
                                {
                                R.id.album_id, R.id.album_name, R.id.album_description, R.id.list_image, R.id.songs_count 
                                }
                        );

                // updating listview
                setListAdapter(adapter);
            }
        });

    }

}
4

5 回答 5

1

在您的适配器中尝试此操作,它可能会对您有所帮助:

 String imageURL = "htp://domain/some-path/kdhfbdskf.jpg";

 Bitmap bmp = null;
    try {
        InputStream in = new java.net.URL(imageURL).openStream();
        bmp = BitmapFactory.decodeStream(in);
    }
    catch (IOException e) {
        e.printStackTrace();
    }

    if (bmp != null) {
        holder.UserImageView.setImageBitmap(bmp);
    } else {
        holder.UserImageView.setImageResource(R.drawable.ic_launcher);
     }        
于 2012-12-15T06:14:48.657 回答
1

您必须先下载图像,然后在列表视图中显示它。您不能直接传递图像 URL,它将不起作用。

于 2012-12-15T05:30:04.047 回答
1

将当前代码更改为并从 onPostExecute 方法中删除 runOnUiThread() :

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_albums);

        cd = new ConnectionDetector(getApplicationContext());

    // Check for internet connection
    if (!cd.isConnectingToInternet()) {
        // Internet Connection is not present
        alert.showAlertDialog(AlbumsActivity.this, "Internet Connection Error",
                "Please connect to working Internet connection", false);
        // stop executing code by return
        return;
    }

        // Hashmap for ListView
        albumsList = new ArrayList<HashMap<String, String>>();

        // Loading Albums JSON in Background Thread
        new LoadAlbums().execute();




    }

    /**
     * Background Async Task to Load all Albums by making http request
     * */
    class LoadAlbums extends AsyncTask<String, String, 
ArrayList<HashMap<String, String>>> {

        /**
         * Before starting background thread Show Progress Dialog
         * */
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(AlbumsActivity.this);
            pDialog.setMessage("Listing Albums ...");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(false);
            pDialog.show();
        }

        /**
         * getting Albums JSON
         * */
        protected ArrayList<HashMap<String, String>> 
     doInBackground(String... args) {
            // Building Parameters
            List<NameValuePair> params = new ArrayList<NameValuePair>();

            // getting JSON string from URL
            String json = jsonParser.makeHttpRequest(URL_ALBUMS, "GET",
                    params);

            // Check your log cat for JSON reponse
            Log.d("Albums JSON: ", "> " + json);

            try {               
                albums = new JSONArray(json);

                if (albums != null) {
                    // looping through All albums
                    for (int i = 0; i < albums.length(); i++) {
                        JSONObject c = albums.getJSONObject(i);

                        // Storing each json item values in variable
                        String id = c.getString(TAG_ID);
                        String name = c.getString(TAG_NAME);
                        String description = c.getString(TAG_DESCRIPTION);
                        String imageurl = c.getString(TAG_IMAGEPATH);
                        String songs_count = c.getString(TAG_SONGS_COUNT);

                        // creating new HashMap
                        HashMap<String, String> map = new 
                HashMap<String, String>();

                        // adding each child node to HashMap key => value
                        map.put(TAG_ID, id);
                        map.put(TAG_NAME, name);
                        map.put(TAG_DESCRIPTION, description);
                        map.put(TAG_IMAGEPATH,imageurl);
                        map.put(TAG_SONGS_COUNT, songs_count);

                        // adding HashList to ArrayList
                        albumsList.add(map);
                    }
                }else{
                    Log.d("Albums: ", "null");
                }

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

            return albumsList;
        }

        /**
         * After completing background task Dismiss the progress dialog
         * **/
        protected void onPostExecute(ArrayList<HashMap<String, 
                             String>> file_url) {
            // dismiss the dialog after getting all albums
            pDialog.dismiss();

            // get listview
            ListView lv = getListView();
                    /**
                     * Updating parsed JSON data into ListView
                     * */
                    ListAdapter adapter = new SimpleAdapter(
                            AlbumsActivity.this, file_url,
                            R.layout.list_item_albums, new String[] 
                                    {
                                    TAG_ID, TAG_NAME, TAG_DESCRIPTION,
TAG_IMAGEPATH, TAG_SONGS_COUNT 
                                    }, 
                                    new int[] 
                                    {
                                    R.id.album_id,
     R.id.album_name, R.id.album_description, R.id.list_image, R.id.songs_count 
                                    }
                            );

                    // updating listview
                    lv.setListAdapter(adapter);

        /**
         * Listview item click listener
         * TrackListActivity will be lauched by passing album id
         * */
        lv.setOnItemClickListener(new android.widget.
                      AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> arg0, View view, int arg2,
                    long arg3) {
                // on selecting a single album

                Intent i = new Intent(getApplicationContext(),
                       TrackListActivity.class);

                // send album id to tracklist activity to get list of songs 
              //under that album
                String album_id = ((TextView) view.
                    findViewById(R.id.album_id)).getText().toString();
                i.putExtra("album_id", album_id);               

                startActivity(i);
            }
        });  


        }

    }

注意:如果您在 ImageView 中获得了直接的 Web URL,那么这将永远不会起作用,因为您需要先从 Web 下载图像,然后将其设置为 ImageView src。

看这篇文章我们如何从网络服务器获取图像

如何在 Android 中通过 URL 加载 ImageView?

于 2012-12-15T05:37:47.063 回答
1

这意味着您想使用图像和文本自定义列表视图。为此(在我的情况下我做了什么),在两个数组中获取图像 url 和文本。然后通过传递上下文来设置列表视图的适配器,两个数组。

要设置图像,您需要导入库(图像 url 帮助程序或 Universe 图像加载器)。两者都可以很好地帮助您,但我会推荐您使用图像 url 帮助程序库,因为它易于使用。

于 2012-12-15T06:02:44.847 回答
0

从执行后删除 runOnUiThread() 并且您不会将 UI 组件运行到线程中..只需设置图像...

于 2012-12-15T05:32:32.143 回答