Introduction
You are creating an Android app and want to read data from a MySQL database and send data. We will create a Web Service in PHP, read from the MySQL database, and let the Android connect with the Web Service and send data, and the Web Service will save it and another Web Service will read data from MySQL and send it to the Android app.
Using the Code
First, we have to create the Web service to read data from the MySQL database.
<
pre
>
/* require the user as the parameter */
<
pre
>
//http://localhost:8080/sample1/webservice1.php?user=1
if(isset($_GET['user']) && intval($_GET['user'])) {
/* soak in the passed variable or set our own */
$number_of_posts = isset($_GET['num']) ? intval($_GET['num']) : 10; //10 is the default
$format = strtolower($_GET['format']) == 'json' ? 'json' : 'xml'; //xml is the default
$user_id = intval($_GET['user']); //no default
/* connect to the db */
$link = mysql_connect('localhost','root','123456') or die('Cannot connect to the DB');
mysql_select_db('TEST',$link) or die('Cannot select the DB');
/* grab the posts from the db */
//$query = "SELECT post_title, guid FROM wp_posts WHERE post_author =
// $user_id AND post_status = 'publish' ORDER BY ID DESC LIMIT $number_of_posts";
$query = "SELECT * FROM `test`.`users`;";
$result = mysql_query($query,$link) or die('Errant query: '.$query);
/* create one master array of the records */
$posts = array();
if(mysql_num_rows($result)) {
while($post = mysql_fetch_assoc($result)) {
$posts[] = array('post'=>$post);
/* output in necessary format */
if($format == 'json') {
header('Content-type: application/json');
echo json_encode(array('posts'=>$posts));
else {
header('Content-type: text/xml');
echo '';
foreach($posts as $index => $post) {
if(is_array($post)) {
foreach($post as $key => $value) {
echo '
<
'
,$key,
'
>
';
if(is_array($value)) {
foreach($value as $tag => $val) {
echo '
<
'
,$tag,
'
>
',htmlentities($val),'
<
/
'
,$tag,
'
>
';
echo '
<
/
'
,$key,
'
>
';
echo '';
/* disconnect from the db */
@mysql_close($link);
Here is the code for the Android activity to read from the Web Service and parse the JSON object:
public
void
clickbutton(View v) {
try
{
HttpParams httpParams =
new
BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParams,
TIMEOUT_MILLISEC);
HttpConnectionParams.setSoTimeout(httpParams, TIMEOUT_MILLISEC);
HttpParams p =
new
BasicHttpParams();
p.setParameter(
"
user"
,
"
1"
);
HttpClient httpclient =
new
DefaultHttpClient(p);
String
url =
"
http://10.0.2.2:8080/sample1/"
+
"
webservice1.php?user=1&format=json"
;
HttpPost httppost =
new
HttpPost(url);
try
{
Log.i(getClass().getSimpleName(),
"
send task - start"
);
List<NameValuePair> nameValuePairs =
new
ArrayList<NameValuePair>(
nameValuePairs.
add
(
new
BasicNameValuePair(
"
user"
,
"
1"
));
httppost.setEntity(
new
UrlEncodedFormEntity(nameValuePairs));
ResponseHandler<String> responseHandler =
new
BasicResponseHandler();
String
responseBody = httpclient.execute(httppost,
responseHandler);
JSONObject json =
new
JSONObject(responseBody);
JSONArray jArray = json.getJSONArray(
"
posts"
);
ArrayList<HashMap<String, String>> mylist =
new
ArrayList<HashMap<String, String>>();
for
(
int
i =
0
; i < jArray.length(); i++) {
HashMap<String, String> map =
new
HashMap<String, String>();
JSONObject e = jArray.getJSONObject(i);
String
s = e.getString(
"
post"
);
JSONObject jObject =
new
JSONObject(s);
map.put(
"
idusers"
, jObject.getString(
"
idusers"
));
map.put(
"
UserName"
, jObject.getString(
"
UserName"
));
map.put(
"
FullName"
, jObject.getString(
"
FullName"
));
mylist.
add
(map);
Toast.makeText(
this
, responseBody, Toast.LENGTH_LONG).show();
}
catch
(ClientProtocolException e) {
e.printStackTrace();
}
catch
(IOException e) {
e.printStackTrace();
}
catch
(Throwable t) {
Toast.makeText(
this
,
"
Request failed: "
+ t.toString(),
Toast.LENGTH_LONG).show();
Here is the PHP code to send data to the Web Service and save it:
$json
= file_get_contents(
'
php://input'
);
$obj
= json_decode($json);
$con
= mysql_connect(
'
localhost'
,
'
root'
,
'
123456'
)
or
die(
'
Cannot connect to the DB'
);
mysql_select_db(
'
TEST'
,$con);
mysql_query(
"
INSERT INTO `test`.`users` (UserName, FullName)
VALUES ('"
.$obj->{
'
UserName'
}.
"
', '"
.$obj->{
'
FullName'
}.
"
')"
);
mysql_close($con);
$posts
= array(1);
header(
'
Content-type: application/json'
);
echo
json_encode(array(
'
posts'
=>$posts));
Android activity to send data to the Web Service as a JSON object to save in the MySQL database:
public
void
clickbuttonRecieve(View v) {
try
{
JSONObject json =
new
JSONObject();
json.put(
"
UserName"
,
"
test2"
);
json.put(
"
FullName"
,
"
1234567"
);
HttpParams httpParams =
new
BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParams,
TIMEOUT_MILLISEC);
HttpConnectionParams.setSoTimeout(httpParams, TIMEOUT_MILLISEC);
HttpClient client =
new
DefaultHttpClient(httpParams);
String
url =
"
http://10.0.2.2:8080/sample1/webservice2.php"
;
HttpPost request =
new
HttpPost(url);
request.setEntity(
new
ByteArrayEntity(json.toString().getBytes(
"
UTF8"
)));
request.setHeader(
"
json"
, json.toString());
HttpResponse response = client.execute(request);
HttpEntity entity = response.getEntity();
if
(entity !=
null
) {
InputStream instream = entity.getContent();
String
result = RestClient.convertStreamToString(instream);
Log.i(
"
Read from server"
, result);
Toast.makeText(
this
, result,
Toast.LENGTH_LONG).show();
}
catch
(Throwable t) {
Toast.makeText(
this
,
"
Request failed: "
+ t.toString(),
Toast.LENGTH_LONG).show();
Points of Interest
To connect to your emulator, you can use this link:
http://10.0.2.2:8080/
.
To read the JSON object in the Web Service, you can use this line of code:
$json
= file_get_contents(
'
php://input'
);
$obj
= json_decode($json);
Senior Software Engineer / System Architect
Experience: +11 years
http://www.linkedin.com/in/hamdyghanem
hamdy.ghanem@gmail.com
Graduated from Munifia University, faculty of science, Math and computer science department May 1999
Experience Brief
11+ years of experience in software development field.
In these years I used most of common software developing tools of Microsoft, And with many nationalities and cultures.
I worked in large scale projects of client side, desktop, web application and mobile phones that involved integration with other system using different technologies I've been working using .NET technologies for 8 years.
Currently, I work as a senior software engineer for CogWin as well as a testing/QA consultant. We develop large scale applications for a high profile customer.
Beside developing and managing, I worked in the last year as a professional tester from developer point of view and applying software evaluation metrics on source code and reverse engineering.
I worked as a team leader more than four years
My experience involved using agile methodology using team foundation server
from 1year I am very interested in Android development
I have a published some applications in the Android Market
Strong skills troubleshooting and debugging production systems are essential
My key skills
High performance, hard worker and new technologies enthusiast
Specialties
C#,VB.net, C++, Java ,php, Python , OOP SQL Server (2000, 2005, 2008),Oracle, Mysql , Java , SSRS ,Source safe, Ontology, Android, ASP.NET ,Ajax, • WPF,WCF, Entity Framework, LINQ, CFG , state machine , Ontology, Decision Tree , Cloud Systems, CRM ,JavaScript, XML, UML, Crystal report , LINQ, Silverlight
I have developed an app that reads data from mysql thru php. As my db is very large, it takes lot of time to load and my app crashes.
How can json be of use in this case?
Sign In
·
View Thread
How to receive data using webservice WordPress to Android application
Member 12739107
13-Sep-16 18:53
Member 12739107
13-Sep-16 18:53
Hello friend.. I would like to know that how to send and receive the bulk data from android app to webserver or vice versa..as JSON format.. Is it possible through array..concepts .. Thank you..
Sign In
·
View Thread
Hello sir i make one app for restaurant... i use php web service using parsing.. but i need to how can i update and delete.. .. plz provide me code for it.. you are well experience man.. that's why i'm asking you..
Hercules Thakkar
Sign In
·
View Thread
HttpClient is too heavy for low-end android device. It is better to use HttpURLConnection directly for getting json data from server.
Sign In
·
View Thread
explanation is not good and note easy to understand if we don't have experience with php,local server and mysql
Sign In
·
View Thread
can you give me a db
i failed try your code.... thanks for advance and actually it's good tutorial
Sign In
·
View Thread
Error converting result java.lang.nullpointerexception, error parsing data org.json.JSONEception.
Cyber12
26-Feb-14 22:06
Cyber12
26-Feb-14 22:06
HERE IS MY LOG CAT ERROR
02-26 10:23:58.570: E/Buffer Error(1065): Error converting result java.lang.NullPointerException: lock == null
02-26 10:23:58.670: E/JSON Parser(1065): Error parsing data org.json.JSONException: End of input at character 0 of
02-26 10:23:59.000: E/AndroidRuntime(1065): FATAL EXCEPTION: AsyncTask #5
02-26 10:23:59.000: E/AndroidRuntime(1065): java.lang.RuntimeException: An error occured while executing doInBackground()
02-26 10:23:59.000: E/AndroidRuntime(1065): at android.os.AsyncTask$3.done(AsyncTask.java:299)
02-26 10:23:59.000: E/AndroidRuntime(1065): at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:352)
02-26 10:23:59.000: E/AndroidRuntime(1065): at java.util.concurrent.FutureTask.setException(FutureTask.java:219)
02-26 10:23:59.000: E/AndroidRuntime(1065): at java.util.concurrent.FutureTask.run(FutureTask.java:239)
02-26 10:23:59.000: E/AndroidRuntime(1065): at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
02-26 10:23:59.000: E/AndroidRuntime(1065): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
02-26 10:23:59.000: E/AndroidRuntime(1065): at
Sign In
·
View Thread
how to recive data using webservice.net to andorid expandable listview
beniv
11-Nov-13 5:19
beniv
11-Nov-13 5:19
How can i get the data from Web service .net and display it in an expandable List view The Web service get the data from Microsoft SQL Server.
i'm using web service.net to read the data from Microsoft Sql Server this is my web service my webservice
this is my webservice
<WebMethod()> _
<ScriptMethod(ResponseFormat:=ResponseFormat.Json)> _
Public Function Getdata_json_paparametera() As
String
Dim conn As SqlConnection = New SqlConnection(
"
myconstring"
)
conn.Open()
Dim cmd As SqlCommand = New SqlCommand(
"
Select Id_Agjenda,Titulli,Useri,data_takimit,Kategoria,data_e_publikimit,e_kryer,rezultati from tblagjenda ;"
, conn)
Dim ds As DataSet = New DataSet()
Dim da As SqlDataAdapter = New SqlDataAdapter(cmd)
da.Fill(ds)
conn.Close()
Dim MArray()() As
String
= New
String
(ds.Tables(
0
).Rows.Count)() {}
Dim i As Integer =
0
For Each rs As DataRow In ds.Tables(
0
).Rows
MArray(i) = New
String
() {rs(
"
Id_Agjenda"
).ToString(), rs(
"
Useri"
).ToString(), rs(
"
Titulli"
).ToString(), rs(
"
data_takimit"
).ToString(), rs(
"
rezultati"
).ToString()}
i = i +
1
Dim js As JavaScriptSerializer = New JavaScriptSerializer()
Dim sJSON As
String
= js.Serialize(MArray)
Return sJSON
End Function
and my activity
@Override
public
void
onActivityCreated(Bundle savedInstanceState){
super
.onActivityCreated(savedInstanceState);
Thread cmdthread1=new Thread(){
@Override
public
void
run(){
SoapObject requst=new SoapObject(NAMESPACEEXP,METHOD_NAME_JSONEXP);
System.out.println(
"
try"
+requst);
SoapSerializationEnvelope envelope=new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.dotNet=true;
envelope.setOutputSoapObject(requst);
HttpTransportSE androidHttptransport=new HttpTransportSE(URL_jsEXP);
try
{
System.out.println(
"
try"
+requst);
androidHttptransport.call(Soap_Action_JSONEXP,envelope);
final
SoapPrimitive response=(SoapPrimitive)envelope.getResponse();
final
String
str=response.toString();
System.out.println(
"
response"
+response);
getActivity().runOnUiThread(
new
Runnable() {
@Override
public
void
run(){
String
strtest=response.toString();
strtest=strtest.replaceAll(
"
]"
,
"
"
).replaceAll(
"
\\["
,
"
"
);
TextView result;
result=(TextView)getActivity().findViewById(R.id.txtexpandla);
result.setText(
"
fdfasf "
+strtest);
ListView listanota=(ListView)getActivity().findViewById(R.id.listViewcmd2);
try
{
System.out.println(
"
string"
+str);
JSONArray array1=(JSONArray)
new
JSONTokener(str).nextValue();
String
[]stringsarraylista=new
String
[array1.length()];
for
(
int
i=0;i<array1.length();i++){
stringsarraylista[i]=array1.getString(i);
ArrayAdapter<String> adaptercmd;
adaptercmd=new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1,stringsarraylista);
listanota.setAdapter(adaptercmd);
}
catch
(JSONException e){
e.printStackTrace();
}
catch
(Exception e){
e.printStackTrace();
System.out.println(
"
error "
);
cmdthread1.start();
Sign In
·
View Thread
Re: how to recive data using webservice.net to andorid expandable listview
creatorb
7-Apr-14 5:12
creatorb
7-Apr-14 5:12
you can get on here http://moinur-rahman.blogspot.com/2012/02/connection-between-android-app-and.html .... i hope it will help you.......
Sign In
·
View Thread
JSONException: Value Errant of type java.lang.String cannot be converted to JSONObject
Member 10166469
31-Jul-13 0:15
Member 10166469
31-Jul-13 0:15
Hello,
When I run the above piece of codes in emulator and press the 'SEND' button, the following error occurs
"JSONException: Value Errant of type java.lang.String cannot be converted to JSONObject."
Any help is appreciated.
modified 31-Jul-13 5:32am.
Sign In
·
View Thread
Re: JSONException: Value Errant of type java.lang.String cannot be converted to JSONObject
ravi koradiya
2-Apr-14 0:34
ravi koradiya
2-Apr-14 0:34
if in php file there is an error in selection or insertion process,
than it will return that error instead of JSON data,
thus JSONObject will be null due to no JSON data.
check db query.
Sign In
·
View Thread
HttpHostConnectException - connection to localhost refused.
Member 10141858
10-Jul-13 1:48
Member 10141858
10-Jul-13 1:48
Thank you very much for your tutorial, it's really helpful!
Btw, I got some problems and hope you could give me guidance.
1) When I pressed on "Receive" Button, a toast text pop up and said that request failed - HttpHostConnectException - connection to localhost refused.
2) The "Send" Button has no response.
Thanks.
Sign In
·
View Thread
07-10 13:23:07.000: E/AndroidRuntime(394): java.lang.IllegalStateException: Could not find a method receiceclickbutton(View) in the activity class com.example.note.MainActivity for onClick handler on view class android.widget.Button with id 'b2'
Sign In
·
View Thread
there is an error in receiveclickbutton. on the click of receive button error is mehod not found...illegal stateexception...plz suggest me what is the reason of error.....
Sign In
·
View Thread
hai..Everybody
I need your help Iam fresher to develop android applications...i need how to write web service and to display the data in my screen....pls send me code thank you in advance
mymailid:rajivvaddi1213@gmail.com
Sign In
·
View Thread
check the port or the firewall !!
see this link
http://stackoverflow.com/questions/14641835/sockettimeoutexception-android
[
^
]
Sign In
·
View Thread
Toast.makeText(
this
,
"
this shows"
, Toast.LENGTH_LONG).show();
responseBody = httpclient.execute(httppost, responseHandler);
Toast.makeText(
this
,
"
this not"
, Toast.LENGTH_LONG).show();
can you help me?
Sign In
·
View Thread
Web01
2.8:2023-10-29:1