title: Android Download Image from URL
body: <p>Im trying to create a app that will download an image from the url and then save it but it doesn't work, I get both "ERROR"-toasts displayed. I am not very good with html commands in Java but yeah</p>
  
  <pre><code>public class MainActivity extends Activity {
  
  @Override
  protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
  
  
      Button button= (Button) findViewById(R.id.button1);
      button.setOnClickListener(new View.OnClickListener() {
  
          public void onClick(View v) {
              final EditText inputurl = new EditText(MainActivity.this);
              String urlcode = inputurl.getText().toString();
              boolean success = (new File("/sdcard/backgroundchanger")).mkdir();
              if (!success) {
                  Log.w("directory not created", "directory not created");
                  Toast.makeText(getApplicationContext(), "ERROR!!", Toast.LENGTH_SHORT).show();
              }
  
              try {
                  URL url = new URL(urlcode);
                  HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                  connection.setDoInput(true);
                  connection.connect();
                  InputStream input = connection.getInputStream();
                  Bitmap myBitmap = BitmapFactory.decodeStream(input);
  
                  String data1 = String.valueOf(String.format("/sdcard/%d.jpg", System.currentTimeMillis()));
  
                  FileOutputStream stream = new FileOutputStream(data1);
  
                  ByteArrayOutputStream outstream = new ByteArrayOutputStream();
                  myBitmap.compress(Bitmap.CompressFormat.JPEG, 85, outstream);
                  byte[] byteArray = outstream.toByteArray();
  
                  stream.write(byteArray);
                  stream.close();
  
                  Toast.makeText(getApplicationContext(), "Downloading Completed", Toast.LENGTH_SHORT).show();
              } catch (Exception e) {
                  e.printStackTrace();
                  Toast.makeText(getApplicationContext(), "ERROR!!!", Toast.LENGTH_SHORT).show();
              }
          }
      });
  
      };
  </code></pre>