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.

Thursday, December 26, 2013

Simple Fragments with Action Bar Example in Android 2.2, android:minSdkVersion="8",

Download(File->Download)

import it in eclipse if it having issues then follow the steps:

Setup the Android Support Libraries in your development project 
Support Library Setup
1. In eclipse File->Import>Existing Projects into workspace
Select a root directory->
C:\Program Files\Android\android-sdk\extras\android\support\v7\appcompat

2. add compatible library to your project.
Right click on your project ->Properties->Android->Library->add
select the V7 lib which you have imported in step 1.

3. Build and run.





Android Push Notifications using Google Cloud Messaging (GCM), PHP and MySQL

Download Code(download zip, file->download)

You can go through the official documentation if you want to know more about GCM.

1. How to enable  the GCM Service

1.1. Goto Google APIs Console page and create a new project.
1.2. Create a new Project.
1.3. After creating project you can see the Project Number in the following image. Note down the      project id which will be used as SENDER ID in android project. 


1.4. After that, Click on APIs & auth and turn on Google Cloude Messaging for android  .
1.5. After that, Click on Credencials from left pannel.
1.6. You can see the 
OAuth and Public API access.
1.7. Click on  CREATE NEW CLIENT ID 
choose a option Client ID for web application, Click ok.
1.8 After, Click  C REATE NEW KEY
Choose a option Key for browser applications,Click ok.



1.9 API key-This API key will be used when sending requests to GCM server.

2. Creating android project.
Download Code

File->Dowload or press CTRL+S

2.1  import this downloaded source code in eclipse.
2.2. open CommonUtilities.java, and give the parameters, 
SERVER_URL="your php file link";
SENDER_ID="This is your Project Number check it in above image1";
2.3 Debug the app.
2.4 During registration we are posting three parameters, regId, name, email.
regId is the id generated by GCM Server.
2.5 You can check the regId in logcat.

3. PHP code.


<?php

/**
 * The following function will send a GCM notification using curl.
 *
 * @param $apiKey [string] The Browser API key string for your GCM account
 * @param $registrationIdsArray [array] An array of registration ids to send this notification to
 * @param $messageData [array] An named array of data to send as the notification payload
 */

function sendNotification( $apiKey, $registrationIdsArray, $messageData )
{
$headers = array("Content-Type:" . "application/json", "Authorization:" . "key=" . $apiKey);
$data = array(
'data' => $messageData,
'registration_ids' => $registrationIdsArray
);

$ch = curl_init();

curl_setopt( $ch, CURLOPT_HTTPHEADER, $headers );
curl_setopt( $ch, CURLOPT_URL, "https://android.googleapis.com/gcm/send" );
curl_setopt( $ch, CURLOPT_SSL_VERIFYHOST, 0 );
curl_setopt( $ch, CURLOPT_SSL_VERIFYPEER, 0 );
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
curl_setopt( $ch, CURLOPT_POSTFIELDS, json_encode($data) );

$response = curl_exec($ch);
curl_close($ch);

return $response;
}
// Message to send
$message = "the test message";
$tickerText = "ticker text message";
$contentTitle = "content title";
$contentText = "content body";

$registrationId = 'DEVICE_ID';
$apiKey = "YOUR_BROWSER_API_KEY";

$response = sendNotification(
$apiKey,
array($registrationId),
array('message' => $message, 'tickerText' => $tickerText, 'contentTitle' => $contentTitle, "contentText" => $contentText) );

echo $response;
?>