1

I have made a program in which I am using PHP to encode data as JSON. My program is working fine, and is not showing any errors or problems; I am getting what I want but I am facing very small issue.

Here, I am not able to show an item's image in ListView but whenever I click on one of the item rows to view full item detail, I get the image of selected item. It means I should be getting the image in ListView, but I'm unable to show that, so could someone please help to sort out this mistake?

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

    }

}
Cat
  • 66,919
  • 24
  • 133
  • 141
Udhikriman
  • 162
  • 1
  • 11

5 Answers5

1

You have to first download the image and then show it in list view. You can not directly pass the image URL, it will not work.

Vipul Purohit
  • 9,807
  • 6
  • 53
  • 76
  • i have downloaded the image, then only trying to show that one, and therefore i am getting item's image in item detailed form, but my bad luck i am missing something that's why not getting in listview, but hopefully i will get it ASAP – Udhikriman Dec 15 '12 at 05:34
1

Change your current code as and also remove runOnUiThread() from onPostExecute method:

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


        }

    }

NOTE : if you are given direct web URL in ImageView then this will never work because you will need first download image from Web then set it to ImageView src.

see this post how we take image from web server

How to load an ImageView by URL in Android?

Community
  • 1
  • 1
ρяσѕρєя K
  • 132,198
  • 53
  • 198
  • 213
  • Thanks to write code, still same problem able to view selected item's image in Item Detail form but not in ListView..help – Udhikriman Dec 15 '12 at 05:51
  • @Udhikriman : sorry dear for this you will need to create a custom adapter and then set it to ImageView see this post http://stackoverflow.com/questions/2471935/how-to-load-an-imageview-by-url-in-android – ρяσѕρєя K Dec 15 '12 at 05:54
  • ok i will do that, i appreciate your efforts to help me and now i am going to give what you deserves....thanks – Udhikriman Dec 15 '12 at 06:00
  • @Udhikriman if you have any issue then tell me i will do for you very quickly ? – ρяσѕρєя K Dec 15 '12 at 06:04
  • thanks i have done and now i am getting image in ListView, can i ask a question last time? – Udhikriman Dec 15 '12 at 06:07
  • thanks friend, i am using this tutorial http://www.javacodegeeks.com/2010/05/getting-started-with-youtube-java-api.html and getting this error YouTubeService cannot be resolved to a type or you can show me some other tutorial or source code link to get list of youtube videos in android and allow user to play selected one, by using this link i want show list of videos : www.youtube.com/playlist?list=PL34F010EEF9D45FB8 – Udhikriman Dec 15 '12 at 06:13
  • please frnd help me i am waiting for your reply and i believe you will support me to complete this task like earlier you have supported..... – Udhikriman Dec 15 '12 at 06:35
  • @Udhikriman : when you are getting this `YouTubeService cannot be resolved to a type` error? – ρяσѕρєя K Dec 15 '12 at 06:50
  • @Udhikriman : because i have imported [this](http://dl.dropbox.com/u/7215751/JavaCodeGeeks/YoutubeApiTutorial/YouTubeApiProject.zip) in my workspace without any error? – ρяσѕρєя K Dec 15 '12 at 06:52
  • @Udhikriman : no dear i think this is best tutorial for what you want – ρяσѕρєя K Dec 15 '12 at 06:58
  • @ ρяσѕρєя K friend like earlier i am still getting this message: Select a directory to search for existing Android projects while importing this project and really i don't why because i have imported many projects earlier in same way...help – Udhikriman Dec 15 '12 at 06:58
  • @Udhikriman : ok then share with me your project then i will do for you – ρяσѕρєя K Dec 15 '12 at 07:00
  • thanks again friend for awesome support, I just want to fetch list of YouTube videos then want to allow user to play selected video and download button with each video to download that's it..buddy if you have time for me so please help i really need this one and can i have your email address for further link if you don't have any problem, and brother use this link :http://www.youtube.com/playlist?list=PL34F010EEF9D45FB8 – Udhikriman Dec 15 '12 at 07:07
  • Hi friend i am still waiting for your reply, i know you are one of the genius developer who has solved 1000s of problem at stackoverflow like day before yesterday within 10 minutes you have solved my problem also, but brother youtube list of videos are so important and urgent for me and i still believe you are making for me a demo program...thanks – Udhikriman Dec 17 '12 at 06:03
  • @Udhikriman : thanks man as i already told you send me your code then i will try for you but you are not sharing code then how i will try to solve your issue. – ρяσѕρєя K Dec 17 '12 at 06:05
  • Please browse this link: http://stackoverflow.com/questions/13930921/the-import-com-facebook-cannot-be-resolved/13931000#comment19206427_13931000 – Udhikriman Dec 18 '12 at 12:12
  • 1
    @Udhikriman : i will see your issue after 9:00PM and put as answer in your question so make your question very clean plz – ρяσѕρєя K Dec 18 '12 at 12:14
  • Thanks nice to meet you :) – ρяσѕρєя K Dec 19 '12 at 06:04
  • I am so happy with your replies and comments, really helpful – Udhikriman Dec 19 '12 at 06:09
  • @Udhikriman : then why you are not accepting my answers dear :) – ρяσѕρєя K Dec 19 '12 at 06:11
  • bhaiya i have already accepted see here : http://stackoverflow.com/questions/13946013/not-getting-list-of-youtube-videos/13946071#comment19232282_13946071 – Udhikriman Dec 19 '12 at 06:14
  • sorry bhaiya i forgot, i just given useful but now i have also ticked on right arrow now happy, i am new at Stackoverflow that's why doing some silly mistakes – Udhikriman Dec 19 '12 at 06:16
1

It means that you want to customize your list view with image and text. For that (what i did in my case), get the image url and text in two arrays. then set the adapter of the list view by passing context, both arrays.

For setting up images, you need to import the library (Either image url helper or Universe image loader). Both can help you well but i will recommend you for the image url helper library because it is easy to use.

Rohit
  • 490
  • 3
  • 15
1

Try this in your Adapter, It might help you:

 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);
     }        
RajeshVijayakumar
  • 10,281
  • 11
  • 57
  • 84
0

remov the runOnUiThread() from the post Execute and you do not run UI component into thread.. simply set images...

QuokMoon
  • 4,387
  • 4
  • 26
  • 50