java - 将图像下载到内部存储并在android中读取

标签 java android eclipse

我正在尝试从 url 下载图像,并希望将其显示在 imageview 中。我的代码如下:

package com.example.imageinternalstorage;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;

import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

public class MainActivity extends Activity {
Button btnstoreinternal,btnloadfrominternal;
ImageView iv_category;
boolean download_success;
String URL_image="http://footballultimate.com/storelocator/resource/uploads/";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        btnstoreinternal=(Button) findViewById(R.id.btnstoreinternal);
        btnloadfrominternal=(Button) findViewById(R.id.btnloadfrominternal);
        iv_category=(ImageView) findViewById(R.id.iv_category);
        btnstoreinternal.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                download_success=downloadFile(URL_image+"Hospital.png");
                if(download_success==true)
                {
                    Toast.makeText(getApplicationContext(),"Download success",Toast.LENGTH_LONG).show();
                }
                else
                {
                    Toast.makeText(getApplicationContext(),"Download failed",Toast.LENGTH_LONG).show();
                }

            }
        });
        btnloadfrominternal.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                iv_category.setImageBitmap(getImageBitmap(MainActivity.this,"Hospital.png"));

            }
        });
    }

    public boolean downloadFile(final String path)
    {
        try
        {
            URL url = new URL(path);

            URLConnection ucon = url.openConnection();
            ucon.setReadTimeout(5000);
            ucon.setConnectTimeout(10000);

            InputStream is = ucon.getInputStream();
            BufferedInputStream inStream = new BufferedInputStream(is, 1024 * 5);

            File file = new File(MainActivity.this.getDir("filesdir", Context.MODE_PRIVATE) + "/Hospital.png");

            if (file.exists())
            {
                file.delete();
            }
            file.createNewFile();

            FileOutputStream outStream = new FileOutputStream(file);
            byte[] buff = new byte[5 * 1024];

            int len;
            while ((len = inStream.read(buff)) != -1)
            {
                outStream.write(buff, 0, len);
            }

            outStream.flush();
            outStream.close();
            inStream.close();

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

        return true;
    }

    public Bitmap getImageBitmap(Context context,String name){
          try{
            FileInputStream fis = context.openFileInput(name);
                Bitmap b = BitmapFactory.decodeStream(fis);
                fis.close();
                return b;
            }
            catch(Exception e){
            }
            return null;
        }
}

当我单击第一个按钮时,下载显示为成功。但是当我单击第二个按钮在 ImageView 中显示图像时,什么也没有发生。所以任何人都可以给我一个从内存中检索代码的替换代码:

public Bitmap getImageBitmap(Context context,String name){
          try{
            FileInputStream fis = context.openFileInput(name);
                Bitmap b = BitmapFactory.decodeStream(fis);
                fis.close();
                return b;
            }
            catch(Exception e){
            }
            return null;
        }

下载代码为:

public boolean downloadFile(final String path)
    {
        try
        {
            URL url = new URL(path);

            URLConnection ucon = url.openConnection();
            ucon.setReadTimeout(5000);
            ucon.setConnectTimeout(10000);

            InputStream is = ucon.getInputStream();
            BufferedInputStream inStream = new BufferedInputStream(is, 1024 * 5);

            File file = new File(MainActivity.this.getDir("filesdir", Context.MODE_PRIVATE) + "/Hospital.png");

            if (file.exists())
            {
                file.delete();
            }
            file.createNewFile();

            FileOutputStream outStream = new FileOutputStream(file);
            byte[] buff = new byte[5 * 1024];

            int len;
            while ((len = inStream.read(buff)) != -1)
            {
                outStream.write(buff, 0, len);
            }

            outStream.flush();
            outStream.close();
            inStream.close();

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

        return true;
    }

最佳答案

我认为,自版本 >2.2 起,Android 就不允许在 onCreate 方法中进行此类网络操作。
解决方案:
1-尝试在扩展AsyncTask的主类中使用私有(private)类,如果您不确定返回类型,可以使用Void。例如,看看这个 AndroidHive tutorial ,当他从网站检索 JSON 数据时,他调用了他创建的用于执行网络操作的“GetContacts”类。

2-如果您对 AsyncTask 的所有内容没有感觉,请看一下 Android Volley图书馆有一个不错的AndroidHive tutorial也是如此。

关于java - 将图像下载到内部存储并在android中读取,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25051291/

相关文章:

android - Monkeyrunner 脚本不运行,但命令有效

java - 修复 Eclipse 中的模块 {a} 不会 "opens {package}"到模块 {B}

java - 通过 JSP 使用 Web 服务 JAX

java - 将二维矩形网格拆分为更小网格的算法

android - Android 平台源代码中的断点

java - Buckminster 插件分辨率慢

java - 如何在 Eclipse 中获得完全限定的类名?

java - 如何将 Git 服务器编写或打包为 Java Servlet 或 Java webapp?

java - 嵌套类中对象的数组

具有 START_STICKY 的 Android 服务在终止应用程序时崩溃