从文件服务器下载随机图像

时间:2012-07-26 05:54:47

标签: android imageview download

这是我的尝试。我的文件托管在我自己的服务器上,主要是JPG文件。我正在尝试将它们下载到我的应用程序中。我无法将这些图像生成到我的应用程序中。我按照此博客http://getablogger.blogspot.gr/2008/01/android-download-image-from-server-and.html

的指南进行操作

我的xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView 
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Hello World, HTTPImage load test"
/>
<Button android:id="@+id/get_imagebt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Get an image"
android:layout_gravity="center"
/> 
<ImageView android:id="@+id/imview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
/>
</LinearLayout>

编码

package com.example.downloadimages;

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;




public class MainActivity extends Activity {

    ImageView imView;
    String imageUrl="http://myfilehosting.com/";
    Random r;


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

        r= new Random();

        Button bt3= (Button)findViewById(R.id.get_imagebt);
        bt3.setOnClickListener(getImgListener);
        imView = (ImageView)findViewById(R.id.imview);
    }

    View.OnClickListener getImgListener = new View.OnClickListener()
    {

        public void onClick(View view) {
        // TODO Auto-generated method stub

        //i tried to randomize the file download, in my server i put 4 files with name like
        //jpg0.jpg, jpg1.jpg, jpg2.jpg so different file is downloaded in button press
        int i =r.nextInt()%4;
        downloadFile(imageUrl+i+".jpg");

        }

        Bitmap bmImg;
        void downloadFile(String fileUrl){
        URL myFileUrl =null; 
        try {
        myFileUrl= new URL(fileUrl);
        } catch (MalformedURLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        }
        try {
        HttpURLConnection conn= (HttpURLConnection)myFileUrl.openConnection();
        conn.setDoInput(true);
        conn.connect();
        int length = conn.getContentLength();
        int[] bitmapData =new int[length];
        byte[] bitmapData2 =new byte[length];
        InputStream is = conn.getInputStream();

        bmImg = BitmapFactory.decodeStream(is);
        imView.setImageBitmap(bmImg);
        } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        }





};
};
}

1 个答案:

答案 0 :(得分:1)

您的代码存在一些问题:

  • 您正尝试从UI线程执行网络操作(从远程服务器下载文件)。 网络操作必须从另一个线程执行。否则 - 抛出异常。

从另一个线程启动代码的方法之一是:

new Thread(new Runnable() {

        @Override
        public void run() {
            downloadFile(imageUrl+i+".jpg");
        }
    }).start();

更好的方法是使用AsyncTask或IntentService(也在单独的线程上执行代码)

  • 第二件事 - 你不能只用输入流的大小创建int数组:如果图像太大,它可能会失败。尝试将下载分解为固定大小的段(例如每段2058字节),例如:

    private HttpURLConnection conn;
    private InputStream stream;
    private FileOutputStream out;
    
    private double fileSize;
    private double downloaded;
    
    
    public void downloadFile(String fileURL, String fileName) {
    try {
    
        conn = (HttpURLConnection) new URL(fileURL).openConnection();
        fileSize = conn.getContentLength();
        File file = new File(fileName);
    
        out = new FileOutputStream(file);
        conn.connect();
    
        stream = conn.getInputStream();
    
        while (status == DOWNLOADING) {
            byte buffer[];
    
            if (fileSize - downloaded > MAX_BUFFER_SIZE) {
                buffer = new byte[MAX_BUFFER_SIZE];
            } else {
                buffer = new byte[(int) (fileSize - downloaded)];
            }
            int read = stream.read(buffer);
    
            if (read == -1) {
    
                out.close();
                if (conn != null) {
                    conn.disconnect();
                }
    
                break;
            }
    
            out.write(buffer, 0, read);
            downloaded += read;
        }
    
    } catch (Exception e) {
        Log.e("downloadFile():", e.getMessage());
        if (conn != null) {
            conn.disconnect();
        }
    }
    
    }