Tutorial / Android Development

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!

  • Stumble it!
  • Share
  • neelem

    i follow all the steps but it shows error while running.when i debug it i found that its not accepting httpclient.execute(httppost); method.only this is showing error.any help pls reply

    • onlymobilepro

      Hi neelem,
      could you disclose more details of your problem?

    • Jack Wilder

      Make sure you have Internet permission setup in the manifest

  • shyaam

    Yes I tried it Does give me an exception on main thread .
    Please come up with a fix for this

    • ncommentposter.com

      It’s because you can not perform networking operation on the main thread. Run your code in AsyncTask

  • Ozzy

    hi i got layout xml for contact but thats all so could you create .java file for this pls?

    code is

    &lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;
    
    &lt;RelativeLayout xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;
    
        xmlns:tools=&quot;http://schemas.android.com/tools&quot;
    
        android:layout_width=&quot;match_parent&quot;
    
        android:layout_height=&quot;match_parent&quot;
    
        android:background=&quot;@drawable/bg&quot;
    
        android:paddingBottom=&quot;@dimen/activity_vertical_margin&quot;
    
        android:paddingLeft=&quot;@dimen/activity_horizontal_margin&quot;
    
        android:paddingRight=&quot;@dimen/activity_horizontal_margin&quot;
    
        android:paddingTop=&quot;@dimen/activity_vertical_margin&quot;
    
        tools:context=&quot;.MainActivity&quot; &gt;
    
           &lt;ImageButton
    
               android:id=&quot;@+id/facebook&quot;
    
               style=&quot;@style/AppTheme&quot;
    
               android:layout_width=&quot;wrap_content&quot;
    
               android:layout_height=&quot;wrap_content&quot;
    
               android:layout_alignParentTop=&quot;true&quot;
    
               android:layout_marginRight=&quot;20dp&quot;
    
               android:layout_toLeftOf=&quot;@+id/anasayfa&quot;
    
               android:src=&quot;@drawable/facebook&quot; /&gt;
    
           &lt;ImageButton
    
               android:id=&quot;@+id/twitter&quot;
    
               android:layout_width=&quot;wrap_content&quot;
    
               android:layout_height=&quot;wrap_content&quot;
    
               android:layout_alignTop=&quot;@+id/facebook&quot;
    
               android:layout_marginLeft=&quot;25dp&quot;
    
               android:layout_toRightOf=&quot;@+id/anasayfa&quot;
    
               android:src=&quot;@drawable/twitter&quot; /&gt;
    
           &lt;ImageButton
    
               android:id=&quot;@+id/anasayfa&quot;
    
               android:layout_width=&quot;wrap_content&quot;
    
               android:layout_height=&quot;wrap_content&quot;
    
               android:layout_alignBottom=&quot;@+id/facebook&quot;
    
               android:layout_centerHorizontal=&quot;true&quot;
    
               android:src=&quot;@drawable/anasayfa&quot; /&gt;
    
           &lt;TextView
    
               android:id=&quot;@+id/textView1&quot;
    
               android:layout_width=&quot;wrap_content&quot;
    
               android:layout_height=&quot;wrap_content&quot;
    
               android:layout_alignLeft=&quot;@+id/facebook&quot;
    
               android:layout_below=&quot;@+id/facebook&quot;
    
               android:layout_marginLeft=&quot;14dp&quot;
    
               android:layout_marginTop=&quot;66dp&quot;
    
               android:text=&quot;@string/adiniz&quot;
    
               android:textAppearance=&quot;?android:attr/textAppearanceSmall&quot; /&gt;
    
           &lt;TextView
    
               android:id=&quot;@+id/textView2&quot;
    
               android:layout_width=&quot;wrap_content&quot;
    
               android:layout_height=&quot;wrap_content&quot;
    
               android:layout_alignRight=&quot;@+id/textView1&quot;
    
               android:layout_below=&quot;@+id/editText1&quot;
    
               android:layout_marginTop=&quot;26dp&quot;
    
               android:text=&quot;@string/telefonunuz&quot;
    
               android:textAppearance=&quot;?android:attr/textAppearanceSmall&quot; /&gt;
    
           &lt;EditText
    
               android:id=&quot;@+id/editText1&quot;
    
               android:layout_width=&quot;wrap_content&quot;
    
               android:layout_height=&quot;wrap_content&quot;
    
               android:layout_alignBottom=&quot;@+id/textView1&quot;
    
               android:layout_toRightOf=&quot;@+id/facebook&quot;
    
               android:ems=&quot;10&quot;
    
               android:inputType=&quot;textPersonName&quot; &gt;
    
               &lt;requestFocus /&gt;
    
           &lt;/EditText&gt;
    
           &lt;EditText
    
               android:id=&quot;@+id/editText2&quot;
    
               android:layout_width=&quot;wrap_content&quot;
    
               android:layout_height=&quot;wrap_content&quot;
    
               android:layout_alignBaseline=&quot;@+id/textView2&quot;
    
               android:layout_alignBottom=&quot;@+id/textView2&quot;
    
               android:layout_alignLeft=&quot;@+id/editText1&quot;
    
               android:layout_alignRight=&quot;@+id/editText1&quot;
    
               android:ems=&quot;10&quot;
    
               android:inputType=&quot;phone&quot; /&gt;
    
           &lt;EditText
    
               android:id=&quot;@+id/editText3&quot;
    
               android:layout_width=&quot;wrap_content&quot;
    
               android:layout_height=&quot;wrap_content&quot;
    
               android:layout_alignBaseline=&quot;@+id/textView4&quot;
    
               android:layout_alignBottom=&quot;@+id/textView4&quot;
    
               android:layout_alignParentRight=&quot;true&quot;
    
               android:layout_toRightOf=&quot;@+id/facebook&quot;
    
               android:ems=&quot;10&quot;
    
               android:inputType=&quot;textEmailAddress&quot; /&gt;
    
           &lt;TextView
    
               android:id=&quot;@+id/textView4&quot;
    
               android:layout_width=&quot;wrap_content&quot;
    
               android:layout_height=&quot;wrap_content&quot;
    
               android:layout_alignLeft=&quot;@+id/textView2&quot;
    
               android:layout_below=&quot;@+id/editText2&quot;
    
               android:layout_marginTop=&quot;26dp&quot;
    
               android:text=&quot;@string/mailiniz&quot;
    
               android:textAppearance=&quot;?android:attr/textAppearanceSmall&quot; /&gt;
    
           &lt;TextView
    
               android:id=&quot;@+id/textView5&quot;
    
               android:layout_width=&quot;wrap_content&quot;
    
               android:layout_height=&quot;wrap_content&quot;
    
               android:layout_alignRight=&quot;@+id/textView2&quot;
    
               android:layout_below=&quot;@+id/editText3&quot;
    
               android:layout_marginTop=&quot;28dp&quot;
    
               android:text=&quot;@string/mesaj&quot;
    
               android:textAppearance=&quot;?android:attr/textAppearanceSmall&quot; /&gt;
    
           &lt;Button
    
               android:id=&quot;@+id/gonder&quot;
    
               android:layout_width=&quot;wrap_content&quot;
    
               android:layout_height=&quot;wrap_content&quot;
    
               android:layout_above=&quot;@+id/textView3&quot;
    
               android:layout_alignRight=&quot;@+id/twitter&quot;
    
               android:layout_marginBottom=&quot;19dp&quot;
    
               android:text=&quot;@string/gonder&quot; /&gt;
    
           &lt;EditText
    
               android:id=&quot;@+id/editText4&quot;
    
               android:layout_width=&quot;wrap_content&quot;
    
               android:layout_height=&quot;wrap_content&quot;
    
               android:layout_alignBaseline=&quot;@+id/textView5&quot;
    
               android:layout_alignBottom=&quot;@+id/textView5&quot;
    
               android:layout_alignLeft=&quot;@+id/editText3&quot;
    
               android:ems=&quot;10&quot;
    
               android:inputType=&quot;textMultiLine&quot; /&gt;
    
           &lt;TextView
    
               android:id=&quot;@+id/textView3&quot;
    
               android:layout_width=&quot;wrap_content&quot;
    
               android:layout_height=&quot;wrap_content&quot;
    
               android:layout_alignParentBottom=&quot;true&quot;
    
               android:layout_centerHorizontal=&quot;true&quot;
    
               android:text=&quot;@string/tasarim&quot;
    
               android:textAppearance=&quot;?android:attr/textAppearanceSmall&quot; /&gt;
    
    &lt;/RelativeLayout&gt;
    
    
  • Davide S

    ….Sorry….

    i’m new about Android…
    I’ve try to copy the code into eclipse but it can’t work.
    There’s an error on the 30 line “setContentView(R.layout.form);”

    R.java doesnt find “form”.
    Someone can help me?
    Someone can send me the complete project in eclipse format or share in this page?!
    tnx!

  • Tim Malche

    nice tutorial ….. working absolutely fine….. thanks