2012-12-15 114 views
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); 
      } 
     }); 

    } 

} 
+0

發表您的doInbackground代碼也 –

+1

@ρяσѕρєяK它已經在那裏。 – Eric

+0

你把圖片的網址。你應該先下載它,然後在listview中分配給imageview。 –

回答

1

你必須先下載圖像,然後在列表視圖中顯示它。您無法直接傳遞圖片網址,因此無法使用。

+0

我已經下載了圖像,然後只試圖表明一個,因此我得到項目的詳細形式項目的形象,但我運氣不佳,我失去了一些東西,這就是爲什麼不進入列表視圖,但希望我會盡快得到它 – Udhikriman

0

從後祛瘀的runOnUiThread()執行,你不跑UI組件成線..簡單地設置圖片...

1

此鏈接對您有所幫助click here,在這裏你可以找到如何從retrive圖像以有效的方式網並顯示它

+0

謝謝,但我已經做了很多,這是唯一的程序,我在哪裏我得到的問題,應用程序巴拉感謝您的幫助,但如果你真的想幫助我,所以請給我看一些源代碼,以獲得YouTube視頻列表,並使用此URL播放選定的一個: - http://www.youtube.com/playlist ?list = PL34F010EEF9D45FB8 – Udhikriman

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); 
      } 
     }); 


     } 

    } 

注意:如果您將得到直接的Web URL中的ImageView那麼這將永遠不會因爲工作你會n首先從Web上下載圖像,然後將其設置爲ImageView src。

看到這個帖子,我們如何利用圖像從Web服務器

How to load an ImageView by URL in Android?

+0

感謝編寫代碼,仍然能夠在「項目詳細信息」表單中查看選定項目的圖像,但無法在ListView中查看。幫助 – Udhikriman

+0

@Udhikriman:對不起,親愛的,你需要創建一個自定義適配器,然後將其設置爲ImageView看到這篇文章http://stackoverflow.com/questions/2471935/how-to-load-an-imageview-by- url-in-android –

+0

@Udhikriman:看我的編輯答案 –

1

這意味着你要自定義與圖像和文字的列表視圖。爲此(我在我的情況下做),獲取圖像的URL和文本在兩個數組。然後通過傳遞上下文(兩個數組)來設置列表視圖的適配器。

爲了設置圖像,您需要導入庫(圖像url助手或Universe圖像加載程序)。兩者都可以幫助你,但我會推薦你​​使用圖像url助手庫,因爲它很容易使用。

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); 
    }   
相關問題