Tuesday, 24 April 2012
Android add data to remote database (MySql)
This is actually divided into two the Android part and the Php Part.
Note: Do not forget to include the INTERNET permission in the AndroidManifest.xml file
The Android Part
main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello" />
<LinearLayout
android:id="@+id/linearLayout1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:layout_margin="20dp">
<EditText
android:id="@+id/editFirstname"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="10dp" >
<requestFocus />
</EditText>
<EditText
android:id="@+id/editLastname"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="10dp" />
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button" />
</LinearLayout>
</LinearLayout>
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.akinware.gtugbase"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk android:minSdkVersion="8" />
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
<application
android:icon="@drawable/ic_launcher"
android:label="@string/app_name" >
<activity
android:label="@string/app_name"
android:name=".GtugBase" >
<intent-filter >
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Gtugbase.java
package com.akinware.gtugbase;
import java.util.ArrayList;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class GtugBase extends Activity {
/** Called when the activity is first created. */
Button btnAdd;
EditText txtFirstname,txtLastname;
String status,error;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
btnAdd = (Button)findViewById(R.id.button1);
txtFirstname = (EditText)findViewById(R.id.editFirstname);
txtLastname = (EditText)findViewById(R.id.editLastname);
/* ** Onclick of the add button ** */
btnAdd.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
/* Collect values from EditText */
String firstName = txtFirstname.getText().toString();
String lastName = txtFirstname.getText().toString();
/* Send Values to Method */
SendToPhpFile(firstName,lastName);
}
});
}
protected void SendToPhpFile(String firstName, String lastName) {
ArrayList<NameValuePair> pp = new ArrayList<NameValuePair>();
/* In case you are having many php functions, this helps you
to select the function you want to send parameters to.
For example here i will be sending values to the "add" function */
pp.add(new BasicNameValuePair("whichfunction", "AddUser"));
/* Add values to arraylist */
pp.add(new BasicNameValuePair("firstname", firstName));
pp.add(new BasicNameValuePair("lastname", lastName));
/* With the help of the HttpClient Class we send all parameter
to the php script. check ConnectBase.java for the location */
try{
status = "";
status = CustomHttpClient.executeHttpPost(ConnectBase.link, pp);
String res=status.toString();
res= res.replaceAll("\\s+","");
/* Depending on value you return if insert was successful */
if(res.equals("1")){
Toaster("Data successfully added.");
}else{
Toaster(status);
}
}catch(Exception e){
Toaster("Data successfully added: " + e.toString());
}
}
public void Toaster(String string){
Toast.makeText(this, string,Toast.LENGTH_LONG).show();
}
}
ConnectBase.java
package com.akinware.gtugbase;
/* The location of your php file */
public class ConnectBase {
public static String link = "http://10.0.2.2/gtugbase/gtug.php";
}
CustomHttpClient.java
package com.akinware.gtugbase;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URI;
import java.util.ArrayList;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.params.ConnManagerParams;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
public class CustomHttpClient {
/** The time it takes for our client to timeout */
public static final int HTTP_TIMEOUT = 2000 * 1000; // milliseconds
/** Single instance of our HttpClient */
private static HttpClient mHttpClient;
/**
* Get our single instance of our HttpClient object.
*
* @return an HttpClient object with connection parameters set
*/
private static HttpClient getHttpClient() {
if (mHttpClient == null) {
mHttpClient = new DefaultHttpClient();
final HttpParams params = mHttpClient.getParams();
HttpConnectionParams.setConnectionTimeout(params, HTTP_TIMEOUT);
HttpConnectionParams.setSoTimeout(params, HTTP_TIMEOUT);
ConnManagerParams.setTimeout(params, HTTP_TIMEOUT);
}
return mHttpClient;
}
/**
* Performs an HTTP Post request to the specified url with the
* specified parameters.
*
* @param url The web address to post the request to
* @param postParameters The parameters to send via the request
* @return The result of the request
* @throws Exception
*/
public static String executeHttpPost(String url, ArrayList<NameValuePair> postParameters) throws Exception {
BufferedReader in = null;
try {
HttpClient client = getHttpClient();
HttpPost request = new HttpPost(url);
UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(postParameters);
request.setEntity(formEntity);
HttpResponse response = client.execute(request);
in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
StringBuffer sb = new StringBuffer("");
String line = "";
String NL = System.getProperty("line.separator");
while ((line = in.readLine()) != null) {
sb.append(line + NL);
}
in.close();
String result = sb.toString();
return result;
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
/**
* Performs an HTTP GET request to the specified url.
*
* @param url The web address to post the request to
* @return The result of the request
* @throws Exception
*/
public static String executeHttpGet(String url) throws Exception {
BufferedReader in = null;
try {
HttpClient client = getHttpClient();
HttpGet request = new HttpGet();
request.setURI(new URI(url));
HttpResponse response = client.execute(request);
in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
StringBuffer sb = new StringBuffer("");
String line = "";
String NL = System.getProperty("line.separator");
while ((line = in.readLine()) != null) {
sb.append(line + NL);
}
in.close();
String result = sb.toString();
return result;
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
The Php Part
<?php
/* Database connection */
mysql_connect("localhost","root","");
mysql_select_db("gtbase");
/* Get the value in the whichfunction parameter
sent from the android application which will
determine the fucntion to call. */
$getFunctionToCall = $_POST['whichfunction'];
/* Depending on the value of the whichfunction
parameter switch to call different function */
switch ($getFunctionToCall){
case "AddUser":
echo AddUser($_POST['firstname'],$_POST['lastname']);
break;
}
/* Function to add user to the user table */
function AddUser($firstname,$lastname){
$sql = "insert into user(firstname,lastname) values('$firstname','$lastname')";
if(mysql_query($sql)){
return 1; // Return 1 for success;
}else{
return 2;// Return 2 for database error;
}
}
?>
Database Structure
CREATE TABLE `user` (
`id` bigint(20) NOT NULL auto_increment,
`firstname` varchar(225) NOT NULL,
`lastname` varchar(225) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
Subscribe to:
Posts (Atom)