Android - downloading image from web, saving to internal memory in location private to app, displaying for list item

后端 未结 3 1372
Happy的楠姐
Happy的楠姐 2021-02-06 11:35

What I\'m trying to do is this: I want my application to download an image from the Internet and save it to the phone\'s internal memory in a location that is private to the app

3条回答
  •  庸人自扰
    2021-02-06 12:16

    it seems that some code is left out, I re-wrote it like this:

    ProductUtils.java

    public static String productLookup(String productID, Context c) throws IOException {
    
        URL url = new URL("http://www.samplewebsite.com/" + productID + ".jpg");
    
        InputStream input = null;
        FileOutputStream output = null;
    
        try {
            String outputName = productID + "-thumbnail.jpg";
    
            input = url.openConnection().getInputStream();
            output = c.openFileOutput(outputName, Context.MODE_PRIVATE);
    
            int read;
            byte[] data = new byte[1024];
            while ((read = input.read(data)) != -1)
                output.write(data, 0, read);
    
            return outputName;
    
        } finally {
            if (output != null)
                output.close();
            if (input != null)
                input.close();
        }
    }
    

提交回复
热议问题