Connect Android device to MySQL

To make the connection between android device & MySQL, developer should have silent knowledge of class JSONObject because this class plays major role for making connection fruitful. Here is a detail about this class.

Here is the whole code. You can download php file and java file.

JSONObject

A modifiable set of name/value mappings. Names are unique, non-null strings. Values may be any mix of JSONObjectsJSONArrays, Strings, Booleans, Integers, Longs, Doubles orNULL. Values may not be nullNaNsinfinities, or of any type not listed here.

This class can coerce values to another type when requested.

  • When the requested type is a boolean, strings will be coerced using valueOf(String).
  • When the requested type is a double, other Number types will be coerced using doubleValue. Strings that can be coerced using valueOf(String) will be.
  • When the requested type is an int, other Number types will be coerced using intValue. Strings that can be coerced using valueOf(String) will be, and then cast to int.
  • When the requested type is a long, other Number types will be coerced using longValue. Strings that can be coerced using valueOf(String) will be, and then cast to long. This two-step conversion is lossy for very large values. For example, the string “9223372036854775806” yields the long 9223372036854775807.
  • When the requested type is a String, other non-null values will be coerced using valueOf(Object). Although null cannot be coerced, the sentinel value NULL is coerced to the string “null”.

For many people, the main reson for learning a scripting language like PHP is because of the interaction with databases it can offer. In this tutorial I will show you how to use PHP and the MySQL database to store information on the web and include it into your website. Before you read this tutorial you should have at least a basic knowledge of how to use PHP.

Now, coming to our tutorial, there should a table like Student(s_id,s_name) where s_id is primary key of table Student. Target is that we want to insert data from android to mysql. For making this we will use PHP in middle as shown below.

Android —> PHP—-> MySQL database(table: Student)

In php we will fetch data from android through following method,

‘”.$_REQUEST['keyword'].”‘

Here is a whole .java file code for android to insert data to database.

ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();

nameValuePairs.add(new BasicNameValuePair("s_name","Jack"));
try{     HttpClient httpclient = new DefaultHttpClient();
	//please note here that change url according to your application
	//if you are currently using android emulator, then you must use
 	//http://10.0.2.2/stu.php for connecting localhost of your pc.
     HttpPost httppost = new HttpPost("http://www.xyz.com/stu.php");
     httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
     HttpResponse response = httpclient.execute(httppost);
     HttpEntity entity = response.getEntity();
     is = entity.getContent();
     }catch(Exception e){
         Log.e("log_tag", "Error in http connection"+e.toString());
    }
//convert response to stringtry
{
      BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
       sb = new StringBuilder();
       sb.append(reader.readLine() + "\n");
       String line="0";
       while ((line = reader.readLine()) != null) {
                      sb.append(line + "\n");        }
        is.close();
        String result=sb.toString();
        }catch(Exception e){
              Log.e("log_tag", "Error converting result "+e.toString());
        }//paring datatry
{
      jArray = new JSONArray(result);
      deal_id=new int[jArray.length()+1];
      JSONObject json_data=null;
      for(int i=0;i<jArray.length();i++){
             json_data = jArray.getJSONObject(i);
                      }
      }      catch(JSONException e1){
    	       } catch (ParseException e1) {
			e1.printStackTrace();	}
    }

 

PHP script to insert data into MySQL table Student

<?phpmysql_connect("host","username","password");
mysql_select_db("db_name");
$sql=mysql_query("insert into Student (s_name)values('".$_REQUEST['s_name']."')");
$r=mysql_query($sql);
if(!$r)echo "Error in query: ".mysql_error();mysql_close();?>

Freelance Jobs

About these ads

About Android Guy

I'm android guy..... I love android very much...i can talk in android, i can walk in android...because android is smart operating system.
This entry was posted in Android PHP and tagged , , , , , , , , , , , , , , , , . Bookmark the permalink.

6 Responses to Connect Android device to MySQL

  1. shadowSRB says:

    Could you send me whole java file? I have a little trouble with this code.

  2. moktar says:

    when im trying to connect to the database ,i’m getting :
    Error in http connectionandroid.os.NetworkOnMainThreadException
    some help ?

    • hasan says:

      R u developing in honeycomb ? coz it happens when u try to access network calls in main UI thread thats a fatal error in honeycomb.
      Sol. start a separate thread and call network in that thread.

  3. Ishwari Shah says:

    I am trying to store input data from android to mysql using php,but data is not getting passed to php page from android,so please can you help me with good running code..I have tried using url by passing variable with it,but it’s not getting passed..Waitting for your help..
    Thanks in Advance!1

  4. shadowSRB says:

    this is my solutions.

    import java.io.InputStream;
    import java.util.ArrayList;
    import org.apache.http.HttpEntity;
    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.HttpPost;
    import org.apache.http.impl.client.DefaultHttpClient;
    import org.apache.http.message.BasicNameValuePair;
    import org.apache.http.util.EntityUtils;
    import android.app.Activity;
    import android.content.Context;
    import android.location.Location;
    import android.location.LocationListener;
    import android.location.LocationManager;
    import android.os.Bundle;
    import android.util.Log;
    import android.view.View;
    import android.view.View.OnClickListener;
    import android.widget.Button;
    import android.widget.Toast;

    public class main extends Activity {
    private static final long MINIMUM_DISTANCE_CHANGE_FOR_UPDATES = 1000; // in
    // Meters
    private static final long MINIMUM_TIME_BETWEEN_UPDATES = 15000; // in
    // Milliseconds

    Button retrieveLocationButton;
    LocationManager locationManager;

    double lat;
    double lon;

    @Override
    public void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,
    MINIMUM_TIME_BETWEEN_UPDATES, MINIMUM_DISTANCE_CHANGE_FOR_UPDATES,
    new MyLocationListener());

    retrieveLocationButton = (Button) findViewById(R.id.retrieve_location_button);
    retrieveLocationButton.setOnClickListener(new OnClickListener() {
    @Override
    public void onClick(View v) {
    showCurrentLocation();
    saveLocation();
    }
    });
    }

    protected void showCurrentLocation() {
    Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);

    if (location != null) {
    lat = location.getLatitude();
    lon = location.getLongitude();
    String message = String.format(
    “Trenutna lokacija \n Longituda: %1$s \n Latituda: %2$s”,
    lon, lat);
    Toast.makeText(main.this, message, Toast.LENGTH_LONG).show();
    } else {
    lon = 42.0000;
    lat = 21.0000;
    String message = String.format(
    “Podrazumevane vrednosti \n Longituda: %1$s \n Latituda: %2$s”,
    lon, lat);
    Toast.makeText(main.this, message, Toast.LENGTH_LONG).show();

    }
    }

    class MyLocationListener implements LocationListener {

    public void onLocationChanged(Location location) {
    String message = String.format(
    “Nova lokacija \n Longituda: %1$s \n Latituda: %2$s”,
    location.getLongitude(), location.getLatitude());
    Toast.makeText(main.this, message, Toast.LENGTH_LONG).show();
    showCurrentLocation();
    saveLocation();
    }

    public void onStatusChanged(String s, int i, Bundle b) {
    Toast.makeText(main.this, “Vaša lokacija je promenjena.”, Toast.LENGTH_LONG)
    .show();
    }

    public void onProviderDisabled(String s) {
    Toast.makeText(main.this,
    “Provider je onemogucen od strane korisnika. GPS je iskljucen.”, Toast.LENGTH_LONG)
    .show();
    }

    public void onProviderEnabled(String s) {
    Toast.makeText(main.this, “Provider je omogucen od strane korisnika. GPS je ukljucen.”,
    Toast.LENGTH_LONG).show();
    }

    }

    private void saveLocation() {
    ArrayList nameValuePairs = new ArrayList(3);

    nameValuePairs.add(new BasicNameValuePair(“lat”,String.valueOf(lat)));
    nameValuePairs.add(new BasicNameValuePair(“lon”,String.valueOf(lon)));
    nameValuePairs.add(new BasicNameValuePair(“ime”,”vrabac”));

    InputStream is = null;
    //http post
    try{
    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost(“http://mojsajt.rs/mysqlcon.php”);
    httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
    HttpResponse response = httpclient.execute(httppost);
    HttpEntity entity = response.getEntity();
    String str = EntityUtils.toString(entity);
    is = entity.getContent();
    Log.i(“postData”, response.getStatusLine().toString());
    }

    catch(Exception e)
    {
    Log.e(“log_tag”, “Error in http connection “+e.toString());
    }
    }

    }

  5. peter says:

    hi guys,
    i need php/ mysql source code for ‘add’ ,’delete’, ‘edit’ via android …….to develop pls help

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s