Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8733753
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 13, 20262026-06-13T09:42:56+00:00 2026-06-13T09:42:56+00:00

I’ve made gridview application that get image path from JSON. my gridview had store

  • 0

I’ve made gridview application that get image path from JSON. my gridview had store 2 images. among 2 image I just can get one image.in class ImageLoaderTask I created String frameUrl to use like imgUrl but I don’t know how to use. I tried to find a lot of solution but it can’t.

How can I reuse connection HttpUrlConnection to get one more image to display in gridview?

String strUrl = "http://192.168.10.104/adchara1/";
GridView gridView;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    // Creating a new non-ui thread task to download json data
    DownloadTask downloadTask = new DownloadTask();

    // Starting the download process
    downloadTask.execute(strUrl);

    gridView = (GridView) findViewById(R.id.lv_countries);        
    gridView.setOnItemClickListener(new OnItemClickListener() {

        public void onItemClick(AdapterView<?> parent, View v, int positon,
                long id) {
             HashMap<String, Object> hm = (HashMap<String, Object>) gridView.getAdapter().getItem(positon);
             String imgPath = (String) hm.get("photo"); //get downloaded image path
             Intent i = new Intent(MainActivity.this, DisplayActivity.class); //start new Intent to another Activity.
             i.putExtra("ClickedImagePath", imgPath ); //put image link in intent.
             startActivity(i);
        }
    });
}

/** A method to download json data from url */
private String downloadUrl(String strUrl) throws IOException{
  String data = "";
  InputStream iStream = null;

    HttpClient httpClient = new DefaultHttpClient();
    HttpPost httpPost = new HttpPost(strUrl);
    ArrayList<NameValuePair> param = new ArrayList<NameValuePair>();
    try {
        httpPost.setEntity(new UrlEncodedFormEntity(param));
        HttpResponse httpResponse = httpClient.execute(httpPost);
        HttpEntity httpEntity = httpResponse.getEntity();
        iStream = httpEntity.getContent();
    } catch (Exception e) {
        Log.e("log_tag", "Error in http connection " + e.toString());
    }
    try {
        BufferedReader br = new BufferedReader(new InputStreamReader(iStream));
        StringBuilder sb = new StringBuilder();
        String line = "";
        while((line = br.readLine()) != null){
            sb.append(line + "\n");
        }
        iStream.close();
        data = sb.toString();
    } catch (Exception e) {
        Log.e("log_tag", "Error converting result " + e.toString());
    }
    return data;
}

/** AsyncTask to download json data */
private class DownloadTask extends AsyncTask<String, Integer, String>{
    String data = null;
    @Override
    protected String doInBackground(String... url) {
        try{
            data = downloadUrl(url[0]);
        }catch(Exception e){
            Log.d("Background Task",e.toString());
        }
        return data;
    }

    @Override
    protected void onPostExecute(String result) {

        // The parsing of the xml data is done in a non-ui thread
        GridViewLoaderTask gridViewLoaderTask = new GridViewLoaderTask();

        // Start parsing xml data
        gridViewLoaderTask.execute(result);
    }
}

/** AsyncTask to parse json data and load ListView */
private class GridViewLoaderTask extends AsyncTask<String, Void, SimpleAdapter>{

    JSONObject jObject;
    // Doing the parsing of xml data in a non-ui thread
    @Override
    protected SimpleAdapter doInBackground(String... strJson) {
        try{
            jObject = new JSONObject(strJson[0]);
            CountryJSONParser countryJsonParser = new CountryJSONParser();
            countryJsonParser.parse(jObject);
        }catch(Exception e){
            Log.d("JSON Exception1",e.toString());
        }

        // Instantiating json parser class
        CountryJSONParser countryJsonParser = new CountryJSONParser();

        // A list object to store the parsed countries list
        List<HashMap<String, Object>> countries = null;

        try{
            // Getting the parsed data as a List construct
            countries = countryJsonParser.parse(jObject);
        }catch(Exception e){
            Log.d("Exception",e.toString());
        }

        // Keys used in Hashmap
        String[] from = { "frame","photo"};

        // Ids of views in listview_layout
        int[] to = { R.id.iv_frame,R.id.iv_photo};

        // Instantiating an adapter to store each items
        // R.layout.listview_layout defines the layout of each item
        SimpleAdapter adapter = new SimpleAdapter(getBaseContext(), countries, R.layout.lv_layout, from, to);
        return adapter;
    }

    /** Invoked by the Android on "doInBackground" is executed */
    protected void onPostExecute(SimpleAdapter adapter) {

        // Setting adapter for the listview
        gridView.setAdapter(adapter);

        for(int i=0;i<adapter.getCount();i++){
            HashMap<String, Object> hm = (HashMap<String, Object>) adapter.getItem(i);
            String frameUrl = (String) hm.get("frame_path");
            String imgUrl = (String) hm.get("photo_path");
            ImageLoaderTask imageLoaderTask = new ImageLoaderTask();

            HashMap<String, Object> hmDownload = new HashMap<String, Object>();
            hm.put("frame_path", frameUrl);
            hm.put("photo_path",imgUrl);
            hm.put("position", i);

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

    /** AsyncTask to download and load an image in ListView */
    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 frameUrl;
            imgUrl = (String) hm[0].get("photo_path");
            frameUrl = (String) hm[0].get("frame_path");
            int position = (Integer) hm[0].get("position");

            URL url;
            URL urlFrame;
            try {
                url = new URL(imgUrl);
                urlFrame = new URL(frameUrl);
                // 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("photo", tmpFile.getPath());
                hmBitmap.put("frame", 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 (MalformedURLException e) {
                return null;
            } catch (FileNotFoundException e) {
                return null;
            } catch (IOException e) {
                return null;
            }
        }

    @Override
    protected void onPostExecute(HashMap<String, Object> result) {
        // Getting the path to the downloaded image
        String path = (String) result.get("photo");
        String framePath = (String) result.get("frame");
        // Getting the position of the downloaded image
        int position = (Integer) result.get("position");

        // Getting adapter of the listview
        SimpleAdapter adapter = (SimpleAdapter ) gridView.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("photo",path);
        hm.put("frame", framePath);
        // Noticing listview about the dataset changes
        adapter.notifyDataSetChanged();
    }
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.activity_main, menu);
    return true;
}
}
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-13T09:42:57+00:00Added an answer on June 13, 2026 at 9:42 am

    Try using smart image view. It takes care of downloading the image from HTTP URI and caching of the image. Following are more detail about the smart image view:

    http://loopj.com/android-smart-image-view/

    https://github.com/loopj/android-smart-image-view

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I'm parsing an RSS feed that has an &#8217; in it. SimpleXML turns this
link Im having trouble converting the html entites into html characters, (&# 8217;) i
That's pretty much it. I'm using Nokogiri to scrape a web page what has
I have just tried to save a simple *.rtf file with some websites and
I have a small JavaScript validation script that validates inputs based on Regex. I
For some reason, after submitting a string like this Jack’s Spindle from a text
I have a string like this: La Torre Eiffel paragonata all&#8217;Everest What PHP function
I've got a string that has curly quotes in it. I'd like to replace
I have a French site that I want to parse, but am running into
I am doing a simple coin flipping experiment for class that involves flipping a

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.