Filter JSON Data in Android Application using PHP and MySQL

Hi there, here I bring you this filter JSON lesson in which you can learn how to fetch data from the server database and then either sort it or filter it through JSON which would be displayed in the form of ListView. In this filter JSON project as an example, we’ll be creating a database of laptops on the server, fetch the whole lot of data and then sort or filter JSON received from the server.  I’ll begin with the server side tasks. So let’s get started.

Setting the server for the project

  • First of all we need to set up the database on the server as I have already in the image below. Just download the db below named laptop.sql and import it to your PhpMyAdmin.

Download Laptop.SQL

Database

  • Now when your db is set up. Lets write Php scripts to  fetch the data from the database.

Creating PHP Scripts

  • First create a php file named Constants.php

  • Next, create a php file named DbConnect.php

  • Next, create a php file named DbOperation.php

  • Finally, create a php file named getData.php

  • If everything is fine you will see the data in JSON format, when you will run this script. If you can also skip this part if you want to use my database. Below is my live URL that you can use in this Filter JSON Tutorial.

http://internetfaqs.net/laptops/getData.php

  • Now let’s begin the android part.

Creating an Android Project for our Filter JSON App

  • Create a new Android project  named  JSONFilterApp. As your gradle is built and files are loaded, add the following dependency to your app level gradle. This will allow us to implement the php script in android.

  • As usual, we shall begin with configuring the activity_main.xml and MainActivity.java. Add the following codes into the respective files.
  • Here’s the activity_main.xml. It consists of four buttons leading to different activities. These activities will display the data in sorted and filtered manners.

  • Here’s the MainActivity.java. In here, the data from the server is fetched as the getData.php is implemented  through the method getLaptops() and the stored into SharedPreferences as String.

  • Now, create a layout resource file named list_layout.xml using the following code. It will contain the layout of the list view in activity_unsorted.xml, activity_sortedbybrand.xml and so on.

  • Now, create a class named Laptop using the following code.

  • Now, create a class named LaptopAdapter using the following code. It will serve as the adapter to the listView.

Creating different activites for the Results

  • Now, create a new Empty Activity named UnsortedActivity which will display the unsorted list of laptops with their details. Now, configure the xml and java parts of this activity using the following codes.
  • Here’s the activity_unsorted.xml. It contains the ListView which will display the unsorted List of Laptops.

  • Here’s the UnsortedActivity.java. In here, the String containing the data is fetched through SharedPreferences and then manipulated through JSON.

  • Next, create another Empty Activity named Sortedbybrand and then configure its xml and java parts using the following codes:-
  • Here’s the activity_sortedbybrand.xml. It simply contains the ListView in which the list of laptops will be displayed.

  • Here’s the Sortedbybrand.java. In here, the String containing the data will be fetched through SharedPreferences and then sorted through JSON by brand.

  • Similarly, create another Empty Activity named Sortedbyprice and configure the xml and java parts using the  following codes.
  • Here’s the activity_sortedbyprice. It again contains the ListView as in activity_soredbybrand.

  • Here’s the Sortedbyprice.java. In here, the String containing the data will be fetched through SharedPreferences and then sorted through JSON by price.

  • Similarly, create another Empty Activity named Filterresults and configure the xml and java parts using the  following codes.
  • Here’s the activity_filterresults.xml. It again contains the List view.

  • Here’s the Filterresults.java. In here, the String containing the data will be fetched through SharedPreferences and then filtered through JSON by price being less than 40000.

  • You are done with the activities here.
  • Finally, just add the internet permission to your AndroidManifest.xml and your Filter JSON app is complete.

  • That’s it:). Run the app the wait to see the Toast saying data fetched Successfully.
filter json data example
Filter JSON
filter json data
Filter JSON
  • If you are facing troubles then download my source code for this filter JSON project from below.

If you ran into some problems regarding this filter JSON Data tutorial, let me know in the comments section. I will try to sortout your problems ASAP.

13 thoughts on “Filter JSON Data in Android Application using PHP and MySQL”

  1. how to get values from json array of json array in android like below follow as:

    {
    “lesson_id”: “23”,
    “lesson_name”: “Lesson 2”,
    “lesson_sname”: “Alphabets”,
    “lesson_case”: “Upper Case”,
    “lesson_content”: “”,
    “worksheets”: [{
    “assignment_id”: “41”,
    “assignment_name”: “UPPER CASE – A TO M”,
    “assignment_file”: “”,
    “assignment_video”: “”,
    “is_assessment”: “no”
    }, {
    “assignment_id”: “42”,
    “assignment_name”: “UPPER CASE- N TO Z”,
    “assignment_file”: “”,
    “assignment_video”: “”,
    “is_assessment”: “no”
    }, {
    “assignment_id”: “43”,
    “assignment_name”: “UPPER CASE- A TO Z”,
    “assignment_file”: “”,
    “assignment_video”: “”,
    “is_assessment”: “no”
    }, {
    “assignment_id”: “44”,
    “assignment_name”: “UPPER CASE ASSESSMENT”,
    “assignment_file”: “2DamCreative18.pdf”,
    “assignment_video”: “h”,
    “is_assessment”: “yes”
    }]

    Reply
    • The main JSON Array you have mentioned must have a name .Let’s say its json1. Now json1 contains two json objects among which one is simple json object and another one is json array (worksheets) in the form of json obejct.

      Suppose you received whole of this data in response. Just parse it using Json object in the following way:-
      JSONObject js = new JSONObject(response);
      JSONArray jsonArray = js.getJSONArray(“json1”);
      Now you have your two json objects in jsonArray out of which one is a json obejct and another is itself an JSON array.
      In the code below you can fetch you jsonarray called worksheet.

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

      if(i==1){
      JSONObject jsonObject = json1.getJSONObject(i);
      }
      }

      JSONArray worksheets = jsonObject.getJSONArray("worksheets");

      Reply
  2. Hi Manish and Bilal,
    Is it really a applying filer on activity, I was thinking this can be done using PreferenceActivity.
    I need to implement filter like flipkart or olx in my application. I have searched a lot on web but did not found any desire result.
    Suggest me, how can achieve this functionality please or post yourself a tutorial like flipkart or olx filter the json data as soon as possible.
    Thanks in advance.

    Reply
    • Definetly, the json data is getting filtered in different activities. As you run the project, on the home screen, look for the parameter on whose name the button’name is. Upon the button tap, it takes you to an activity where the data is filtered according to the parameter on the button.

      Reply
  3. Hi guys

    I have a problem on file DbOperation.php in the following line:

    $result = $stmt->get_result();

    My browser show me this message:

    Fatal error: Call to undefined method mysqli_stmt::get_result() in /home/u345942556/public_html/DbOperation.php on line 23

    Sorry for my english.

    Reply
    • the method $stmt->get_result() requires PHPverion>5.3 and also requires mysqlnd driver to be installed on your server. So it throws the above error. The alternate of this method can be seen below:-

      if($statement=$conn->prepare(“SELECT * FROM users WHERE token= ? LIMIT 1”)){

      $statement-> bind_param(‘s’,$cvalue);

      // Execute
      $statement-> execute();

      // Bind results
      $statement-> bind_result($token);

      // Fetch value
      while ( $statement-> fetch() ) {
      echo $token . “”;
      }

      // Close statement
      $statement-> close();
      }

      // Close entire connection
      $conn-> close();

      Reply
  4. Hi Kumar,

    I have the same problem with Alexandre Conseicao.

    When running getData.php, browser shows me this message

    Fatal error: Call to undefined method mysqli_stmt::get_result() in /home/u304133174/public_html/filterjson/DbOperation.php on line 29

    Can you help me? I think it is because there is no get_result() function
    in the DbOperation.php file you have uploaded in this tutorial.

    Thanks in advance,
    Fotis Pegios

    Reply
  5. if($statement=$conn->prepare(“SELECT * FROM users WHERE token= ? LIMIT 1”)){

    $statement-> bind_param(‘s’,$cvalue);

    // Execute
    $statement-> execute();

    // Bind results
    $statement-> bind_result($token);

    // Fetch value
    while ( $statement-> fetch() ) {
    echo $token . “”;
    }

    // Close statement
    $statement-> close();
    }

    // Close entire connection
    $conn-> close();
    where to put this method?
    when i put this in my dboperation.php in getlaptops function,i get error syntax error, unexpected ‘users’ (T_STRING).What to do to correct this error?

    Reply
  6. for (int i = 0; i < jsonArray.length(); i++) {

    try {
    String f;
    JSONObject jsonObject = jsonArray.getJSONObject(i);
    String m = jsonObject.getString("modelname");

       if(m=="ASUS-13431") {
     
                        String modelname = "Modelname:" + jsonObject.getString("modelname");
                        String ram = "Ram:" +jsonObject.getString("ram");
                        String os = "Os:" +jsonObject.getString("os");
                        String price = "Price:"  + jsonObject.getString("price");
                        String screensize = "Screensize:" + jsonObject.getString("screensize");
                        String brand = "Brand:" + jsonObject.getString("brand");
                        Laptop laptop = new Laptop(modelname,ram,os,price,screensize,brand);
                        laptopList.add(laptop);
                    }

    I'm trying to sort by modelname but I'm not getting any output

    Reply
  7. Hi,
    Thank you to share your work. I tried to do the same but Android Studio 3.1 seems not work properly.
    It returns : Could not find method compile() for arguments [com.android.volley:volley:1.0.0] on object of type org.gradle.api.internal.artifacts.dsl.dependencies.DefaultDependencyHandler.

    How can I fix it? Thank you

    Reply

Leave a Comment