Example of Android Application and Database Interaction

Some people I know have brought up questions of how to send data to and from a server with an Android app. Since then, I have created a quick example of how from pulling some code from couple of other Android projects that I have been working on. Unfortunately, my development server want to crash on me, so I did not fully test the code. I am throwing this up so people can have an example to work from.

The idea of this simple code is to have the user input their first and last name, hit a button, and have a new screen start that will show their name and a list of any other names that is already in the database.

I will assume that you have the know how to create a project in your IDE of choice or have a project already going, so I’m not going to show those steps.

 

Here we go:

Step 1: Create First Layout

In the main activity layout, I used the fallowing code:

<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:id=”@+id/textView1″

android:layout_width=”wrap_content”

android:layout_height=”wrap_content”

android:text=”@string/FirstName”

android:textAppearance=”?android:attr/textAppearanceMedium” />

<EditText

android:id=”@+id/etFirstName”

android:layout_width=”wrap_content”

android:layout_height=”wrap_content”

android:hint=”First Name”

android:ems=”10″ />

<TextView

android:id=”@+id/textView2″

android:layout_width=”wrap_content”

android:layout_height=”wrap_content”

android:text=”@string/LastName”

android:textAppearance=”?android:attr/textAppearanceMedium” />

<EditText

android:id=”@+id/etLastName”

android:layout_width=”wrap_content”

android:layout_height=”wrap_content”

android:hint=”Last Name”

android:ems=”10″ />

<Button

android:id=”@+id/bAddPerson”

android:layout_width=”wrap_content”

android:layout_height=”wrap_content”

android:text=”@string/Add” />

</LinearLayout>

 

The code will produce a layout that looks like the image below.

 Layout

Step 2: Code for the main activity java file.

For this, I used:

public class MainActivity extends Activity implements OnClickListener {

private EditText firstName, lastName;

private List<NameValuePair> data;

private List<String> aList;

private JSONParser jparser;

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

data = new ArrayList<NameValuePair>(); //Need a list to send to the JSONParser

aList = new ArrayList<String>();

jparser = new JSONParser();

//Grab the fields from the layout

firstName = (EditText) findViewById(R.id.etFirstName);

lastName = (EditText) findViewById(R.id.etLastName);

//Get the button from the layout

Button addPerson = (Button) findViewById(R.id.bAddPerson);

//When a person clicks the button, this will call the the OnClick function

addPerson.setOnClickListener(this);

}

@Override

public void onClick(View v) {

//If the EditText are empty, this will tell the user to fill something in

if (firstName.getText().toString().length() <= 0 || lastName.getText().toString().length() <= 0 ) {

Toast toast = Toast.makeText(this, “Please fill in the Edit Text.”, Toast.LENGTH_LONG);

toast.show();

}

else {

//Add the names to the data list

data.add(new BasicNameValuePair(“firstName”, firstName.getText().toString()));

data.add(new BasicNameValuePair(“lastName”, lastName.getText().toString()));

//Send the data to the JSON parser.

//The parser will send the data to a server, than the server will save the names to //a database using PHP.

//The PHP code will send back a list of names that are on the server already.

aList = jparser.sendDataToServer(data);

//Create an intent and attach the data that I got from the server to it.

Intent intent = new Intent(“android.intent.action.STUFFADDED”);

intent.putStringArrayListExtra(“List”, (ArrayList<String>)aList);

startActivity(intent);

}

}

}

 

Step 3 We have to create the JSON parser:

Create a new file named JSONParser.java and throw this code in it.

public class JSONParser {

private String serverURL = “http://192.168.2.104/Test/test.php”;

private HttpClient client;

private HttpPost post;

private JSONArray jArray;

private InputStream in;

JSONParser () {

post = new HttpPost(serverURL);

client = new DefaultHttpClient();

jArray = null;

}

 

public List<String> sendDataToServer(List<NameValuePair> data) {

new BasicResponseHandler();

HttpResponse response = null;

try {

post.setEntity(new UrlEncodedFormEntity(data)); //sets up the URL info

response = client.execute(post);//make the connection and sends the data

HttpEntity entity = response.getEntity(); //reads any response that was sent back

in = entity.getContent(); //gets the info from the server

}catch (ClientProtocolException e1) {

e1.printStackTrace();

}catch (IOException e1) {

e1.printStackTrace();

}

List<String> listToReturn = new ArrayList<String>();

try {

//This will read what was sent back from the server

//and append each line into a String Builder

BufferedReader reader = new BufferedReader(new InputStreamReader(in, “iso- 8859-1”), 8);

//Set up the variables

StringBuilder sb = new StringBuilder();

String line = null;

//read through each line of the data from the server

while ((line = reader.readLine()) != null) {

sb.append(line + “\n”);

}

in.close();

//this will setup a jArray

jArray = new JSONArray(sb.toString());

}catch(Exception e) {

Log.e(“log_tag”, “Error converting result “+e.toString());

}

//And this will put the data into a nice array to send back to the main activity.

for (int i = 0; i < jArray.length(); i++) {

try {

listToReturn.add(jArray.getString(i));

}catch (JSONException e) {

e.printStackTrace();

}

}

return listToReturn;

}

}

 

Note: There maybe a better way to do this but this has worked for me in the past. If you know of a better JSON parser for Android applications that will send data to and from a server, give me a heads up.

 

Step 4 Displaying any data:

Just create a java file named StuffAdded. I used the fallowing code.

public class StuffAdded extends Activity{

 

private TextView textView; //This will setup the text view

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

//grab the textview from the layout

textView = (TextView) findViewById(R.id.tvStuffToShow);

stuffThatIsInTheDatabase();

}

public void stuffThatIsInTheDatabase () {

Intent intent = getIntent();

List<String> aList = intent.getStringArrayListExtra(“List”);

for (int i=0; i<aList.size(); i++){

textView.append(aList.get(i).toString() + “\n\n”);

}

}

And code for the layout.

<?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:id=”@+id/textView1″

android:layout_width=”wrap_content”

android:layout_height=”wrap_content”

android:text=”@string/Stuff”

android:textAppearance=”?android:attr/textAppearanceMedium” />

<TextView

android:id=”@+id/tvStuffToShow”

android:layout_width=”match_parent”

android:layout_height=”wrap_content”

android:layout_weight=”1.03″

android:text=”” />

</LinearLayout>

 

Note: Don’t forget to add the information to your AndroidManifest.xml file.

I hope this helps anyone that needs an example of this. If you need an example of the PHP on the server side of things, give me a heads up and I will do what I can.


2 Responses to Example of Android Application and Database Interaction

  1. hey hi, i am developing an android application for some restaurant which takes input from user such as name,number and email id and i want to send this data which would be stored in sqlite db to server please kindly help me with this i have literally searched google but could not get anything plssssss help me.