1

I'm having trouble loading images from my JSON file to the listview in Android

I understand I have to use BitmapFactory.decodeStream but beyond that I'm not really sure how to implement it

Here's my adapter and activity

public class JSON {

static InputStream is = null;

static String jsonString = "";

static JSONObject jObj = null;

public JSON() {

}

public JSONObject getJSONFromUrl(String urlString) {

    try {
        URL url = new URL(urlString);
        HttpURLConnection con = (HttpURLConnection) url.openConnection();
        is = con.getInputStream();
    } catch (Exception e) {
        Log.v("NETWORK ERROR #1", e.getMessage());
    }

    StringBuilder sb = new StringBuilder();
    BufferedReader reader = null;
    try {
        reader = new BufferedReader(new InputStreamReader(is));

        String line = "";
        while ((line = reader.readLine()) != null) {
            sb.append(line);
        }
    } catch (IOException e) {
        Log.v("NETWORK ERROR #2 ", e.getMessage());
    } finally {
        if (reader != null) {
            try {
                reader.close();
            } catch (IOException e) {
                Log.v("NETWORK ERROR #3", e.getMessage());
            }

            jsonString = sb.toString();
        }
    }

    try {
        jObj = new JSONObject(jsonString);
    } catch (JSONException e) {
        Log.e("JSON Parser", "Error parsing data " + e.toString());
    }

    return jObj;
    }
}

public class Main2Activity extends ListActivity {

//JSON URL
private static String url = "http://pastebin.com/raw.php?i=8eTR5TXv";

private static final String ALBUMS = "album";

private static final String C_ALBUMS = "c_album";
private static final String C_ARTISTS = "c_artist";
private static final String C_DATES = "c_date";
private static final String C_RATINGS = "c_rating";
private static final String C_PICS = "c_pic";

JSONArray albumType = null;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main2);

    //Turn off StrictMode
    StrictMode.ThreadPolicy policy = new StrictMode.
            ThreadPolicy.Builder().permitAll().build();
    StrictMode.setThreadPolicy(policy);

    ArrayList<HashMap<String, String>> contactList = new ArrayList<HashMap<String, String>>();

    JSON jParser = new JSON();

    JSONObject json = jParser.getJSONFromUrl(url);

    try {
        albumType = json.getJSONArray(ALBUMS);

        for(int i = 0; i < albumType.length(); i++){
            JSONObject a = albumType.getJSONObject(i);

            String cAlbum = a.getString(C_ALBUMS);
            String cArtist = a.getString(C_ARTISTS);
            String cDate = a.getString(C_DATES);
            String cRating = a.getString(C_RATINGS);
            String cPic = a.getString(C_PICS);

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

            map.put(C_ALBUMS, cAlbum);
            map.put(C_ARTISTS, cArtist);
            map.put(C_DATES, cDate);
            map.put(C_RATINGS, cRating);
            map.put(C_PICS, cPic);

            contactList.add(map);
        }

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

    ListAdapter adapter = new SimpleAdapter(
            this,
            contactList,
            R.layout.row2,
            new String[] { C_ALBUMS, C_ARTISTS, C_DATES, C_RATINGS, C_PICS },
            new int[] {R.id.tv_albumName, R.id.tv_Artist, R.id.tv_Date, R.id.tv_Rating, R.id.tv_pic}
    );

    setListAdapter(adapter);
}

and the XML

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/ALBUM_NAME"
    android:id="@+id/tv_albumName"
    android:textSize="20sp"
    android:layout_alignParentTop="true"
    android:layout_alignParentLeft="true"
    android:layout_alignParentStart="true" />

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/ARTIST"
    android:id="@+id/tv_Artist"
    android:textSize="12sp"
    android:layout_below="@+id/tv_albumName"
    android:layout_alignLeft="@+id/tv_albumName"
    android:layout_alignStart="@+id/tv_albumName" />

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/DATE"
    android:id="@+id/tv_Date"
    android:textSize="12sp"
    android:layout_below="@+id/tv_Artist"
    android:layout_alignLeft="@+id/tv_Artist"
    android:layout_alignStart="@+id/tv_Artist" />

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/RATING"
    android:id="@+id/tv_Rating"
    android:textSize="12sp"
    android:layout_below="@+id/tv_Date"
    android:layout_alignLeft="@+id/tv_Date"
    android:layout_alignStart="@+id/tv_Date" />

<ImageView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/tv_pic"
    android:layout_alignBottom="@+id/tv_Date"
    android:layout_alignParentRight="true"
    android:layout_alignParentEnd="true"
    android:padding="1sp"/>

Any help would be greatly appreciated, thanks

7
  • If you run the app, does it show anything or give any errors? Commented Dec 9, 2015 at 4:38
  • Sorry, added adapter. If I run the app with my current code, it all works, the images just don't show Commented Dec 9, 2015 at 6:26
  • Possible duplicate of Lazy load of images in ListView Commented Dec 9, 2015 at 6:40
  • Please share what are you getting in logcat detail, that would be helpful to investigate what is happing wrong in the code. Commented Dec 9, 2015 at 6:45
  • The way you write the code its obvious you are trying to set the URL to ImageView... It's not possible. After you acheive the URL you have to download the image and then you can display it. Use some of the known libraries like the other people suggest. Commented Dec 9, 2015 at 6:48

2 Answers 2

2

You just have to use Image Loader Libraries like Picasso, Glide.

May this link will helpful to use Introduction to Glide, Image Loader Library for Android, recommended by Google

Picasso:

Picasso.with(context)
    .load("http://inthecheesefactory.com/uploads/source/glidepicasso/cover.jpg")
    .into(ivImg);

Glide:

Glide.with(context)
    .load("http://inthecheesefactory.com/uploads/source/glidepicasso/cover.jpg")
    .into(ivImg);

Or You can try Universal Image Loader Library in Android

//your image url
String url = "Your Image URL";

ImageLoader imageLoader = ImageLoader.getInstance();
DisplayImageOptions options = new DisplayImageOptions.Builder().cacheInMemory(true)
                .cacheOnDisc(true).resetViewBeforeLoading(true)
                .showImageForEmptyUri(fallback)
                .showImageOnFail(fallback)
                .showImageOnLoading(fallback).build();

//initialize image view
ImageView imageView = (ImageView) findViewById(R.id.imageView1)     

//download and display image from url
imageLoader.displayImage(url, imageView, options);
Sign up to request clarification or add additional context in comments.

Comments

1

You can use a simple library to display images in Android ListView. Images are being downloaded asynchronously in the background. Images are being cached on SD card and in memory.

Get LazyList from here

ImageLoader imageLoader=new ImageLoader(context);
...
imageLoader.DisplayImage(url, imageView);

Don't forget to add the following permissions to your AndroidManifest.xml:

<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

1 Comment

imageLoader.DisplayImage("contactlist.get(position).get("c_pic")", imageView); could be more usefull i guess.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.