1

我想要如果我的应用程序第一次启动它应该从网络下载图像并将该图像存储在 中Device/EmulatorDevice/Emulator应该显示在ImageView. 我试过这样:

ImageView myImgView;

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

    myImgView = (ImageView) findViewById(R.id.imageView1);      

    new MyAsnyc();
     Log.d(MY_TAGT, "AsyncTask Executed.....");

}
private class MyAsnyc extends AsyncTask<Void, Void,Void>{
    public File file ;
    InputStream is;
    private Bitmap bitmap;
    protected void doInBackground() throws IOException{

        File path = Environment.getExternalStoragePublicDirectory(
                Environment.DIRECTORY_PICTURES);
        file = new File(path, "DemoPicture.jpg");
        try{
            // Make sure the Pictures directory exists.
            path.mkdirs();

            URL url = new      URL(BASE_URL);
            /* Open a connection to that URL. */
            URLConnection ucon = url.openConnection();

            /*
             * Define InputStreams to read from the URLConnection.
             */
            is = ucon.getInputStream();

            OutputStream os = new FileOutputStream(file);
            byte[] data = new byte[is.available()];
            is.read(data);
            Log.i(MY_TAGT, "Picture is readable........");
            os.write(data);
            Log.i(MY_TAGT, "Picture is Saved........");
            is.close();
            os.close();

        }
        catch (IOException e) {
            Log.d("ImageManager", "Error: " + e);
        }
    }
    @Override
    protected Void doInBackground(Void... params) {
        // TODO Auto-generated method stub

        try {
            doInBackground();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return null;
    }
    protected void onPostExecute(){

        try{
            // Tell the media scanner about the new file so that it is
            // immediately available to the user.

            MediaScannerConnection.scanFile(null,
                    new String[] { file.toString() }, null,
                    new MediaScannerConnection.OnScanCompletedListener() {
                public void onScanCompleted(String path, Uri uri) {
                    Log.i("ExternalStorage", "Scanned " + path + ":");
                    Log.i("ExternalStorage", "-> uri=" + uri);
                }
            });
        }
        catch (Exception e) {
            // TODO: handle exception

        }

        /*Here I want to set this image in ImageView*/

        bitmap = BitmapFactory.decodeFile(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).toString()+"/DemoPicture.jpg");
        myImgView.setImageBitmap(bitmap);
    }
}

但是以这种方式MyAsync不执行类,请告诉如何做到这一点。

EDIT这是我的日志

在此处输入图像描述

4

5 回答 5

6

使用执行来调用它。

new MyAsnyc().execute();
于 2013-03-07T12:29:05.553 回答
1

采用

new MyAsnyc().execute();

代替

new MyAsnyc();

因为AsyncTask.execute(Params...params)方法用于执行 AsyncTask

编辑 :

使用 While 或 for 循环将数据写入文件中:

OutputStream os = new FileOutputStream(file);
            byte[] data = new byte[is.available()];

            Log.i(MY_TAGT, "Picture is readable........");
            int count;
            while ( (count = is.read(data)) >= 0 ) {
              os.write(data,0,count)
             }

            Log.i(MY_TAGT, "Picture is Saved........");
            is.close();
            os.close();
于 2013-03-07T12:29:25.667 回答
0

您忘记执行 AsyncTask:

(new MyAsnyc()).execute();
于 2013-03-07T12:30:31.373 回答
0

在 Log.d(MY_TAGT, "AsyncTask Executed....."); 行之前 你只是构造了新的 AsyncTask 对象,但你没有用 execute() 方法调用它的执行..

编辑:第二个问题是,实际上你想在那个 ImageView 中显示哪张图片并不是很清楚。因为 bitmap = BitmapFactory.decodeFile(..blahblahblah..) 在此之后可能会为空。在我看来,你给文件夹名称,并且您想将该“文件”解码为位图..制作一些有关此解码和位图值的日志并向我们展示..

编辑2:

文件路径 = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES); 文件文件 = 新文件(路径,“DemoPicture.jpg”);位图 = BitmapFactory.decodeFile(file);

应该工作得更好一点..

于 2013-03-07T12:31:51.533 回答
0

你必须试试这个:

public class DownloadImage {    
public static File getImage(String imageUrl, String fileName){
File file = null;
try {
    //set the download URL, a url that points to a file on the internet
    //this is the file to be downloaded         
    URL url = new URL(imageUrl);
    Log.d("INFORMATION..", "FILE FOUNDED....");
    //create the new connection
    HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();

    //set up some things on the connection
    urlConnection.setRequestMethod("GET");
    urlConnection.setDoOutput(true);

    //and connect!
    urlConnection.connect();
    Log.d("INFORMATION..", "FILE CONECTED....");
    //set the path where we want to save the file
    //in this case, going to save it on the root directory of the
    //sd card.
    File SDCardRoot = Environment.getExternalStorageDirectory();
    //create a new file, specifying the path, and the filename
    //which we want to save the file as.
    file = new File(SDCardRoot, fileName);

    //this will be used to write the downloaded data into the file we created
    FileOutputStream fileOutput = new FileOutputStream(file);
    Log.d("INFORMATION..", "WRINTING TO FILE DOWNLOADED...." + file);
    //this will be used in reading the data from the internet
    InputStream inputStream = urlConnection.getInputStream();

    //this is the total size of the file
    int totalSize = urlConnection.getContentLength();
    //variable to store total downloaded bytes
    int downloadedSize = 0;

    //create a buffer...
    byte[] buffer = new byte[1024];
    int bufferLength = 0; //used to store a temporary size of the buffer

    //now, read through the input buffer and write the contents to the file
    while ( (bufferLength = inputStream.read(buffer)) > 0 ) {
        //add the data in the buffer to the file in the file output stream (the file on the sd card
        fileOutput.write(buffer, 0, bufferLength);
        //add up the size so we know how much is downloaded
        downloadedSize += bufferLength;
        Log.d("INFORMATION..", "FILE DOWNLOADED....");
        //this is where you would do something to report the prgress, like this maybe
        //updateProgress(downloadedSize, totalSize);

    }
    //close the output stream when done
    fileOutput.close();
    Log.d("INFORMATION..", "FILE DOWNLOADING COMPLETED....");
    //catch some possible errors...
} catch (MalformedURLException e) {
    e.printStackTrace();
} catch (IOException e) {
    e.printStackTrace();
}
return file;


 }
}

DownloadImage.getImage(String imageUrl, String fileName)像这样调用MainActivity.java它:

public class MainActivity extends Activity {

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

ImageView imageView = (ImageView) findViewById(R.id.imageView1);

String url = "http://4.bp.blogspot.com/-8v_k_fOcfP8/UQIL4ufghBI/AAAAAAAAEDo/9ffRRTM9AnA/s1600/android-robog-alone.png"; 

String file = DownloadImage.getImage(url, "My Image.jpg").toString();

// Get file path on device and set it to imageView
Bitmap bitmap = BitmapFactory.decodeFile(file);
imageView.setImageBitmap(bitmap);
}
}

我想这就是你要找的!希望对你有帮助

于 2013-03-10T08:32:51.957 回答