Thursday, October 2, 2014

Android upload file to PHP server with parameters using progress bar


new ProcessFileUploadTask(new File(Environment.getExternalStorageDirectory().toString()+"/yourfile_name/";


//asynch task to upload file with parameters
public class ProcessFileUploadTask extends AsyncTask<Void, Integer, Void>  implements DialogInterface.OnCancelListener{

  private ProgressDialog progressDialog;
  private File file;
  String res="";

   public ProcessFileUploadTask(File file) {
    this.file = file;
  }

   @Override
// can use UI thread here
protected void onPreExecute() {
super.onPreExecute();
try{
progressDialog = new ProgressDialog(PostDataActivity.this);
progressDialog.setMessage("Uploading... Please wait!");
progressDialog.setIndeterminate(false);
progressDialog.setMax(file_size);
progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
progressDialog.setCancelable(false);
       progressDialog.setCanceledOnTouchOutside(false);
       progressDialog.show();
}
catch(Exception e){
Log.e("Exception:",e.toString());
}
}

protected void onPostExecute(Void v) {  
   
progressDialog.dismiss();
Toast toast=Toast.makeText(getApplicationContext(), "Uploaded Successfully.", Toast.LENGTH_LONG);

}

   @Override
  protected Void doInBackground(Void... v) {
    HttpURLConnection.setFollowRedirects(false);
    HttpURLConnection conn = null;
     
   
    try {
    //posting parameters with url
    String finalUrl = Uri.parse("www.example.com/demo.php")
               .buildUpon()
               .appendQueryParameter("name", "firzan")
               .build().toString();
      conn = (HttpURLConnection) new URL(finalUrl).openConnection();
      conn.setConnectTimeout(10*1000);
     
      conn.setRequestMethod("POST");
      String boundary = "---------------------------boundary";
      String tail = "\r\n--" + boundary + "--\r\n";
      conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
      conn.setDoOutput(true);

      String metadataPart = "--" + boundary + "\r\n"
          + "Content-Disposition: form-data; name=\"metadata\"\r\n\r\n"
          + "" + "\r\n";

      String fileHeader1 = "--" + boundary + "\r\n"
          + "Content-Disposition: form-data; name=\"uploadedfile\"; filename=\""
          + serverFileName + "\"\r\n"
          + "Content-Type: application/octet-stream\r\n"
          + "Content-Transfer-Encoding: binary\r\n";

       long fileLength = file.length() + tail.length();
      String fileHeader2 = "Content-length: " + fileLength + "\r\n";
      String fileHeader = fileHeader1 + fileHeader2 + "\r\n";
      String stringData = metadataPart + fileHeader;

      long requestLength = stringData.length() + fileLength;
      conn.setRequestProperty("Content-length", "" + requestLength);
      conn.setFixedLengthStreamingMode((int) requestLength);
      conn.connect();

      DataOutputStream out = new DataOutputStream(conn.getOutputStream());
      out.writeBytes(stringData);
      out.flush();

      int progress = 0;
      int bytesRead = 0;
      byte buf[] = new byte[10*1024];
      BufferedInputStream bufInput = new BufferedInputStream(new FileInputStream(file));
      while ((bytesRead = bufInput.read(buf)) != -1) {
     
      // write output
        out.write(buf, 0, bytesRead);
        out.flush();
        progress += bytesRead;
        // update progress bar
        publishProgress(progress);
      }
     
       // Write closing boundary and close stream
      out.writeBytes(tail);
      out.flush();
      out.close();

       // Get server response
      BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
      String line = "";
      StringBuilder builder = new StringBuilder();
      while((line = reader.readLine()) != null) {
        builder.append(line);
      }
      serverResponseCode = conn.getResponseCode();
    serverResponseMessage = conn.getResponseMessage();
    ServerResponce=builder.toString();
    Log.e("ser res",ServerResponce.toString());
    }
    catch (Exception e) {
    Log.e("Exception",e.toString());
    progressDialog.dismiss();
    exceptionText=e.toString();
   
    } finally {  
      if (conn != null) conn.disconnect();
      //finish();
    }
   
    return null;
  }
   @Override
  protected void onProgressUpdate(Integer... progress) {
    progressDialog.setProgress((int) (progress[0]));
  }
   @Override
  public void onCancel(DialogInterface dialog) {
   super.onCancelled();
    cancel(true);
    dialog.dismiss();
    finish();
 
  }
 
  }



PHP Script

<?php

        $name=$_REQUEST['name'];
$target_path_videos = 'videos/';
$target_path_videos = $target_path_videos .'_'. basename( $_FILES['uploadedfile']['name']);

if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path_videos))
{
  echo '1';
}
else
{
echo "Error";
}

 
?>

Android Sliding Menu using Navigation Drawer/ Hamburger

Download the Demo Project From Following link and import it in your eclipse ide.

Download

1. Find the String variables for List View items and icon names in strings.xml.(change as per your needs.)
2. Android introduced a newer UI element called DrawerLayout for Navigation Drawer. Open your layout file (activity_main.xml) for main activity and type the following code.
Here FrameLayout is used to replace the main content using Fragments and it should be always the first child of the layout for z-index purpose.
3.list_item_bg_normal.xml  and list_item_bg_pressed.xml represents list item state when normal and pressed.
4. Created another xml file to combine both the drawable states under res ⇒ drawable named list_selector.xml
5.counter_bg.xml  used  for rounde corner background for the counter value.
6. As listview has the custom layout, we need another layout file which defines the each list row. So create a layout file under res ⇒ layout named drawer_list_item.xml. This is a relative layout which places the icon, title and counter relative to one another.
7. In NavDrawerItem.java, isCounterVisible defines the visibility of the counter value.
8. in MainActivity.java, invalidateOptionMenu() is called in onDrawerOpened() and onDrawerClosed() to hide and show the action bar icons on navigation drawer opened and closed.