Saturday, September 26, 2015

PHP simple web service demo to store JSON Object into database | PHP web service example | PHP GET POST REST Web service example

Hello Friends,

Below is a simple php code to store JSON object into MySQL database from android client-








1)saveJSONObject.php

<?php

//take the values from client as json

$json = file_get_contents('php://input');

//open database connection

$con = mysql_connect('localhost','root','Manish') or die('Cannot connect to the DB');

mysql_select_db('a4298774_mydb',$con);

//take json values into data variable

$data = json_decode($json);

//get the json values from client in name and number variable

//$name = '".$data->{'name'}."';

//$number= '".$data->{'number'}."' ;



//('".$obj->{'UserName'}."', '".$obj->{'FullName'}."')");

//make a sql query to store data

$sql="INSERT INTO `a4298774_mydb`.`callhistory`(srnumber, name,number)VALUES (NULL,'".$data->{'name'}."', '".$data->{'number'}."')";

$qur=mysql_query($sql);



//check the database response it is true or false

if($qur){

$json=array("status"=>1,"message"=>"done");

}

else{

$json=array("status"=>0,"message"=>"error");

}

//close the database connection

mysql_close($con);

//set header

header('Content-type: application/json');

//print the result as json object

echo json_encode($json);

?>














2)MainActivity.java
package com.androidhub4you.savecontacts;



import java.io.BufferedReader;

import java.io.InputStream;

import java.io.InputStreamReader;



import org.apache.http.HttpEntity;

import org.apache.http.HttpResponse;

import org.apache.http.client.HttpClient;

import org.apache.http.client.methods.HttpPost;

import org.apache.http.entity.ByteArrayEntity;

import org.apache.http.impl.client.DefaultHttpClient;

import org.apache.http.params.BasicHttpParams;

import org.apache.http.params.HttpConnectionParams;

import org.apache.http.params.HttpParams;

import org.json.JSONArray;

import org.json.JSONObject;



import android.app.Activity;

import android.app.ProgressDialog;

import android.os.AsyncTask;

import android.os.Bundle;

import android.util.Log;

import android.view.View;

import android.view.View.OnClickListener;

import android.widget.Toast;



public class MainActivity extends Activity {



@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);


findViewById(R.id.submit).setOnClickListener(new OnClickListener() {


@Override

public void onClick(View v) {

// TODO Auto-generated method stub


new saveContactData().execute();

}

});


}



public class saveContactData extends AsyncTask<String, Void, String> {



ProgressDialog pd = null;



@Override

protected void onPreExecute() {

pd = ProgressDialog.show(MainActivity.this, "Please wait",

"Loading please wait..", true);

pd.setCancelable(true);



}



@Override

protected String doInBackground(String... params) {

saveContacts();


return null;

}



@Override

protected void onPostExecute(String result) {

pd.dismiss();




}



}


public void saveContacts() {

try {

JSONObject json1 = new JSONObject();

json1.put("name", "ravi");

json1.put("number", "123456798");


/* JSONObject json2 = new JSONObject();

json2.put("name", "sumit");

json2.put("number", "123456798");


JSONArray json=new JSONArray();

json.put(json1);

json.put(json2);*/


HttpParams httpParams = new BasicHttpParams();

HttpConnectionParams.setConnectionTimeout(httpParams,50000);

HttpConnectionParams.setSoTimeout(httpParams, 5000);

HttpClient client = new DefaultHttpClient(httpParams);



String url = "http://androidhub4you.com/saveJSONObject.php";



HttpPost request = new HttpPost(url);

request.setEntity(new ByteArrayEntity(json1.toString().getBytes(

"UTF8")));

request.setHeader("Accept", "application/json");

request.addHeader("Content-Type", "application/json");

HttpResponse response = client.execute(request);

HttpEntity entity = response.getEntity();

// If the response does not enclose an entity, there is no need

if (entity != null) {

InputStream instream = entity.getContent();



Log.v("<<server response>>", converResponseToString(instream));


}

} catch (Throwable t) {


}

}

//Method to change the inputstream into string



public String converResponseToString(InputStream InputStream)

{

String mResult="";

StringBuilder mStringBuilder;

try

{

BufferedReader reader = new BufferedReader(new InputStreamReader(InputStream,"UTF-8"),8);

mStringBuilder = new StringBuilder();

mStringBuilder.append(reader.readLine() + "\n");

String line="0";

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

{

mStringBuilder.append(line + "\n");

}

InputStream.close();

mResult=mStringBuilder.toString();

return mResult;

}catch(Exception e){

return mResult;

}

}



}



3)activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"

xmlns:tools="http://schemas.android.com/tools"

android:layout_width="match_parent"

android:layout_height="match_parent"

tools:context="com.androidhub4you.savecontacts.MainActivity" >



<Button

android:id="@+id/submit"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="submit" />



</RelativeLayout>


4)Manifest.xml

<?xml version="1.0" encoding="utf-8"?>

<manifest xmlns:android="http://schemas.android.com/apk/res/android"

package="com.androidhub4you.savecontacts"

android:versionCode="1"

android:versionName="1.0" >




<uses-sdk

android:minSdkVersion="8"

android:targetSdkVersion="21" />

<uses-permission android:name="android.permission.INTERNET" />

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />


<application

android:allowBackup="true"

android:icon="@drawable/ic_launcher"

android:label="@string/app_name"

android:theme="@android:style/Theme.Black" >

<activity

android:name=".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>


Read More:http://www.androidhub4you.com/2015/09/write-php-web-service-to-store-json.html
 
Write comments for more query!

Thanks,
Manish



1 comment:

  1. I need tutorials on phonegap and what is the basic usage in android?

    ReplyDelete