Archish
Archish

Reputation: 870

setting image in listview not working in android

i want to display restaurent name and its image in listview. i am sucessfully getting restaurent name but not getting images.this is my code.i've acctach my output screen you can see that restaurent name is displaying but images are not displying they should be lefthand side

public class RestaurantSelect extends Activity {
ProgressDialog mProgressDialog;
ListView listview;
private String key,ResCategory,url;
private SimpleAdapter listadapter;
JsonArray jobj= new JsonArray();
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_restaurant_select);

    new AreaPOP().execute();
    listview = (ListView) findViewById(R.id.listResturent);
    Intent in = getIntent();

    try
    {
        if(!in.getStringExtra("AreaID").isEmpty())
        {
            //url="http://192.168.0.2/cityapp/GETresturentByArea.php";
            url="http://www.mycityapp.co.in/api/GETresturentByArea.php";
            key=in.getStringExtra("AreaID");
        }
    }
    catch (Exception e)
    {
        //url="http://192.168.0.2/cityapp/GETresturentByCategory.php";
        url="http://www.mycityapp.co.in/api/GETresturentByCategory.php";
        key=in.getStringExtra("ResCategory");
    }
    listview.setOnItemClickListener(new OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> arg0, View arg1, int position, long id) {
            //http://saigeethamn.blogspot.in/2010/04/custom-listview-android-developer.html
            //http://www.androidhive.info/2012/01/android-json-parsing-tutorial/
            //http://digitallibraryworld.com/?p=195
            HashMap fullObject = (HashMap)arg0.getItemAtPosition(position);
            Intent in = new Intent(getApplicationContext(), RestaurantDetail.class);
            in.putExtra("ResID", fullObject.get("rowid").toString());
            startActivity(in);
        }
    });

}

private class AreaPOP extends AsyncTask<Void, Void, Void> {

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        mProgressDialog = new ProgressDialog(RestaurantSelect.this);
        mProgressDialog.setTitle("getting data");

        mProgressDialog.setMessage("Loading...");
        mProgressDialog.setIndeterminate(false);
        mProgressDialog.show();
    }


    @Override
    protected Void doInBackground(Void... params) {
       // String url_create_product="http://www.mycityapp.co.in/api/GETresturent.php";

        List<NameValuePair> paramsRes = new ArrayList<NameValuePair>();
        paramsRes.add(new BasicNameValuePair("key", key));
        JSONArray json = jobj.makeHttpRequest(url,"POST", paramsRes);
        List<HashMap<String, Object>> listdata = new ArrayList<HashMap<String, Object>>();
        JSONObject c;
        for (int i=0;i<json.length();i++){
            try {
                HashMap<String,Object> temp = new HashMap<String,Object>();
                c = json.getJSONObject(i);
                temp.put("rowid",c.getString("rowid"));
                temp.put("restaurantname", c.getString("restaurantname").toUpperCase());
                temp.put("resMainImg", c.getString("resMainImg"));
                temp.put("img",R.drawable.ic_launcher);
                listdata.add(temp);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        listadapter = new SimpleAdapter(RestaurantSelect.this,listdata,R.layout.custom_row_view,new String[] {"restaurantname","resMainImg"},new int[] {R.id.txtListRest,R.id.imgListRestMainPic});

        return null;
    }
    @Override
    protected void onPostExecute(Void args) {
        listview.setAdapter(listadapter);
        for(int i=0;i<listadapter.getCount();i++){

            HashMap<String, Object> hm = (HashMap<String, Object>) listadapter.getItem(i);
            String imgUrl = (String) hm.get("resMainImg");
            ImageLoaderTask imageLoaderTask = new ImageLoaderTask();
            HashMap<String, Object> hmDownload = new HashMap<String, Object>();
            hm.put("resMainImg",imgUrl);
            hm.put("position", i);

            // Starting ImageLoaderTask to download and populate image in the listview
            imageLoaderTask.execute(hm);

        }
        mProgressDialog.dismiss();
    }

}

private class ImageLoaderTask extends AsyncTask<HashMap<String, Object>, Void, HashMap<String, Object>>{

    @Override
    protected HashMap<String, Object> doInBackground(HashMap<String, Object>... hm) {

        InputStream iStream=null;
        String imgUrl = (String) hm[0].get("resMainImg");
        int position = (Integer) hm[0].get("position");
        URL url;
        try {
            url = new URL(imgUrl);

            // Creating an http connection to communicate with url
            HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();

            // Connecting to url
            urlConnection.connect();

            // Reading data from url
            iStream = urlConnection.getInputStream();

            // Getting Caching directory
            File cacheDirectory = getBaseContext().getCacheDir();

            // Temporary file to store the downloaded image
            File tmpFile = new File(cacheDirectory.getPath() + "/wpta_"+position+".png");

            // The FileOutputStream to the temporary file
            FileOutputStream fOutStream = new FileOutputStream(tmpFile);

            // Creating a bitmap from the downloaded inputstream
            Bitmap b = BitmapFactory.decodeStream(iStream);

            // Writing the bitmap to the temporary file as png file
            b.compress(Bitmap.CompressFormat.PNG,100, fOutStream);

            // Flush the FileOutputStream
            fOutStream.flush();

            //Close the FileOutputStream
            fOutStream.close();

            // Create a hashmap object to store image path and its position in the listview
            HashMap<String, Object> hmBitmap = new HashMap<String, Object>();

            // Storing the path to the temporary image file
            hmBitmap.put("flag",tmpFile.getPath());

            // Storing the position of the image in the listview
            hmBitmap.put("position",position);

            // Returning the HashMap object containing the image path and position
            return hmBitmap;


        }catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    protected void onPostExecute(HashMap<String, Object> result) {

        // Getting the path to the downloaded image
        String path = (String) result.get("flag");
        // Getting the position of the downloaded image
        int position = (Integer) result.get("position");
        // Getting adapter of the listview
        SimpleAdapter adapter = (SimpleAdapter ) listview.getAdapter();
        // Getting the hashmap object at the specified position of the listview
        HashMap<String, Object> hm = (HashMap<String, Object>) adapter.getItem(position);
        // Overwriting the existing path in the adapter
        hm.put("flag", path);
        // Noticing listview about the dataset changes
        adapter.notifyDataSetChanged();
    }


}

}

and i am getting this in logcat.

10-16 14:13:33.096  14005-14005/com.example.db2admin.cityapp I/System.out﹕ resolveUri failed on bad bitmap uri: http://www.mycityapp.co.in/cityappimg/res4/menu/images1.jpg
10-16 14:13:33.098  14005-14005/com.example.db2admin.cityapp E/BitmapFactory﹕ Unable to decode stream: java.io.FileNotFoundException: http:/www.indiandelicacy.in/Content/Restaurant/26/original-Kansar-Gujarati-Thali-logo.jpg: open failed: ENOENT (No such file or directory)
10-16 14:13:33.098  14005-14005/com.example.db2admin.cityapp I/System.out﹕ resolveUri failed on bad bitmap uri: http://www.indiandelicacy.in/Content/Restaurant/26/original-Kansar-Gujarati-Thali-logo.jpg
10-16 14:13:33.101  14005-14005/com.example.db2admin.cityapp E/BitmapFactory﹕ Unable to decode stream: java.io.FileNotFoundException: http:/www.wokonfirechinese.com/html/images/wok-on-fire-chinese-logo.png: open failed: ENOENT (No such file or directory)

this is my output

Upvotes: 0

Views: 136

Answers (5)

Hari Krishnan
Hari Krishnan

Reputation: 6302

You can use Picasso library to display images. Add this library in your build.gradle dependencies:

compile 'com.squareup.picasso:picasso:2.4.0'

Now use this to display images

File file = new File(imagePath);
 if(file.exists()) {
        Picasso.with(context).load(file).skipMemoryCache().placeholder(R.drawable.placeholder).into(yourImageView);
    } 

Remember to keep a placeholder for your image in your drawable folder.

Upvotes: 0

Sergey Shevchenko
Sergey Shevchenko

Reputation: 56

I think this is what you need. Also you can use Picasso, UniversalImageLoader or something like that to download images. I hope it is helpfull for you.

Upvotes: 0

Aditya Vyas-Lakhan
Aditya Vyas-Lakhan

Reputation: 13555

Aquery is also using for image loading, download aquery jar and import it in your project and try this way

 public class MainActivity extends Activity {

    private ImageView img;
    private AQuery aq;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        aq = new AQuery(this);
        img=(ImageView)findViewById(R.id.simpleLoadImg);
        aq.id(R.id.simpleLoadImg).image("http://sexocomcafe1-teste.tempsite.ws/imagensUsuario13/avata/Atra%C3%A7%C3%A3o%20PerigosaRJ_44690132.jpg",false,false);

    }


}

OR

You can also use Fresco lib

Upvotes: 0

Shivani Gupta
Shivani Gupta

Reputation: 271

use Picasso library . It is very easy to use and no use of image loader it will load easily .

Upvotes: 1

Bubunyo Nyavor
Bubunyo Nyavor

Reputation: 2570

Image manipulation can be hard in android, i recommend using an existing library like this one

Upvotes: 1

Related Questions