Wednesday, July 31, 2013

Android MySQL PHP & JSON tutorial

In this post I'm going to describe how we can read data from MySQL database and show them in a Android list view. You can download the complete Android project from here. To fetch data here I used a PHP script which encodes data into json format.
This project has three main parts.
1. MySQL database
2. PHP web service
3.Android web service client

1. MySQL database.
My database has only one table named "emp_info" and it has two columns. "employee name" and "employee no". "employee no" is the primary key.


2.PHP web service
Use following PHP script to fetch data from the database and to encode data in to json format.

<?php
$host="XXXXX"; //replace with database hostname 
$username="XXXXX"; //replace with database username 
$password="XXXXX"; //replace with database password 
$db_name="XXXXXX"; //replace with database name

$con=mysql_connect("$host", "$username", "$password")or die("cannot connect"); 
mysql_select_db("$db_name")or die("cannot select DB");
$sql = "select * from emp_info"; 
$result = mysql_query($sql);
$json = array();

if(mysql_num_rows($result)){
while($row=mysql_fetch_assoc($result)){
$json['emp_info'][]=$row;
}
}
mysql_close($con);
echo json_encode($json); 
?> 
You can see the output of  php by clicking below url:
http://cpriyankara.coolpage.biz/employee_details.php

3.Android web service client.
This part is bit complected. Android activity is a combination of Async Task json and list view. If you are not familiar with those stuff look following tutorials.

Android Async Task and web service access
http://codeoncloud.blogspot.com/2013/07/android-web-service-access-using-async.html

Android list view
http://codeoncloud.blogspot.com/2013/07/how-to-populate-android-list-view-from.html

Here is the code for main Android activity.
package com.axel.mysqlphpjson;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;

public class MainActivity extends Activity {
 private String jsonResult;
 private String url = "http://cpriyankara.coolpage.biz/employee_details.php";
 private ListView listView;

 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
  listView = (ListView) findViewById(R.id.listView1);
  accessWebService();
 }

 @Override
 public boolean onCreateOptionsMenu(Menu menu) {
  // Inflate the menu; this adds items to the action bar if it is present.
  getMenuInflater().inflate(R.menu.main, menu);
  return true;
 }

 // Async Task to access the web
 private class JsonReadTask extends AsyncTask<String, Void, String> {
  @Override
  protected String doInBackground(String... params) {
   HttpClient httpclient = new DefaultHttpClient();
   HttpPost httppost = new HttpPost(params[0]);
   try {
    HttpResponse response = httpclient.execute(httppost);
    jsonResult = inputStreamToString(
      response.getEntity().getContent()).toString();
   }

   catch (ClientProtocolException e) {
    e.printStackTrace();
   } catch (IOException e) {
    e.printStackTrace();
   }
   return null;
  }

  private StringBuilder inputStreamToString(InputStream is) {
   String rLine = "";
   StringBuilder answer = new StringBuilder();
   BufferedReader rd = new BufferedReader(new InputStreamReader(is));

   try {
    while ((rLine = rd.readLine()) != null) {
     answer.append(rLine);
    }
   }

   catch (IOException e) {
    // e.printStackTrace();
    Toast.makeText(getApplicationContext(),
      "Error..." + e.toString(), Toast.LENGTH_LONG).show();
   }
   return answer;
  }

  @Override
  protected void onPostExecute(String result) {
   ListDrwaer();
  }
 }// end async task

 public void accessWebService() {
  JsonReadTask task = new JsonReadTask();
  // passes values for the urls string array
  task.execute(new String[] { url });
 }

 // build hash set for list view
 public void ListDrwaer() {
  List<Map<String, String>> employeeList = new ArrayList<Map<String, String>>();

  try {
   JSONObject jsonResponse = new JSONObject(jsonResult);
   JSONArray jsonMainNode = jsonResponse.optJSONArray("emp_info");

   for (int i = 0; i < jsonMainNode.length(); i++) {
    JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
    String name = jsonChildNode.optString("employee name");
    String number = jsonChildNode.optString("employee no");
    String outPut = name + "-" + number;
    employeeList.add(createEmployee("employees", outPut));
   }
  } catch (JSONException e) {
   Toast.makeText(getApplicationContext(), "Error" + e.toString(),
     Toast.LENGTH_SHORT).show();
  }

  SimpleAdapter simpleAdapter = new SimpleAdapter(this, employeeList,
    android.R.layout.simple_list_item_1,
    new String[] { "employees" }, new int[] { android.R.id.text1 });
  listView.setAdapter(simpleAdapter);
 }

 private HashMap<String, String> createEmployee(String name, String number) {
  HashMap<String, String> employeeNameNo = new HashMap<String, String>();
  employeeNameNo.put(name, number);
  return employeeNameNo;
 }
}


Add Internet permission to AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.axel.mysqlphpjson"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="17" />

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

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.axel.mysqlphpjson.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>

Code for main activity layout.
<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"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >

    <ListView
        android:id="@+id/listView1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="14dp" >
    </ListView>

</RelativeLayout>
Quick demo of the application:


Was above information helpful?
Your comments always encourage me to write more...

91 comments:

  1. try {
    HttpResponse response = httpclient.execute(httppost);
    jsonResult = inputStreamToString(
    response.getEntity().getContent()).toString();
    }

    gives me error that inputStreamToString is not applicable for the arguments string.

    nay idea?

    ReplyDelete
    Replies
    1. You need to import InputStream

      Delete
    2. hi ..I am getting an error that JSON array cannot converted into JSON object.can some body me plz.

      Delete
  2. Nice tutorial. Thanks
    Can u do the same with inserting data into database from a custom list view with checkboxes.
    whatever checkbox is checked is inserted in database

    ReplyDelete
  3. Excellent Tutorial..
    Can you maybe extend on clicking on each item and open a new activity for each selected row in the listview?

    This would be really interesting..

    ReplyDelete
  4. Replies
    1. Yes, my web service is fetching data from MySql database server hosed at freetzi.com.

      Delete
  5. is this an online data? and how to put the php file into http?
    thks

    ReplyDelete
    Replies
    1. You have to use a php hosting service. There are plenty of free php hosting services are also available like 000webhost.com, freetzi.com etc.

      Delete
  6. thanks,
    0-08 10:31:29.750: E/AndroidRuntime(4026): FATAL EXCEPTION: AsyncTask #1
    10-08 10:31:29.750: E/AndroidRuntime(4026): java.lang.RuntimeException: An error occured while executing doInBackground()
    10-08 10:31:29.750: E/AndroidRuntime(4026): at android.os.AsyncTask$3.done(AsyncTask.java:278)
    10-08 10:31:29.750: E/AndroidRuntime(4026): at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)
    10-08 10:31:29.750: E/AndroidRuntime(4026): at java.util.concurrent.FutureTask.setException(FutureTask.java:124)
    10-08 10:31:29.750: E/AndroidRuntime(4026): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307)
    10-08 10:31:29.750: E/AndroidRuntime(4026): at java.util.concurrent.FutureTask.run(FutureTask.java:137)
    10-08 10:31:29.750: E/AndroidRuntime(4026): at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:208)
    10-08 10:31:29.750: E/AndroidRuntime(4026): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
    10-08 10:31:29.750: E/AndroidRuntime(4026): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
    10-08 10:31:29.750: E/AndroidRuntime(4026): at java.lang.Thread.run(Thread.java:856)
    10-08 10:31:29.750: E/AndroidRuntime(4026): Caused by: java.lang.IllegalArgumentException: Illegal character in path at index 11: 127.168.1.1 estSer est.php
    10-08 10:31:29.750: E/AndroidRuntime(4026): at java.net.URI.create(URI.java:727)
    10-08 10:31:29.750: E/AndroidRuntime(4026): at org.apache.http.client.methods.HttpPost.(HttpPost.java:79)
    10-08 10:31:29.750: E/AndroidRuntime(4026): at com.example.mysqlphpjson.MainActivity$JsonReadTask.doInBackground(MainActivity.java:56)
    10-08 10:31:29.750: E/AndroidRuntime(4026): at com.example.mysqlphpjson.MainActivity$JsonReadTask.doInBackground(MainActivity.java:1)
    10-08 10:31:29.750: E/AndroidRuntime(4026): at android.os.AsyncTask$2.call(AsyncTask.java:264)
    10-08 10:31:29.750: E/AndroidRuntime(4026): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
    10-08 10:31:29.750: E/AndroidRuntime(4026): ... 5 more

    ReplyDelete
    Replies
    1. Error is mentioned here :
      Caused by: java.lang.IllegalArgumentException: Illegal character in path at index 11: 127.168.1.1 estSer est.php
      Check the web service again.

      Delete
  7. Thanks for Posting this tutorial Nice one, Easy to understand and it's working properly..

    ReplyDelete
  8. Excelente tutorial.+1
    But how i can update the listview if the data changes???

    ReplyDelete
  9. When I use a variable containing the value like "Mark" the JSON Parser cannot convert the data.
    ERROR = Error parsing data [Value [] of type org.json.JSONArray cannot be converted to JSONObject] []

    E.G:
    $name = 'Mark';
    "SELECT * FROM emp_ WHERE employee name = '$name'";

    But when i do this:
    "SELECT * FROM emp_ WHERE employee name = 'Mark'";
    It is working perfectly....please help me.

    ReplyDelete
  10. I have been trying to select a particular user's details from my database tables via the use of a session variable. When ever I do so am given the following error

    JSON Parser - Error parsing data [Value [] of type org.json.JSONArray cannot be converted to JSONObject] []

    But when I use an actual value(e.g. Mark) everything works out fine and the data is displayed via my app

    ReplyDelete
  11. HI! First for the excellent tutorial. I have a question, well 3 :), only is running with your web service?. I mean, with the web service that you create in the example (with a web adress that you also add in the code). Is possible also to run with my own web service? . How? I was trying to set the variable String url = http://MY IP/prueba/prueba.php but is not working.

    Everything is the same like in the example, just that I use my own site

    Thanks again

    ReplyDelete
  12. Hi! First, thanks for this excellent tutorial. I have a question, well maybe more :)
    Is this example only running with your web service. I mean, with the web service PHP from the example.
    I was trying to set the variable String url = http://MY IP/prueba.php, then I can load my own data from my own web server. But unfortunaly is not loading my information, I don't get any error. Maybe I am missing something
    Is possible to do it like this? I hope yes, but How? I don't change nothing from the code in the example, I use the same, just with different data in the DB

    Again thanks

    ReplyDelete
  13. Hi i tried this code but while launching it on the android emulator, it's showing - unfortunately "project name' has stopped

    ReplyDelete
  14. Hi, I tried this code....but while launching it on the android emulator, it's showing - unfortunately 'project_name' has stopped....please help

    ReplyDelete
  15. What part of the code would need to change if you had a 4 column database? I am running into some trouble of gathering all four columns for display.

    ReplyDelete
  16. What part of the code would change if you had a 4 column database? I am running into some trouble trying to get more than 2 columns of my database.

    ReplyDelete
  17. Thanks for this tutorial really it helped me a lot

    ReplyDelete
  18. after 1 day of searching i found this tuto very good and it works thank you

    ReplyDelete
  19. It really works, nice tutorial.........thanks.....

    ReplyDelete
  20. It really works, nice tutorial....., thanks......

    ReplyDelete
  21. Thanks MAN!!! Its Really work.can you help me more.

    ReplyDelete
  22. This information is very helpful. Keep posting.
    Thanks for the post.Well the information looks very interesting as it explained in a most appropriate manner.

    Website Development company

    ReplyDelete
  23. org.json.JSONException: Value <br of type java.lang.String cannot be converted to JSONObject.
    What to do?

    ReplyDelete
  24. org.json.JSONException: Value <br of type java.lang.String cannot be converted to JSONObject

    what should i do?

    ReplyDelete
  25. I really wish you has rolled this project into a zip or posted on github, but since you did not..
    I ended up creating the files from scratch then tried to import them into eclipse.
    Issues needing cleanup:
    This line in your code for AndroidManifest.xml causes an error:
    android:theme="@style/AppTheme" >
    ..because it causes eclipse to look for a styles.xml under res\values that is not there.
    creating the file manually using the xml code below clears that error:
    see this stackoverflow thread (http://stackoverflow.com/questions/13705067/holo-themed-app-falls-back-to-default-android-theme)

    ..for the three "styles.xml" code files to be placed under:
    res/value
    res/value-v11
    res/value/-v14

    The second set of errors is caused by these lines in main activity code:
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"

    ..which causes eclipse to look for a dimens.xml under the res\values folder.
    To clear the error, create this dimens.xml file manually with the following code:


    16dp
    16dp


    The last error is due to this line in the main Android activity code:
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
    }
    Which causes an error because it thinks there is a missing .xml file that should be under the res\menu folder.
    So you could manually create such an.xml file (like menu.xml) under res\menu, but since their is no code for actually listening for options menu I just commented out the code to clear the error:
    /* @Override
    *public boolean onCreateOptionsMenu(Menu menu) {
    *// Inflate the menu; this adds items to the action bar if it is present.
    *getMenuInflater().inflate(R.menu.main, menu);
    *return true;
    * }
    */

    After that it should compile without errors.
    Thanks for the useful tutorial.
    Now I just have to figure out how to concatenate several database column fields into a single line of listview text instead of just the two specified by the line:
    String outPut = name + "-" + number;
    This may mean losing the hashmap altogether (since a hashmap is basically/usually consists of just key/value pairing), but I need at least 5 fields together on one row of text for each the listview item.


    ReplyDelete
  26. I really wish you has rolled this project into a zip or posted on github, but since you did not..
    I ended up creating the files from scratch then tried to import them into eclipse.
    Issues needing cleanup:
    This line in your code for AndroidManifest.xml causes an error:
    android:theme="@style/AppTheme" >
    ..because it causes eclipse to look for a styles.xml under res\values that is not there.
    creating the file manually using the xml code below clears that error:
    see this stackoverflow thread (http://stackoverflow.com/questions/13705067/holo-themed-app-falls-back-to-default-android-theme)

    ..for the three "styles.xml" code files to be placed under:
    res/value
    res/value-v11
    res/value/-v14

    The second set of errors is caused by these lines in main activity code:
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"

    ..which causes eclipse to look for a dimens.xml under the res\values folder.
    To clear the error, create this dimens.xml file manually with the following code:


    16dp
    16dp


    The last error is due to this line in the main Android activity code:
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
    }
    Which causes an error because it thinks there is a missing .xml file that should be under the res\menu folder.
    So you could manually create such an.xml file (like menu.xml) under res\menu, but since their is no code for actually listening for options menu I just commented out the code to clear the error:
    /* @Override
    *public boolean onCreateOptionsMenu(Menu menu) {
    *// Inflate the menu; this adds items to the action bar if it is present.
    *getMenuInflater().inflate(R.menu.main, menu);
    *return true;
    * }
    */

    After that it should compile without errors.
    Thanks for the useful tutorial.
    Now I just have to figure out how to concatenate several database column fields into a single line of listview text instead of just the two specified by the line:
    String outPut = name + "-" + number;
    This may mean losing the hashmap altogether (since a hashmap is basically/usually consists of just key/value pairing), but I need at least 5 fields together on one row of text for each the listview item.

    ReplyDelete
  27. Hi guys...
    give me error
    12-25 05:03:25.897: E/JSON Parser(860): Error parsing data org.json.JSONException: Value

    ReplyDelete
  28. 12-25 05:03:25.897: E/JSON Parser(860): Error parsing data org.json.JSONException: Value

    ReplyDelete
  29. how can i send data from android to php with json?

    ReplyDelete
  30. Hi, thanks for this great example. I have a question: How can I get record ID when I touch on a record? I use listView.setOnItemClickListener and "String record = ((TextView) view).getText().toString();". But ID shouldn't be viewed on textview in my application. How can I manage this?

    Thanks in advance.

    ReplyDelete
  31. Hi, thanks for this great example. I have a question: How can I get record ID when I touch on a record? I use listView.setOnItemClickListener and "String record = ((TextView) view).getText().toString();". But ID shouldn't be viewed on textview in my application. How can I manage this?

    Thanks in advance.

    ReplyDelete

  32. Hi, friends
    The post is really awesome with lots of information inside. It has knowledgeable post.
    Thanks a lot for posting this
    Free English Speaking Course in India

    ReplyDelete
  33. Great tutorial. First one I tried that actually works. It would be great if you could expand a bit. I am looking for how to do a more complex list view such as one with an image and several text views. Any chance you could show how to do this?

    ReplyDelete
  34. Great tutorial. Nice coding. I am found in some of the errors.
    http://www.dreamdestinations.in/

    ReplyDelete
  35. Great tutorial. Nice coding. Useful Android MySQL PHP & JSON tutorial. Thanks for Posting.
    http://www.dreamdestinations.in/

    ReplyDelete
  36. But we can i do if i want to fetch data from multiple mysql tables on android by json

    ReplyDelete
  37. But what can i do if I want to fetch mysql multiple data by join query in android by using json????

    ReplyDelete
  38. 02-26 00:40:56.868: E/AndroidRuntime(1466): FATAL EXCEPTION: main
    02-26 00:40:56.868: E/AndroidRuntime(1466): Process: com.example.login, PID: 1466
    02-26 00:40:56.868: E/AndroidRuntime(1466): java.lang.NullPointerException
    02-26 00:40:56.868: E/AndroidRuntime(1466): at org.json.JSONTokener.nextCleanInternal(JSONTokener.java:116)
    02-26 00:40:56.868: E/AndroidRuntime(1466): at org.json.JSONTokener.nextValue(JSONTokener.java:94)
    02-26 00:40:56.868: E/AndroidRuntime(1466): at org.json.JSONObject.(JSONObject.java:155)
    02-26 00:40:56.868: E/AndroidRuntime(1466): at org.json.JSONObject.(JSONObject.java:172)
    02-26 00:40:56.868: E/AndroidRuntime(1466): at com.example.login.AndroidPHPConnectionDemo.ListDrwaer(AndroidPHPConnectionDemo.java:121)
    02-26 00:40:56.868: E/AndroidRuntime(1466): at com.example.login.AndroidPHPConnectionDemo$JsonReadTask.onPostExecute(AndroidPHPConnectionDemo.java:103)
    02-26 00:40:56.868: E/AndroidRuntime(1466): at com.example.login.AndroidPHPConnectionDemo$JsonReadTask.onPostExecute(AndroidPHPConnectionDemo.java:1)
    02-26 00:40:56.868: E/AndroidRuntime(1466): at android.os.AsyncTask.finish(AsyncTask.java:632)
    02-26 00:40:56.868: E/AndroidRuntime(1466): at android.os.AsyncTask.access$600(AsyncTask.java:177)
    02-26 00:40:56.868: E/AndroidRuntime(1466): at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:645)
    02-26 00:40:56.868: E/AndroidRuntime(1466): at android.os.Handler.dispatchMessage(Handler.java:102)
    02-26 00:40:56.868: E/AndroidRuntime(1466): at android.os.Looper.loop(Looper.java:137)
    02-26 00:40:56.868: E/AndroidRuntime(1466): at android.app.ActivityThread.main(ActivityThread.java:4998)
    02-26 00:40:56.868: E/AndroidRuntime(1466): at java.lang.reflect.Method.invokeNative(Native Method)
    02-26 00:40:56.868: E/AndroidRuntime(1466): at java.lang.reflect.Method.invoke(Method.java:515)
    02-26 00:40:56.868: E/AndroidRuntime(1466): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:777)
    02-26 00:40:56.868: E/AndroidRuntime(1466): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:593)
    02-26 00:40:56.868: E/AndroidRuntime(1466): at dalvik.system.NativeStart.main(Native Method)

    I connect php-mysql xamp use so please help me my email id pravinfatak123@gmail.com

    ReplyDelete
  39. no error but cannot run

    ReplyDelete
  40. it work, it let say using localhost, can i just paste the url?
    like this....
    private String url = "http://localhost/degree%20project/Attendance%20Monitoring%20System/decode.php";

    ReplyDelete
    Replies
    1. Nope you have to use the server ip address instead of localhost and your server should be accessible from outside

      Delete
  41. why cannot view on phone, im use galaxy ace, version is 2.3.4..

    ReplyDelete
  42. When I run the app I am retrieving your data. I presume it has something to do with this Line:-

    private String url = "http://cpriyankara.coolpage.biz/employee_details.php";

    I want to pull down the data I have stored on my localhost. But I'm not sure what the host name should be. In the php file I have this:-




    Then I have the changed the String URL to :- private String url = "http://localhost/clientservertest/login.php";

    The app is crashing when I load it. Any help would be greatly appreciated

    ReplyDelete
    Replies
    1. Replace localhost with your computer ip address but make sure that your firewall settings allow to access your wamp server and the wamp server should be accessible from outside

      Delete
  43. I created a test app following your tutorial and I can retrieve your data ok. I presume this has something to do with this line of code:-

    private String url = "http://cpriyankara.coolpage.biz/employee_details.php";

    I then created a small MySQL database using WAMP and populated it with my own data. I have edited the php to look like this :-



    I then changed the String URL variable to :-

    private String url = "http://localhost/clientservertest/login.php";

    Should these changes allow me to view my data? Any help would be greatly appreciated.

    ReplyDelete
  44. I created a test app following your tutorial and I can retrieve your data ok. I presume this has something to do with this line of code:-

    private String url = "http://cpriyankara.coolpage.biz/employee_details.php";

    I then created a small MySQL database using WAMP and populated it with my own data. I have edited the php to look like this :-



    I then changed the String URL variable to :-

    private String url = "http://localhost/clientservertest/login.php";

    Should these changes allow me to view my data? Any help would be greatly appreciated.

    ReplyDelete
  45. hi, nice tutorial
    i found this message on debuging

    05-25 22:23:43.310: ERROR/InputDispatcher(718): Motion event has invalid pointer count 0; value must be between 1 and 16.
    05-25 22:23:43.400: ERROR/InputDispatcher(718): Motion event has invalid pointer count 0; value must be between 1 and 16.
    05-25 22:23:43.430: ERROR/Constants(887): Getting new oem
    05-25 22:23:43.430: ERROR/Constants(887): product.oem not found
    05-25 22:23:43.430: ERROR/Constants(887): Getting new oem
    05-25 22:23:43.430: ERROR/Constants(887): product.oem not found
    05-25 22:23:43.440: ERROR/Constants(887): Getting new oem
    05-25 22:23:43.440: ERROR/Constants(887): product.oem not found
    05-25 22:23:43.610: ERROR/Sensor-AccelerometerUI(902): java.io.IOException: Connection refused
    05-25 22:23:44.640: ERROR/AndroidRuntime(4999): in writeCrashedAppName, pkgName :com.example.prokaraokemobile
    05-25 22:23:44.640: ERROR/AndroidRuntime(4999): FATAL EXCEPTION: main
    05-25 22:23:44.640: ERROR/AndroidRuntime(4999): java.lang.NullPointerException
    05-25 22:23:44.640: ERROR/AndroidRuntime(4999): at com.example.prokaraokemobile.MainActivity.ListDrwaer(MainActivity.java:122)
    05-25 22:23:44.640: ERROR/AndroidRuntime(4999): at com.example.prokaraokemobile.MainActivity$JsonReadTask.onPostExecute(MainActivity.java:89)
    05-25 22:23:44.640: ERROR/AndroidRuntime(4999): at com.example.prokaraokemobile.MainActivity$JsonReadTask.onPostExecute(MainActivity.java:1)
    05-25 22:23:44.640: ERROR/AndroidRuntime(4999): at android.os.AsyncTask.finish(AsyncTask.java:602)
    05-25 22:23:44.640: ERROR/AndroidRuntime(4999): at android.os.AsyncTask.access$600(AsyncTask.java:156)
    05-25 22:23:44.640: ERROR/AndroidRuntime(4999): at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:615)
    05-25 22:23:44.640: ERROR/AndroidRuntime(4999): at android.os.Handler.dispatchMessage(Handler.java:99)
    05-25 22:23:44.640: ERROR/AndroidRuntime(4999): at android.os.Looper.loop(Looper.java:137)
    05-25 22:23:44.640: ERROR/AndroidRuntime(4999): at android.app.ActivityThread.main(ActivityThread.java:4424)
    05-25 22:23:44.640: ERROR/AndroidRuntime(4999): at java.lang.reflect.Method.invokeNative(Native Method)
    05-25 22:23:44.640: ERROR/AndroidRuntime(4999): at java.lang.reflect.Method.invoke(Method.java:511)
    05-25 22:23:44.640: ERROR/AndroidRuntime(4999): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:825)
    05-25 22:23:44.640: ERROR/AndroidRuntime(4999): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:592)
    05-25 22:23:44.640: ERROR/AndroidRuntime(4999): at dalvik.system.NativeStart.main(Native Method)
    05-25 22:23:44.690: ERROR/InputDispatcher(718): channel 'b327f6f0 com.example.prokaraokemobile/com.example.prokaraokemobile.MainActivity (server)' ~ Channel is unrecoverably broken and will be disposed!
    05-25 22:23:44.740: ERROR/gpop.InstalledAppsGrid(887): Hidden list size 11
    05-25 22:28:55.530: ERROR/dalvikvm(846): No JIT support for bytecode f0 at offsetPC 1
    05-25 22:28:55.530: ERROR/dalvikvm(846): JIT implementation not found
    05-25 22:36:00.000: ERROR/dalvikvm(718): No JIT support for bytecode f0 at offsetPC 2
    05-25 22:36:00.000: ERROR/dalvikvm(718): JIT implementation not found

    ReplyDelete
    Replies
    1. I suspect that your web service is not accessible because "java.io.IOException: Connection refused" make sure that it is accessible.

      Delete
  46. hi, i found the messages like this:

    05-25 22:23:43.310: ERROR/InputDispatcher(718): Motion event has invalid pointer count 0; value must be between 1 and 16.
    05-25 22:23:43.400: ERROR/InputDispatcher(718): Motion event has invalid pointer count 0; value must be between 1 and 16.
    05-25 22:23:43.430: ERROR/Constants(887): Getting new oem
    05-25 22:23:43.430: ERROR/Constants(887): product.oem not found
    05-25 22:23:43.430: ERROR/Constants(887): Getting new oem
    05-25 22:23:43.430: ERROR/Constants(887): product.oem not found
    05-25 22:23:43.440: ERROR/Constants(887): Getting new oem
    05-25 22:23:43.440: ERROR/Constants(887): product.oem not found
    05-25 22:23:43.610: ERROR/Sensor-AccelerometerUI(902): java.io.IOException: Connection refused
    05-25 22:23:44.640: ERROR/AndroidRuntime(4999): in writeCrashedAppName, pkgName :com.example.prokaraokemobile
    05-25 22:23:44.640: ERROR/AndroidRuntime(4999): FATAL EXCEPTION: main
    05-25 22:23:44.640: ERROR/AndroidRuntime(4999): java.lang.NullPointerException
    05-25 22:23:44.640: ERROR/AndroidRuntime(4999): at com.example.prokaraokemobile.MainActivity.ListDrwaer(MainActivity.java:122)
    05-25 22:23:44.640: ERROR/AndroidRuntime(4999): at com.example.prokaraokemobile.MainActivity$JsonReadTask.onPostExecute(MainActivity.java:89)
    05-25 22:23:44.640: ERROR/AndroidRuntime(4999): at com.example.prokaraokemobile.MainActivity$JsonReadTask.onPostExecute(MainActivity.java:1)
    05-25 22:23:44.640: ERROR/AndroidRuntime(4999): at android.os.AsyncTask.finish(AsyncTask.java:602)
    05-25 22:23:44.640: ERROR/AndroidRuntime(4999): at android.os.AsyncTask.access$600(AsyncTask.java:156)
    05-25 22:23:44.640: ERROR/AndroidRuntime(4999): at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:615)
    05-25 22:23:44.640: ERROR/AndroidRuntime(4999): at android.os.Handler.dispatchMessage(Handler.java:99)
    05-25 22:23:44.640: ERROR/AndroidRuntime(4999): at android.os.Looper.loop(Looper.java:137)
    05-25 22:23:44.640: ERROR/AndroidRuntime(4999): at android.app.ActivityThread.main(ActivityThread.java:4424)
    05-25 22:23:44.640: ERROR/AndroidRuntime(4999): at java.lang.reflect.Method.invokeNative(Native Method)
    05-25 22:23:44.640: ERROR/AndroidRuntime(4999): at java.lang.reflect.Method.invoke(Method.java:511)
    05-25 22:23:44.640: ERROR/AndroidRuntime(4999): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:825)
    05-25 22:23:44.640: ERROR/AndroidRuntime(4999): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:592)
    05-25 22:23:44.640: ERROR/AndroidRuntime(4999): at dalvik.system.NativeStart.main(Native Method)
    05-25 22:23:44.690: ERROR/InputDispatcher(718): channel 'b327f6f0 com.example.prokaraokemobile/com.example.prokaraokemobile.MainActivity (server)' ~ Channel is unrecoverably broken and will be disposed!
    05-25 22:23:44.740: ERROR/gpop.InstalledAppsGrid(887): Hidden list size 11
    05-25 22:28:55.530: ERROR/dalvikvm(846): No JIT support for bytecode f0 at offsetPC 1
    05-25 22:28:55.530: ERROR/dalvikvm(846): JIT implementation not found
    05-25 22:36:00.000: ERROR/dalvikvm(718): No JIT support for bytecode f0 at offsetPC 2
    05-25 22:36:00.000: ERROR/dalvikvm(718): JIT implementation not found

    what it's mean??
    thanks before

    ReplyDelete
  47. Great blog!!!!!!!!!It describes some small code about the PHP,.NET and Android application..
    The interested candidate can join this blog..
    Online Android Tutorial

    ReplyDelete
  48. So nice blog!!!
    The main focus of this blog is in the database MySQL.So the candidate which are interested in Learning database can join this blog.
    Training MySQL

    ReplyDelete
  49. Hi

    I have been able to get your Tutorial to work. thanks for sharing. However can you write an example where the list we created from json response is search filtered based on user input.

    Thanks!

    ReplyDelete
  50. Android library projects can not be launch ?

    ReplyDelete
  51. Android library projects can not be launch

    ReplyDelete
  52. PHP and Mysql are the main programming coding to create the functionality for the website.But developers should have the strong skills in that segment.
    Web Designing Company Bangalore | Website Designers Bangalore

    ReplyDelete
  53. hello,

    when i try to run the codes. an error occured "UNFORTUNATELY THE APPLICATION STOPPED". the application suddenly closed. when i run in the emulator.

    ReplyDelete
  54. thank you thank you thank you!! modified your code for my own list and database, worked perfectly, no debugging required. Unbelievable!! THANK YOU.

    ReplyDelete
  55. thank you thank you thank you!! modified your code for my own custom list adapter and database - worked perfectly, no debugging required. Unbelievable!! THANK YOU.

    ReplyDelete
  56. Thanks alot! you really helped me :)

    ReplyDelete
  57. Thanks alot! you really helped me :)

    ReplyDelete
  58. not able to print the value of json while using my server address...but it works perfectly with localhost..not able to find out the reason..only the json value is not printing otherwise if for test purpose echo("hello") works on both server address and localhost..but not json..plz help

    ReplyDelete
    Replies
    1. May be your web service cannot access the database. If you can please post the error stack trace.

      Delete
  59. thank you very much. thanks to your code i could my problem.

    ReplyDelete
  60. I need a detail activity like when i click on record to its open in a new activity with detal from my sql db

    ReplyDelete
  61. I need a detail activity like when i click on record to its open in a new activity with detal from my sql db

    ReplyDelete
  62. A php tutorials that covers all the basics of PHP with examples help to learn php language for Begginers Online.

    ReplyDelete
  63. How could I implement the above code with a recyclerview?

    ReplyDelete
  64. How could i implement the above code with a recyclerview?

    ReplyDelete
  65. when i used my own URL instead of your's in given MainActivity.java file. It works for first time but for the second it is not working anymore. I have tried all these like: http://10.0.2.2 or http://127.0.0.1 or http://your ip. what could be the possible solution?

    ReplyDelete
  66. When I use a variable containing the value like "Mark" the JSON Parser cannot convert the data.
    ERROR = Error parsing data [Value [] of type org.json.JSONArray cannot be converted to JSONObject] []

    E.G:
    $name = 'Mark';
    "SELECT * FROM emp_ WHERE employee name = '$name'";

    But when i do this:
    "SELECT * FROM emp_ WHERE employee name = 'Mark'";
    It is working perfectly....please help me.

    ReplyDelete
  67. When I use a variable containing the value like "Mark" the JSON Parser cannot convert the data.
    ERROR = Error parsing data [Value [] of type org.json.JSONArray cannot be converted to JSONObject] []

    E.G:
    $name = 'Mark';
    "SELECT * FROM emp_ WHERE employee name = '$name'";

    But when i do this:
    "SELECT * FROM emp_ WHERE employee name = 'Mark'";
    It is working perfectly....please help me.

    ReplyDelete
  68. if there are 6 entries to display then how to do it..please help me

    ReplyDelete
  69. Please suggest :--
    12-24 03:37:26.285 7392-7392/employee.employee_detail E/AndroidRuntime: FATAL EXCEPTION: main
    Process: employee.employee_detail, PID: 7392
    java.lang.NullPointerException
    at org.json.JSONTokener.nextCleanInternal(JSONTokener.java:116)
    at org.json.JSONTokener.nextValue(JSONTokener.java:94)
    at org.json.JSONObject.(JSONObject.java:155)
    at org.json.JSONObject.(JSONObject.java:172)
    at employee.employee_detail.MainActivity.ListDrwaer(MainActivity.java:108)
    at employee.employee_detail.MainActivity$JsonReadTask.onPostExecute(MainActivity.java:93)
    at employee.employee_detail.MainActivity$JsonReadTask.onPostExecute(MainActivity.java:51)
    at android.os.AsyncTask.finish(AsyncTask.java:632)
    at android.os.AsyncTask.access$600(AsyncTask.java:177)
    at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:645)
    at android.os.Handler.dispatchMessage(Handler.java:102)
    at android.os.Looper.loop(Looper.java:136)
    at android.app.ActivityThread.main(ActivityThread.java:5017)
    at java.lang.reflect.Method.invokeNative(Native Method)
    at java.lang.reflect.Method.invoke(Method.java:515)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
    at dalvik.system.NativeStart.main(Native Method)

    ReplyDelete
  70. Please suggest

    12-24 03:37:26.285 7392-7392/employee.employee_detail E/AndroidRuntime: FATAL EXCEPTION: main
    Process: employee.employee_detail, PID: 7392
    java.lang.NullPointerException
    at org.json.JSONTokener.nextCleanInternal(JSONTokener.java:116)
    at org.json.JSONTokener.nextValue(JSONTokener.java:94)
    at org.json.JSONObject.(JSONObject.java:155)
    at org.json.JSONObject.(JSONObject.java:172)
    at employee.employee_detail.MainActivity.ListDrwaer(MainActivity.java:108)
    at employee.employee_detail.MainActivity$JsonReadTask.onPostExecute(MainActivity.java:93)
    at employee.employee_detail.MainActivity$JsonReadTask.onPostExecute(MainActivity.java:51)
    at android.os.AsyncTask.finish(AsyncTask.java:632)
    at android.os.AsyncTask.access$600(AsyncTask.java:177)
    at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:645)
    at android.os.Handler.dispatchMessage(Handler.java:102)
    at android.os.Looper.loop(Looper.java:136)
    at android.app.ActivityThread.main(ActivityThread.java:5017)
    at java.lang.reflect.Method.invokeNative(Native Method)
    at java.lang.reflect.Method.invoke(Method.java:515)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
    at dalvik.system.NativeStart.main(Native Method)

    ReplyDelete
  71. Wenn die Suche nach Dienstleistungen E-Commerce- Website-Entwicklung und Design sind hier beste E-Commerce- Design und Entwicklungsdienstleistungen . Bitte kontaktieren Sie uns unter http://www.accuratesolutionsltd.com/kontaktieren-sie-uns/

    ReplyDelete
  72. Not working...Error: values cannot convert to JSONobject..can anyone tell me the problem?.

    ReplyDelete
  73. Good efforts. All the best for future posts. I have bookmarked you. Well done. I read and like this post. Thanks. graphic designing courses in jalandhar

    ReplyDelete
  74. i need the code for the login activity with mysqlii database ,,plz send me the code fpor this

    ReplyDelete
  75. Your blog has given me that thing which I never expect to get from all over the websites. Nice post guys!
    regards,
    Melbourne Web Designer

    ReplyDelete
  76. Thank you for sharing; it’s nice and helpful information. I hope I could read more information like this in the next visit.
    regards,
    SEO melbourne

    ReplyDelete