Android - 从网络下载图像,保存到应用程序私有位置的内存中,显示列表项

发布于 2024-10-02 06:39:27 字数 2046 浏览 3 评论 0原文

我想做的是:我希望我的应用程序从互联网下载图像并将其保存到手机内存中应用程序私有的位置。如果列表项没有可用的图像(即无法在 Internet 上找到),我希望显示默认的占位符图像。这是我在 list_item_row.xml 文件中定义为默认图像。

在我的 ListActivity 文件中,我正在调用我编写的 CustomCursorAdapter 类的实例。在 CustomCursorAdapter 中,我迭代所有列表项并定义需要映射到视图的内容,包括尝试从内部存储器读取图像文件。

我已经看到了关于这个主题的几个问题,但是这些示例要么特定于外部手机内存(例如 SDCard),涉及保存字符串而不是图像,要么涉及使用 Bitmap.compressFormat 来降低文件的分辨率(这在我的情况是,因为这些图像将是分辨率已经很小的小缩略图)。尝试将每个示例中的代码拼凑在一起很困难,因此我询问了我的具体示例。

目前,我相信我已经编写了有效的代码,但没有为我的列表项显示图像,包括默认的占位符图像。我不知道问题是否是由无效的下载/保存代码或无效的读取代码引起的 - 我不知道如何检查内部存储器以查看图像是否存在,这没有帮助。

无论如何,这是我的代码。任何帮助将不胜感激。

ProductUtils.java

public static String productLookup(String productID, Context c) throws IOException {
    URL url = new URL("http://www.samplewebsite.com/" + productID + ".jpg");
    URLConnection connection = url.openConnection();
    InputStream input = connection.getInputStream();
    FileOutputStream output = 
        c.openFileOutput(productID + "-thumbnail.jpg", Context.MODE_PRIVATE);
    byte[] data = new byte[1024];

    output.write(data);
    output.flush();
    output.close();
    input.close();
}

CustomCursorAdapter.java

public class CustomCursorAdapter extends CursorAdapter {
    public CustomCursorAdapter(Context context, Cursor c) {
        super(context, c);
    }

    @Override
    public void bindView(View view, Context context, Cursor cursor) {
        ImageView thumbnail = (ImageView) view.findViewById(R.id.thumbnail);

        String fileName = 
                cursor.getString(cursor.getColumnIndex(DbAdapter.KEY_IMAGE_FILE_PATH));

        Bitmap bMap = BitmapFactory.decodeFile(fileName);
        thumbnail.setImageBitmap(bMap);
    }

    @Override
    public View newView(Context context, Cursor cursor, ViewGroup parent) {
        LayoutInflater inflater = LayoutInflater.from(context);
        View v = inflater.inflate(R.layout.list_item_row, parent, false);
        bindView(v, context, cursor);
        return v;
    }
}

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 application. If there is no image available for the list item (i.e. it can't be found on the Internet), I want a default placeholder image to display. This is the image that I have defined in my list_item_row.xml file as the default.

In my ListActivity file, I am calling an instance of a CustomCursorAdapter class I have written. It is in CustomCursorAdapter where I am iterating through all the list items and defining what content needs to be mapped to the views, including the image file by trying to read it from internal memory.

I've seen several questions on this subject, but the examples either are specific to external phone memory (e.g. SDCard), involve saving strings instead of images, or involve using Bitmap.CompressFormat to reduce the resolution of the file (which is unnecessary in my case, as these images will be small thumbnails of already-small resolution). Trying to piece together code from each example has been difficult, hence my asking about my specific example.

At the moment, I believe I've written valid code, but no image is displaying for my list items, including the default placeholder image. I don't know if the problem is being caused by invalid download/save code, or invalid read code - it doesn't help that I don't know how to check internal memory to see if the image exists.

Anyways, here's my code. Any help would be greatly appreciated.

ProductUtils.java

public static String productLookup(String productID, Context c) throws IOException {
    URL url = new URL("http://www.samplewebsite.com/" + productID + ".jpg");
    URLConnection connection = url.openConnection();
    InputStream input = connection.getInputStream();
    FileOutputStream output = 
        c.openFileOutput(productID + "-thumbnail.jpg", Context.MODE_PRIVATE);
    byte[] data = new byte[1024];

    output.write(data);
    output.flush();
    output.close();
    input.close();
}

CustomCursorAdapter.java

public class CustomCursorAdapter extends CursorAdapter {
    public CustomCursorAdapter(Context context, Cursor c) {
        super(context, c);
    }

    @Override
    public void bindView(View view, Context context, Cursor cursor) {
        ImageView thumbnail = (ImageView) view.findViewById(R.id.thumbnail);

        String fileName = 
                cursor.getString(cursor.getColumnIndex(DbAdapter.KEY_IMAGE_FILE_PATH));

        Bitmap bMap = BitmapFactory.decodeFile(fileName);
        thumbnail.setImageBitmap(bMap);
    }

    @Override
    public View newView(Context context, Cursor cursor, ViewGroup parent) {
        LayoutInflater inflater = LayoutInflater.from(context);
        View v = inflater.inflate(R.layout.list_item_row, parent, false);
        bindView(v, context, cursor);
        return v;
    }
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

好像遗漏了一些代码,我重新编写了这样的:

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

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();
    }
}
薄荷梦 2024-10-09 06:39:27

看起来在尝试读取图像时仅仅引用图像文件名是不够的,我必须调用 getFilesDir() 来获取文件存储的路径。下面是我使用的代码:

String path = context.getFilesDir().toString();
String fileName = cursor.getString(cursor.getColumnIndex(DbAdapter.KEY_PRODUCT_ID));

if (fileName != null && !fileName.equals("")) {
    Bitmap bMap = BitmapFactory.decodeFile(path + "/" + fileName);
    if (bMap != null) {
        thumbnail.setImageBitmap(bMap);
    }
}

Looks like simply referring to the image file name when trying to read it was not enough, and I had to call getFilesDir() to get the path of the file storage. Below is the code I used:

String path = context.getFilesDir().toString();
String fileName = cursor.getString(cursor.getColumnIndex(DbAdapter.KEY_PRODUCT_ID));

if (fileName != null && !fileName.equals("")) {
    Bitmap bMap = BitmapFactory.decodeFile(path + "/" + fileName);
    if (bMap != null) {
        thumbnail.setImageBitmap(bMap);
    }
}
苏大泽ㄣ 2024-10-09 06:39:27
void  writeToFile(Bitmap _bitmapScaled)
    {
        ByteArrayOutputStream bytes = new ByteArrayOutputStream();
        _bitmapScaled.compress(Bitmap.CompressFormat.PNG, 40, bytes);
        try{
        File f;
        //you can create a new file name "test.jpg" in sdcard folder.
        if (android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED))
            f =new File(android.os.Environment.getExternalStorageDirectory(),"FamilyLocator/userimages/"+imageName);
        else
         f = new File(Environment.getDataDirectory(),"FamilyLocator/userimages/"+imageName);

        f.createNewFile();
        //write the bytes in file
        FileOutputStream fo = new FileOutputStream(f);
        fo.write(bytes.toByteArray());
        // remember close de FileOutput
        fo.close();
        }catch(Exception e){e.printStackTrace();}
    }
void  writeToFile(Bitmap _bitmapScaled)
    {
        ByteArrayOutputStream bytes = new ByteArrayOutputStream();
        _bitmapScaled.compress(Bitmap.CompressFormat.PNG, 40, bytes);
        try{
        File f;
        //you can create a new file name "test.jpg" in sdcard folder.
        if (android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED))
            f =new File(android.os.Environment.getExternalStorageDirectory(),"FamilyLocator/userimages/"+imageName);
        else
         f = new File(Environment.getDataDirectory(),"FamilyLocator/userimages/"+imageName);

        f.createNewFile();
        //write the bytes in file
        FileOutputStream fo = new FileOutputStream(f);
        fo.write(bytes.toByteArray());
        // remember close de FileOutput
        fo.close();
        }catch(Exception e){e.printStackTrace();}
    }
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文