Submitting Android Form Data Via POST Method

This tutorial walks you through the creation of the form application which allows your users to supply feedback to you using http POST request.
The authors are assuming the reader has some basic knowledge of Android app development and have all tools installed such as Eclipse, Android SDK and etc. If you haven’t already, be sure to read the “Android App Developemnt For Absolute Beginners

Step 1: Creating Android Project

Create a new project by going to File -> New Android Project. Fill all the details and name your project as ‘formpost‘.
Once your project is created, create a new Android XML Linear Layout File ‘form.xml‘ under res -> layout folder.
For more information about Android XML Linear Layout, please read the “Android Linear Layout For Absolute Beginner“.

Step 2: Designing The Form

First of all, you need to think about what kind of data you want to collect from your users. The form may consists of any number of fields (such as text field, checkbox and etc). Consider the type of data you want to collect and provide the appropriate fields for your users.
But for this tutorial, we will only have a text field to collect the data and a button to trigger the send data activity.
Example of how our application will look like:
android form post
layout/form.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >
    
    <TextView 
        android:text="Message"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
    />
    
    <EditText
        android:id="@+id/msgTextField"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:hint="Your Message"
    />
    
    <Button
        android:text="Send"
        android:id="@+id/sendButton"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:onClick="send"
    />

</LinearLayout>
There are 2 key elements here: EditText and Button. The EditText field acts as a form field for users’ feedback and the Button used to triggers send() function.

Step 3: Implement Button Click Handler

In the button control, you specified the onClick as send, so now you need to implement a function called “send” within the MainActivity class.
package com.example.formpost;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;

public class MainActivity extends Activity {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.form);
	}
	    
	//When the send button is clicked
    public void send(View v)
    {

    }
    
}

Step 4: Reading The Input From EditText Field

Now that your form is designed and the click handler have been implemented, next you need to retrieve the form data from the EditText Field.
package com.example.formpost;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

public class MainActivity extends Activity {
	
	//create variables for storing message & button objects
	EditText msgTextField;
	Button sendButton;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.form);
	        
	        //make message text field object
	        msgTextField = (EditText) findViewById(R.id.msgTextField);
	        //make button object
	        sendButton = (Button) findViewById(R.id.sendButton);
	    }
	    
	//When the send button is clicked
    public void send(View v)
    {
    	
    }
}

Step 5: Submit The Form Via POST Method

You’ve got all form data, you are ready to send it to server using POST request:
package com.example.formpost;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends Activity {
	
	EditText msgTextField;
	Button sendButton;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		 setContentView(R.layout.form);
	        
	        //make message text field object
	        msgTextField = (EditText) findViewById(R.id.msgTextField);
	        //make button object
	        sendButton = (Button) findViewById(R.id.sendButton);
	    }
	    
	    public void send(View v)
	    {
	    	//get message from message box
	    	String  msg = msgTextField.getText().toString();
	    	
	    	//check whether the msg empty or not
	    	if(msg.length()>0) {
	    		HttpClient httpclient = new DefaultHttpClient();
	    		HttpPost httppost = new HttpPost("http://www.yourdomain.com/serverside-script.php");
	    		
	    		try {
	    			List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
	    		       nameValuePairs.add(new BasicNameValuePair("id", "01"));
	    		       nameValuePairs.add(new BasicNameValuePair("message", msg));
	    		       httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
	    		   	   httpclient.execute(httppost);
	    				msgTextField.setText(""); //reset the message text field
	    				Toast.makeText(getBaseContext(),"Sent",Toast.LENGTH_SHORT).show();
	    		} catch (ClientProtocolException e) {
	    			e.printStackTrace();
	    		} catch (IOException e) {
	    			e.printStackTrace();
	    		}
	    	} else {
	    		//display message if text field is empty
	    		Toast.makeText(getBaseContext(),"All fields are required",Toast.LENGTH_SHORT).show();
	    	}
	    }
	    
	}

Step 6: Required permissions

To access the Internet your application requires the android.permission.INTERNET permission. Let’s open up ‘AndroidManifest.xml’ file and add the following code:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.formpost"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="17" />
    <uses-permission android:name="android.permission.INTERNET" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.example.formpost.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>

Step 7: Server Side Code

Lastly, we write a simple PHP code to get the data from the POST request. Example:
<?php
// get the "message" variable from the post request
// this is the data coming from the Android app
$message=$_POST["message"]; 
// specify the file where we will save the contents of the variable message
$filename="submitted-msg.html";
// write (append) the data to the file
file_put_contents($filename,$message." From Peter",FILE_APPEND);
// load the contents of the file to a variable
$androidmessages=file_get_contents($filename);
// display the contents of the variable (which has the contents of the file)
echo $androidmessages;
?>
Launch your Android app on your emulator and send a message. Then open up your browser, navigate to http://www.yourdomain.com/submitted-msg.html and you should see your message there. :)

Conclusion

In this tutorial, you learned how to create a feedback form and submit the form’s data to server-side within Android Application. We hope you enjoyed the tutorial and look forward to your feedback!

Comments

Popular posts from this blog

HOW TO REGISTER FOR SAFETOKEN

How To Get Help In MMM Nigeria - Mavrodi Mondial Moneybox