Android Tutorial: How To Post Data From An Android App To a Website

1,707 views

You will konw what I’ll do next on ADASitemap!

http://webhole.net/2011/11/15/android-tutorial-how-to-post-data-from-an-android-app-to-a-website/

The Android API has a set of functions that allows you to use HTTP requests, POST, GET etc. In this tutorial we will make an app that will allow you to update the contents of a file in a server using POST requests.

Server Side Code

Our server side code will be very simple and it will be written in PHP. The code will get data from a post request, update a file with the data and load this file to display it in a browser.

Make a file with the following contents and upload them to your server. Know the web address of this file, we will give it to our Android app so that it knows where to POST the data.

<?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="androidmessages.html";
// write (append) the data to the file
file_put_contents($filename,$message."<br />",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;
?>

App Side Code

On the app side our interface will be nothing more than a text box and a button. The button is linked the the send() function in our activity, the function send() will be executed when the user pushed the button.

layout/main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
    <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"
        />
    <Button
        android:text="Send"
        android:id="@+id/sendButton"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:onClick="send"
        /> 

</LinearLayout>

We only need one activity, the send() function will be doing all the magic. The steps in the send function are:

  • get the contents from the text box and store them in a variable
  • make an http post request to your php script
  • clear the text box

HelloWorldActivity.java

package com.yoursite.helloworld;

import java.io.IOException;
import org.apache.http.client.ClientProtocolException;

import java.util.ArrayList;
import java.util.List;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;

import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.message.BasicNameValuePair;

// import everything you need
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 HelloWorldActivity extends Activity {

    Button sendButton;

    EditText msgTextField;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        // load the layout
        setContentView(R.layout.main);        

        // make message text field object
        msgTextField = (EditText) findViewById(R.id.msgTextField);
        // make send button object
        sendButton = (Button) findViewById(R.id.sendButton);

    }

    // this is the function that gets called when you click the button
    public void send(View v)
    {
        // get the message from the message text box
        String msg = msgTextField.getText().toString();  

        // make sure the fields are not empty
        if (msg.length()>0)
        {
	  	    HttpClient httpclient = new DefaultHttpClient();
	   	    HttpPost httppost = new HttpPost("http://yourwebsite.com/yourPhpScript.php");
	   	 try {
	   	   List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
	       nameValuePairs.add(new BasicNameValuePair("id", "12345"));
	       nameValuePairs.add(new BasicNameValuePair("message", msg));
	       httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
	   	   httpclient.execute(httppost);
	   	   msgTextField.setText(""); // clear text box
	     } catch (ClientProtocolException e) {
	         // TODO Auto-generated catch block
	     } catch (IOException e) {
	         // TODO Auto-generated catch block
	     }

        }
        else
        {
        	// display message if text fields are empty
            Toast.makeText(getBaseContext(),"All field are required",Toast.LENGTH_SHORT).show();
        }

    }
}

and this is the manifest file.

manifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="com.yoursite.helloworld"
      android:versionCode="1"
      android:versionName="1.0">
    <uses-sdk android:minSdkVersion="8" />

    <application android:icon="@drawable/icon" android:label="@string/app_name">
        <activity android:name=".HelloWorldActivity"
                  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>

How To Test The App

Open the app and send a message. The open http://yourwebsite.com/youtPhpScript.php and you should see the message you sent. Send another message, refresh the website to see the new message.

转载本站文章请注明,转载自:阿达基站路测的天空[http://blog.signalsitemap.com]

本文链接:Android Tutorial: How To Post Data From An Android App To a Website | 阿达基站路测的天空

This entry was posted in Android and tagged . Bookmark the permalink.

Comments are closed.