Friday, April 4, 2014

Android - Uploading a File to a PHP Server

The following script allows you to upload a file from your Android application by sending the file to the PHP server, which can then save the file to the disk.

Prerequisite:

IOUtils is provided by the Apache Commons library. You can download the jar here. Add the jar file to your Android application's /lib folder and you'll be good to go.

private void uploadFile(String filePath, String fileName) {
InputStream inputStream;
try {
inputStream = new FileInputStream(new File(filePath));
byte[] data;
try {
data = IOUtils.toByteArray(inputStream);
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("http://api.example.com/ping.php");
InputStreamBody inputStreamBody = new InputStreamBody(new ByteArrayInputStream(data), fileName);
MultipartEntity multipartEntity = new MultipartEntity();
multipartEntity.addPart("file", inputStreamBody);
httpPost.setEntity(multipartEntity);
HttpResponse httpResponse = httpClient.execute(httpPost);
// Handle response back from script.
if(httpResponse != null) {
} else { // Error, no response.
}
} catch (IOException e) {
e.printStackTrace();
}
} catch (FileNotFoundException e1) {
e1.printStackTrace();
}
}


Edit the highlighted line to specify the location of the PHP script.
The server-side PHP script accepts the uploaded data and saves it to a file. It can look as follows:

<?php

$objFile = & $_FILES["file"];
$strPath = basename( $objFile["name"] );

if( move_uploaded_file( $objFile["tmp_name"], $strPath ) ) {
print "The file " . $strPath . " has been uploaded.";
} else {
print "There was an error uploading the file, please try again!";

}
>


Thursday, April 3, 2014

Android multiple post requests web services (GET,POST)

The code is very simple and straightforward, for post request with attachement, first of all you would have to add two jar files to your build path.
1. apache-mime4j-0.6.jar 
2.  httpmime-4.0.1.jar

Important 
This two jar add to your build path.

HTTP GET
try {
        HttpClient client = new DefaultHttpClient();  
        String getURL = "http://www.google.com";
        HttpGet get = new HttpGet(getURL);
        HttpResponse responseGet = client.execute(get);  
        HttpEntity resEntityGet = responseGet.getEntity();  
        if (resEntityGet != null) {  
                    //do something with the response
                    Log.i("GET RESPONSE",EntityUtils.toString(resEntityGet));
                }
} catch (Exception e) {
    e.printStackTrace();
}
HTTP POST


 try {
        HttpClient client = new DefaultHttpClient();  
        String postURL = "http://somepostaddress.com";
        HttpPost post = new HttpPost(postURL); 
            List<NameValuePair> params = new ArrayList<NameValuePair>();
            params.add(new BasicNameValuePair("user", "kris"));
            params.add(new BasicNameValuePair("pass", "xyz"));
            UrlEncodedFormEntity ent = new UrlEncodedFormEntity(params,HTTP.UTF_8);
            post.setEntity(ent);
            HttpResponse responsePOST = client.execute(post);  
            HttpEntity resEntity = responsePOST.getEntity();  
            if (resEntity != null) {    
                Log.i("RESPONSE",EntityUtils.toString(resEntity));
            }
    } catch (Exception e) {
        e.printStackTrace();
    }



HTTP POST with File attachment

File file = new File("path/to/your/file.txt");
try {
         HttpClient client = new DefaultHttpClient();  
         String postURL = "http://someposturl.com";
         HttpPost post = new HttpPost(postURL); 
     FileBody bin = new FileBody(file);
     MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);  
     reqEntity.addPart("myFile", bin);
     post.setEntity(reqEntity);  
     HttpResponse response = client.execute(post);  
     HttpEntity resEntity = response.getEntity();  
     if (resEntity != null) {    
               Log.i("RESPONSE",EntityUtils.toString(resEntity));
         }
} catch (Exception e) {
    e.printStackTrace();
}

please post your comments  

Wednesday, April 2, 2014

Android CursorLoader with Example

      A CursorLoader is normally used to interact with a ContentProvider asynchronously. It can query in the background against a ContentProvider so the UI thread can continuously interact with the user. This avoids the UI thread being un-responsive while querying ContentProvider. The CursorLoader will initiate the query in separate thread, retrieve the results from ContentProvider and reconnects to the Activity when it is finished.


How to use CursorLoader?

LoaderCallbacks<Cursor> interface is used to create a CursorLoader. This interface provides set of callback methods to initialize, run a CursorLoader.
The activity should implement this interface to use the CursorLoader.

Example:

Sample Project download

CursorLoader

public class MainActivity extends FragmentActivity implements
  LoaderManager.LoaderCallbacks<Cursor> {
    .
    .
}

To initialize a background query we have to use LoaderManager.initLoader() method. This will initiate the background tasks. To get LoaderManager in a FragmentActivity getSupportLoaderManager() is used.
Example:
getSupportLoaderManager().initLoader(1, null, this);

Once we initialize the query, onCreateLoader() method will be invoked by Android. In this method we can create our CursorLoader against the ContentProvider. We can provide Projections, Selection criteria, Sort order during the creation of CursorLoader.
Example:

@Override
public Loader<Cursor> onCreateLoader(int arg0, Bundle arg1) {
 Uri CONTENT_URI = ContactsContract.RawContacts.CONTENT_URI;
 return new CursorLoader(this, CONTENT_URI, null, null, null, null);
}

Once we are done with creation of CursorLoader, the ContentProvider URI specified in the CursorLoader object will be queried. All the projections, selections, sort order will be applied to query the ContentProvider (if specified any).
Once the background thread completes the query, onLoadFinished() method will be invoked.
onLoadFinished() is another callback method which will give us a Cursor with result data from the query. We can use this cursor to get the data and do some processing to display it to the user.

onLoaderReset() method is invoked when the cursor becomes stale/invalid. If the Cursor is being placed in a CursorAdapter, you should use the swapCursor(null) method to remove any references it has to the Loader's data.

Sample Application:

In this sample application we are using CursorLoader to query Contacts Content provider. To run this on emulator we are inserting a new contact from code and querying the same using CursorLoader. 
Note: To read contacts we need to have READ_CONTACTS permission. To write a new contact we need to haveWRITE_CONTACTS permission.

AndroidManifest.xml:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.cursorloaderexample"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="16" />

    <uses-permission android:name="android.permission.READ_CONTACTS" >
    </uses-permission>
    <uses-permission android:name="android.permission.WRITE_CONTACTS" >
    </uses-permission>

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.example.cursorloaderexample.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>


Layout xml file:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity" >

    <TextView
        android:id="@+id/res"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:layout_marginLeft="34dp"
        android:layout_marginTop="22dp" />

</RelativeLayout>


Activity class:

package com.example.cursorloaderexample;

import java.util.ArrayList;

import android.content.ContentProviderOperation;
import android.content.OperationApplicationException;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.RemoteException;
import android.provider.ContactsContract;
import android.provider.ContactsContract.CommonDataKinds.Phone;
import android.provider.ContactsContract.CommonDataKinds.StructuredName;
import android.provider.ContactsContract.Data;
import android.provider.ContactsContract.RawContacts;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.view.Menu;
import android.widget.TextView;

public class MainActivity extends FragmentActivity implements
  LoaderManager.LoaderCallbacks<Cursor> {
 TextView resTextView = null;

 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
  resTextView = (TextView) findViewById(R.id.res);
  ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();
  int rawContactInsertIndex = ops.size();
  ops.add(ContentProviderOperation.newInsert(RawContacts.CONTENT_URI)
    .withValue(RawContacts.ACCOUNT_TYPE, "Test")
    .withValue(RawContacts.ACCOUNT_NAME, "CTE").build());

  ops.add(ContentProviderOperation
    .newInsert(Data.CONTENT_URI)
    .withValueBackReference(Data.RAW_CONTACT_ID,
      rawContactInsertIndex)
    .withValue(Data.MIMETYPE, StructuredName.CONTENT_ITEM_TYPE)
    .withValue(StructuredName.DISPLAY_NAME, "test name")
    .withValue(Phone.NUMBER, 1234567890).build());
  try {
     //Use below statement to insert a new contact
     //getContentResolver().applyBatch(ContactsContract.AUTHORITY, ops);
  } catch (Exception e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
  }
  getSupportLoaderManager().initLoader(1, null, this);
 }

 @Override
 public boolean onCreateOptionsMenu(Menu menu) {
  // Inflate the menu; this adds items to the action bar if it is present.
  getMenuInflater().inflate(R.menu.activity_main, menu);
  return true;
 }

 @Override
 public Loader<Cursor> onCreateLoader(int arg0, Bundle arg1) {
  Uri CONTENT_URI = ContactsContract.RawContacts.CONTENT_URI;
  return new CursorLoader(this, CONTENT_URI, null, null, null, null);
 }

 @Override
 public void onLoadFinished(Loader<Cursor> arg0, Cursor cursor) {
  cursor.moveToFirst();
  StringBuilder res = new StringBuilder();
  while (!cursor.isAfterLast()) {
   res.append("\n" + cursor.getString(21) + "-" + cursor.getString(22));

   cursor.moveToNext();
  }
  resTextView.setText(res);

 }

 @Override
 public void onLoaderReset(Loader<Cursor> loader) {
  // If the Cursor is being placed in a CursorAdapter, you should use the
  // swapCursor(null) method to remove any references it has to the
  // Loader's data.
 }

 @Override
 protected void onDestroy() {
  // TODO Auto-generated method stub
  super.onDestroy();
 }

}