title: Mobile got hanged while uploading images from gallery in android
body: <p>I want to upload images from gallery to make it as  my profile image.But my mobile got hanged for few seconds and after that, it comes to normal mode and uploads the image with some delay.Can anyone please help me to avoid hanging and upload the image quickly.</p>
  
  <p>Here is my code.</p>
  
  <pre><code>public void res() {
  
  
          System.out.println("res method for jscript");
          webView.loadUrl("javascript:callFromActivity(\"" + msgToSend + "\")");
      }
  
      public void showCustomAlert() {
          // TODO Auto-generated method stub
  
          Context context = getApplicationContext();
          // Create layout inflator object to inflate toast.xml file
          LayoutInflater inflater = getLayoutInflater();
  
          // Call toast.xml file for toast layout
          View toastRoot = inflater.inflate(R.layout.toast, null);
  
          Toast toast = new Toast(context);
  
          // Set layout to toast
          toast.setView(toastRoot);
          toast.setGravity(Gravity.CENTER_HORIZONTAL | Gravity.CENTER_VERTICAL,
                  0, 0);
          toast.setDuration(Toast.LENGTH_LONG);
          toast.show();
  
      }
  
      protected void onActivityResult(int requestCode, int resultCode, Intent data) {
          super.onActivityResult(requestCode, resultCode, data);
      if(data!=null)
      {
          if (requestCode == CAM_REQUREST) {
               Bundle extras = data.getExtras();
  
               if (extras != null) {
              bitmap_profile_image = extras.getParcelable("data");            
              bitmap_profile_image = (Bitmap) data.getExtras().get("data");
              imagepath = ImageWrite(bitmap_profile_image);
          }
          }
  
          else if (requestCode == RESULT_LOAD_IMAGE &amp;&amp; resultCode == RESULT_OK
                  &amp;&amp; null != data) {
              Uri selectedImage = data.getData();
              String[] filePathColumn = { MediaStore.Images.Media.DATA };
  
              Cursor cursor = getContentResolver().query(selectedImage,
                      filePathColumn, null, null, null);
              cursor.moveToFirst();
  
              int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
              String picturePath = cursor.getString(columnIndex);
              cursor.close();
              imagepath = ImageWrite(BitmapFactory.decodeFile(picturePath));
  
          } else {
  
          }
      }
  
              Imageuploading();
  
      }
  
      public String ImageWrite(Bitmap bitmap1) {
  
          String extStorageDirectory = Environment.getExternalStorageDirectory()
                  .toString();
          OutputStream outStream = null;
          File file = new File(extStorageDirectory, "selectimage.PNG");
  
          try {
  
              outStream = new FileOutputStream(file);
              bitmap1.compress(Bitmap.CompressFormat.PNG, 100, outStream);`enter code here`
              outStream.flush();
              outStream.close();
  
          } catch (FileNotFoundException e) {
              e.printStackTrace();
  
          } catch (IOException e) {
              e.printStackTrace();
  
          }
          String imageInSD = "/sdcard/selectimage.PNG";
  
          return imageInSD;
  
      }
  
      protected void Imageuploading() {
          // TODO Auto-generated method stub
  
          try {
  
              Log.e("imageuploading", "dfdf");
  
              HttpURLConnection connection = null;
              DataOutputStream outputStream = null;
              DataInputStream inputStream = null;
  
              String pathToOurFile = (String) imagepath;
  
              // String urlServer =
              // "http://demo.cogzideltemplates.com/client/snapchat-clone/index.php/user/image_upload";
              String urlServer = Liveurl+"mobile/image_upload";
              String lineEnd = "\r\n";
              String twoHyphens = "--";
              String boundary = "*****";
  
              int bytesRead, bytesAvailable, bufferSize;
              byte[] buffer;
              int maxBufferSize = 1 * 1024 * 1024;
  
              FileInputStream fileInputStream = new FileInputStream(new File(
                      pathToOurFile));
  
              URL url = new URL(urlServer);
              connection = (HttpURLConnection) url.openConnection();
  
              // Allow Inputs &amp; Outputs
              connection.setDoInput(true);
              connection.setDoOutput(true);
              connection.setUseCaches(false);
  
              // Enable POST method
              connection.setRequestMethod("POST");
  
              connection.setRequestProperty("Connection", "Keep-Alive");
              connection.setRequestProperty("Content-Type",
                      "multipart/form-data;boundary=" + boundary);
  
              outputStream = new DataOutputStream(connection.getOutputStream());
              outputStream.writeBytes(twoHyphens + boundary + lineEnd);
              outputStream
                      .writeBytes("Content-Disposition: form-data; name=\"uploadedfile\";filename=\""
                              + pathToOurFile + "\"" + lineEnd);
              outputStream.writeBytes(lineEnd);
  
              bytesAvailable = fileInputStream.available();
              bufferSize = Math.min(bytesAvailable, maxBufferSize);
              buffer = new byte[bufferSize];
  
              // Read file
              bytesRead = fileInputStream.read(buffer, 0, bufferSize);
  
              while (bytesRead &gt; 0) {
                  outputStream.write(buffer, 0, bufferSize);
                  bytesAvailable = fileInputStream.available();
                  bufferSize = Math.min(bytesAvailable, maxBufferSize);
                  bytesRead = fileInputStream.read(buffer, 0, bufferSize);
              }
  
              outputStream.writeBytes(lineEnd);
              outputStream.writeBytes(twoHyphens + boundary + twoHyphens
                      + lineEnd);
  
              // Responses from the server (code and message)
              int serverResponseCode = connection.getResponseCode();
              String serverResponseMessage = connection.getResponseMessage();
  
              // Toast.makeText(getApplicationContext(), serverResponseMessage,
              // Toast.LENGTH_LONG).show();
              System.out.println("image" + serverResponseMessage);
  
              fileInputStream.close();
              outputStream.flush();
              outputStream.close();
  
              DataInputStream inputStream1 = null;
              inputStream1 = new DataInputStream(connection.getInputStream());
              String str = "";
              String Str1_imageurl = "";
  
              while ((str = inputStream1.readLine()) != null) {
                  Log.e("Debug", "Server Response " + str);
  
                  Str1_imageurl = str;
                  Log.e("Debug", "Server Response String imageurl" + str);
              }
              inputStream1.close();
              System.out.println("image url inputstream1 " + Str1_imageurl);
              // Toast.makeText(getApplicationContext(), Str1_imageurl,
              // Toast.LENGTH_LONG).show();
  
              msgToSend = Str1_imageurl.trim();
  
              System.out.println("message to send "+msgToSend);
  
          } catch (Exception e) {
  
              e.printStackTrace();
  
          }
  
          res();
  
      }
  
      public void clearApplicationData() {
          File cache = getCacheDir();
          File appDir = new File(cache.getParent());
  
          System.out.println("application dir"+appDir);
          if (appDir.exists()) {
              String[] children = appDir.list();
              for (String s : children) {
                  if (!s.equals("lib")) {
                      deleteDir(new File(appDir, s));
                      Log.i("TAG", "**************** File /data/data/APP_PACKAGE/" + s + " DELETED *******************");
                      Intent i=new Intent(Profile_settings.this,splash.class);
                      //i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                     // clearApplicationData();
                      startActivity(i);
                  }
              }
          }
      }
  
      public static boolean deleteDir(File dir) {
          if (dir != null &amp;&amp; dir.isDirectory()) {
              String[] children = dir.list();
              for (int i = 0; i &lt; children.length; i++) {
                  boolean success = deleteDir(new File(dir, children[i]));
                  if (!success) {
                      return false;
                  }
              }
          }
  
          return dir.delete();
      }
      private void loadSavedPreferences() {    
          //User has successfully logged in, save this information
          // We need an Editor object to make preference changes.
  
          SharedPreferences settings = getSharedPreferences(index.PREFS_NAME, 0);
          SharedPreferences.Editor editor = settings.edit();
          editor.clear();`enter code here`
          editor.commit();
  
          }
  </code></pre>
  
  <p>Thanks in advance.</p>