download image on android using http request in android
<p>I have used a tutorial and arrived at this result which works in an emulator, but it ceases to work on a real Android device.</p>

<p>The code is given here and all other Android permissions required are set; internet and write to external device are set.</p>

<pre><code>import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import org.apache.http.util.ByteArrayBuffer;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.widget.ImageView;
import android.widget.TextView;

public class main extends Activity {

    private final String PATH = "/mnt/sdcard/Pictures/";
    TextView tv;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        tv = (TextView)findViewById(R.id.textView1);
        DownloadFromUrl(PATH + "dwnldimg.png");
        ImageView iv = (ImageView) findViewById(R.id.imageView1);
        Bitmap bmp = BitmapFactory.decodeFile(PATH  + "dwnldimg.png");
        iv.setImageBitmap(bmp);
    }
    public void DownloadFromUrl(String fileName) {
            try {
                    URL url = new URL("http://192.168.1.4/evilempire.jpg"); //you can write here any link
                    File file = new File(fileName);
                     long startTime = System.currentTimeMillis();
                    tv.setText("Starting download......from " + url);
                    HttpURLConnection conn = (HttpURLConnection)url.openConnection();;
                    conn.setDoInput(true);
                    conn.connect();
                    InputStream is = conn.getInputStream();
                    BufferedInputStream bis = new BufferedInputStream(is);
                    /*
                     * Read bytes to the Buffer until there is nothing more to read(-1).
                     */
                    ByteArrayBuffer baf = new ByteArrayBuffer(50);
                    int current = 0;
                    while ((current = bis.read()) != -1) {
                            baf.append((byte) current);
                    }

                    FileOutputStream fos = new FileOutputStream(file);
                    fos.write(baf.toByteArray());
                    fos.close();
                    tv.setText("Download Completed in" + ((System.currentTimeMillis() - startTime) / 1000) + " sec");
            } catch (IOException e) {
                 tv.setText("Error: " + e);
            }
    }

}
</code></pre>
