2013-02-01 5 views
1

J'ai fait une application dans laquelle je suis aller chercher la liste des produits ainsi que leur nom , la description et l'image, je suis capable de montrer une image dans un fiche produit détaillée en cliquez sur l'un des ListView Item ligne mais obtenir problème pour montrer une image dans un ListView, je ne sais pas pourquoi je reçois ce problème ..Comment afficher une image dans un ListView dans Android

s'il vous plaît laissez-moi savoir où il me manque:

code:

public class CategoryActivity 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 = "http://XXX.com/albums.php"; 

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

    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_category); 
     cd = new ConnectionDetector(getApplicationContext()); 
     // Check for internet connection 
     if (!cd.isConnectingToInternet()) { 
      // Internet Connection is not present 
      alert.showAlertDialog(CategoryActivity.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 LoadCategories().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(), ProductListActivity.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 LoadCategories extends AsyncTask<String, String, String> { 

     /** 
     * Before starting background thread Show Progress Dialog 
     * */ 
     @Override 
     protected void onPreExecute() { 
      super.onPreExecute(); 
      pDialog = new ProgressDialog(CategoryActivity.this); 
      pDialog.setMessage("Loading Please Wait ..."); 
      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(
          CategoryActivity.this, albumsList, 
          R.layout.list_item_categories, 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

S'il vous plaît peut vous détaillez votre problème? – Goo

+0

Vous obtenez des images du serveur, il semble. Pour de tels cas, il y a 1 très belle façon, en utilisant LazyList ... essayez-le http://stackoverflow.com/questions/7620026/lazylist-layout – Braj

Répondre

2

Ne vous inquiétez pas

Je suppose que vous devez utiliser le code ci-dessous, il y a utile, quelques jours, j'ai utilisé que dans mon application:

tout d'abord remplacer onPostExecute par ceci:

protected void onPostExecute(String file_url) { 

      /** 
      * Updating parsed JSON data into ListView 
      * */ 
      adapter = new LazyAdapter(
        CategoryActivity.this, albumsList); 
      // updating listview 
      setListAdapter(adapter); 
      // updating UI from Background Thread 
      pDialog.dismiss(); 

     } 

Maintenant, créez un LazyAdapter classe et de mettre le code ci-dessous, il suffit de faire copier et coller j'ai changé dans votre façon:

 public class LazyAdapter extends BaseAdapter { 

private Activity activity; 
private ArrayList<HashMap<String, String>> data; 
private static LayoutInflater inflater=null; 
public ImageLoader imageLoader; 

public LazyAdapter(Activity a, ArrayList<HashMap<String, String>> d) { 
    activity = a; 
    data=d; 
    inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
    imageLoader=new ImageLoader(activity.getApplicationContext()); 
} 

public int getCount() { 
    return data.size(); 
} 

public Object getItem(int position) { 
    return position; 
} 

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

public View getView(int position, View convertView, ViewGroup parent) { 
    View vi=convertView; 
    if(convertView==null) 
     vi = inflater.inflate(R.layout.listrow, null); 

    TextView title = (TextView)vi.findViewById(R.id.title); 
    TextView description = (TextView)vi.findViewById(R.id.description); 
    TextView cost = (TextView)vi.findViewById(R.id.cost); 
    ImageView thumb_image=(ImageView)vi.findViewById(R.id.list_image); 


    HashMap<String, String> item = new HashMap<String, String>(); 
    item = data.get(position); 

    // Setting all values in listview 
    title.setText(item.get(Catalogue.KEY_TITLE)); 
    description.setText(item.get(Catalogue.KEY_DESCRIPTION)); 
    cost.setText(item.get(Catalogue.KEY_COST)); 

    imageLoader.DisplayImage(item.get(Catalogue.KEY_THUMB_URL), thumb_image); 
    return vi; 
} 
} 

Soyez heureux ...... Bonne programmation Happy Ending

+0

merci mon pote c'est ce que je cherchais, je viens de changer le nom des variables et ID de widget et fait ... Merci, vous avez fait ma semaine .... DIEU vous bénisse ... – Babu

Questions connexes