简体   繁体   中英

Downloading and displaying an image

I want to download an image from server, save it on the SD card, and show it. I wrote that code, but it doesn't work - there are no bugs, but I see only a black screen instead of the image.

public class Main extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    MyTask mt = new MyTask();
    mt.execute();

    Intent intent = new Intent();  
    intent.setAction(android.content.Intent.ACTION_VIEW);  
    File file = new File("/sdcard/askeroid/logos/1_mobile.png");  
    intent.setDataAndType(Uri.fromFile(file), "image/*");  
    startActivity(intent); 
}  

}
class MyTask extends AsyncTask {

@Override
protected Void doInBackground(Void... params) {
    try{
        URL url = new URL("http://ed.sadko.mobi/logo/logo_1mobile.png");
        URLConnection connection = url.openConnection();
        connection.connect();

        InputStream input = new BufferedInputStream(url.openStream());
        OutputStream output = new FileOutputStream("/sdcard/askeroid/logos/1_mobile.png");

        output.flush();
        output.close();
        input.close();

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

}

You don't wait for the end of the download before moving to next activity.

I suggest you use AsyncTask - download the image using in doInBackground and start next activity in onPostExecute .

Something like:

AsyncTask<Void, Void, Void> task = new AsyncTask<Void, Void, Void>() {
    @Override protected Long doInBackground(Void ... urls) {
        // download the image
    }

    @Override protected void onPostExecute(Void result) {
        // start new activity...
    }
};
task.execute();

Also, please note that the path to the SD card may vary between different devices. Take a look here to see how to access it properly.

+1 for The answer to use AsyncTask, it makes threading on android super easy. Another problem is that you open the InputStream and the OutputStream but you never actually read anything from the input nor do you write anything to the output, so the file on your sdcard is going to be empty.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM