Simplified Coding

  • About
  • Contact Us
  • Advertise
  • Privacy Policy
You are here: Home / Android Application Development / Android Advance / Filter JSON Data in Android Application using PHP and MySQL

Filter JSON Data in Android Application using PHP and MySQL

September 6, 2016 by Manish Kumar 13 Comments

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

Constants.php
1
2
3
4
5
6
7
8
9
10
11
12
<?php
/**
* Created by PhpStorm.
* User: Manish
* Date: 9/3/2016
* Time: 5:33 PM
*/
 
define('DB_HOST','Your Host name');
define('DB_USERNAME','Your database Username');
define('DB_PASSWORD','Your database Password');
define('DB_NAME','Your database name');

  • Next, create a php file named DbConnect.php

DbConnect.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
<?php
 
/**
* Created by PhpStorm.
* User: Manish
* Date: 9/3/2016
* Time: 5:36 PM
*/
 
class DbConnect
{
 
 
    private $con;
 
    function __construct()
    {
    }
 
    function connect(){
 
 
        include 'Constants.php';
        $this->con = new mysqli(DB_HOST,DB_USERNAME,DB_PASSWORD,DB_NAME);
        if(mysqli_connect_errno()){
 
            echo 'Failed to connect to mysql'.mysqli_connect_errno();
        }
        return $this->con;
    }
 
}

  • Next, create a php file named DbOperation.php

DbOperation.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
<?php
 
/**
* Created by PhpStorm.
* User: Manish
* Date: 9/3/2016
* Time: 5:40 PM
*/
class DbOperation
{
 
 
private  $con;
 
    function __construct()
    {
        require_once 'DbConnect.php';
        $db =new DbConnect();
        $this->con = $db->connect();
    }
 
 
 
 
    public function getLaptops(){
 
        $stmt = $this->con->prepare("SELECT * FROM laptop ");
        $stmt->execute();
        $result = $stmt->get_result();
        return $result;
    }
 
}

  • Finally, create a php file named getData.php

getData.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
<?php
/**
* Created by PhpStorm.
* User: Manish
* Date: 9/3/2016
* Time: 9:00 PM
*/
 
 
require 'DbOperation.php';
 
$response = array();
 
$db = new DbOperation();
 
$result = $db->getLaptops();
$response['laptops'] = array();
 
while($row = mysqli_fetch_array($result)){
 
    $temp = array();
 
 
    $temp['id'] = $row['id'];
    $temp['modelname'] = $row['modelname'];
    $temp['ram'] = $row['ram'];
    $temp['os'] = $row['os'];
    $temp['price'] = $row['price'];
    $temp['screensize'] = $row['screensize'];
    $temp['brand'] = $row['brand'];
 
    array_push($response['laptops'],$temp);
 
}
 
echo json_encode($response);

  • 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.

VolleyDependency
1
compile 'com.android.volley:volley:1.0.0'

  • 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.

activity_main.xml
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
<?xml version="1.0" encoding="utf-8"?>
<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="com.example.manish.jsonfilterapp.MainActivity">
 
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="UNSORTED LIST"
        android:id="@+id/buttonUnsortedlist"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="77dp" />
 
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="SORTED BY BRAND"
        android:id="@+id/buttonSortedbybrand"
        android:layout_below="@+id/buttonUnsortedlist"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="40dp" />
 
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Sorted by Price"
        android:id="@+id/buttonSortedbyprice"
        android:layout_marginTop="44dp"
        android:layout_below="@+id/buttonSortedbybrand"
        android:layout_alignStart="@+id/buttonSortedbybrand" />
 
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Filter Results"
        android:id="@+id/buttonFilterresults"
        android:layout_below="@+id/buttonSortedbyprice"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="40dp" />
</RelativeLayout>

  • 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.

MainActivity.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
package com.example.manish.jsonfilterapp;
 
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
 
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
 
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
 
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
 
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
 
 
    Button buttonUnsortedlist,buttonSortedbybrand,buttonSortedbyprice,buttonFilterresults;
    ProgressDialog progressDialog;
    TextView textView;  SharedPreferences sharedPreferences;
    String URL = "Your URL for getData.php";
    String mn;
    LaptopAdapter laptopAdapter;
    ArrayList<Laptop> laptopList= new ArrayList<Laptop>();
    String jsonString;
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
 
        progressDialog = new ProgressDialog(this);
        buttonFilterresults = (Button) findViewById(R.id.buttonFilterresults);
        buttonSortedbybrand = (Button) findViewById(R.id.buttonSortedbybrand);
        buttonSortedbyprice = (Button) findViewById(R.id.buttonSortedbyprice);
        buttonUnsortedlist = (Button) findViewById(R.id.buttonUnsortedlist);
 
        buttonSortedbybrand.setOnClickListener(this);
        buttonUnsortedlist.setOnClickListener(this);
        buttonFilterresults.setOnClickListener(this);
        buttonSortedbyprice.setOnClickListener(this);
        getLaptops();
        sharedPreferences = getSharedPreferences("SHARED_PREF_NAME", Context.MODE_PRIVATE);
 
 
 
    }
 
    @Override
    public void onClick(View v) {
        if(v==buttonUnsortedlist){
            startActivity(new Intent(this,UnsortedActivity.class));
        }
        if(v==buttonSortedbybrand){
 
            startActivity(new Intent(this,Sortedbybrand.class));
        }
        if(v==buttonSortedbyprice){
 
            startActivity(new Intent(this,Sortedbyprice.class));
        }
        if(v==buttonFilterresults){
 
            startActivity(new Intent(this,Filterresults.class));
        }
 
    }
 
    public void  getLaptops() {
        progressDialog.setMessage("Fetching data from the Server...");
        progressDialog.show();
 
        StringRequest stringRequest = new StringRequest(Request.Method.POST, URL,
 
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
 
                        progressDialog.dismiss();
 
                        Toast.makeText(MainActivity.this, "Data Successfully Fetched", Toast.LENGTH_SHORT).show();
                        try {
                            JSONObject js = new JSONObject(response);
 
                            JSONArray jsonArray = js.getJSONArray("laptops");
 
                            jsonString = jsonArray.toString();
 
 
                            SharedPreferences.Editor editor = sharedPreferences.edit();
 
                            editor.putString("jsonString",jsonString);
                            editor.apply();
 
 
 
                            JSONArray sortedJsonArray = new JSONArray();
                            List<JSONObject> jsonValues = new ArrayList<JSONObject>();
                            for (int i = 0; i < jsonArray.length(); i++) {
                                jsonValues.add(jsonArray.getJSONObject(i));
                            }
                            Collections.sort( jsonValues, new Comparator<JSONObject>() {
                                //You can change "Name" with "ID" if you want to sort by ID
                                private static final String KEY_NAME = "modelname";
 
                                @Override
                                public int compare(JSONObject a, JSONObject b) {
                                    String valA = new String();
                                    String valB = new String();
 
                                    try {
                                        valA = (String) a.get(KEY_NAME);
                                        valB = (String) b.get(KEY_NAME);
                                    }
                                    catch (JSONException e) {
                                        //do something
                                    }
 
                                    return valA.compareTo(valB);
                                    //if you want to change the sort order, simply use the following:
                                    //return -valA.compareTo(valB);
                                }
                            });
 
                            for (int i = 0; i < jsonArray.length(); i++) {
                                sortedJsonArray.put(jsonValues.get(i));
                            }
 
 
 
 
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
 
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
 
                    }
                });
 
        RequestQueue request = Volley.newRequestQueue(this);
        request.add(stringRequest);
    }
}

  • 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.

list_layout.xml
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent"
    >
 
 
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/textViewModelname"/>
 
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/textViewRam"/>
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/textViewOs"/>
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/textViewPrice"/>
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/textViewScreensize"/>
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/textViewBrand"/>
</LinearLayout>

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

Laptop
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
package com.example.manish.jsonfilterapp;
 
/**
* Created by Manish on 9/4/2016.
*/
public class Laptop {
 
    public  String modelname,ram,os,price,screensize,brand;
 
    Laptop(String modelname, String ram, String os, String price, String screensize, String brand){
 
       this.modelname = modelname;
       this.ram = ram;
       this.os = os;
       this.price = price;
       this.screensize = screensize;
       this.brand = brand;
   }
 
    public String getModelname() {
        return modelname;
    }
 
    public String getRam() {
        return ram;
    }
 
    public String getOs() {
        return os;
    }
 
    public String getPrice() {
        return price;
    }
 
    public String getScreensize() {
        return screensize;
    }
 
    public String getBrand() {
        return brand;
    }
}

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

LaptopAdapter
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
package com.example.manish.jsonfilterapp;
 
import android.app.Activity;
import android.content.Intent;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.TextView;
 
import java.util.ArrayList;
 
/**
* Created by Manish on 9/4/2016.
*/
 
 
    public class LaptopAdapter extends ArrayAdapter<Laptop>
    {
        Activity activity;
        int layoutResourceId;
        ArrayList<Laptop> data=new ArrayList<Laptop>();
        Laptop laptop;
 
        public LaptopAdapter(Activity activity, int layoutResourceId, ArrayList<Laptop> data) {
            super(activity, layoutResourceId, data);
 
            this.activity=activity;
            this.layoutResourceId=layoutResourceId;
            this.data=data;
 
 
        }
 
 
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
 
            View row=convertView;
            LaptopHolder holder=null;
 
 
            if(row==null)
            {
 
                LayoutInflater inflater=LayoutInflater.from(activity);
 
                row=inflater.inflate(layoutResourceId,parent,false);
 
                holder=new LaptopHolder();
 
                holder.modelname= (TextView) row.findViewById(R.id.textViewModelname);
                holder.ram= (TextView) row.findViewById(R.id.textViewRam);
                holder.os= (TextView) row.findViewById(R.id.textViewOs);
                holder.price= (TextView) row.findViewById(R.id.textViewPrice);
                holder.screensize= (TextView) row.findViewById(R.id.textViewScreensize);
                holder.brand= (TextView) row.findViewById(R.id.textViewBrand);
 
 
 
                row.setTag(holder);
 
            }
            else
            {
                holder= (LaptopHolder) row.getTag();
            }
 
            laptop=data.get(position);
 
            holder.modelname.setText(laptop.getModelname());
            holder.ram.setText(laptop.getRam());
            holder.os.setText(laptop.getOs());
            holder.price.setText(laptop.getPrice());
            holder.screensize.setText(laptop.getScreensize());
            holder.brand.setText(laptop.getBrand());
 
 
            return row;
        }
 
 
        class LaptopHolder
        {
 
            TextView modelname,ram,os,price,screensize,brand;
 
 
        }
 
    }

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.

activity_unsorted.xml
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
<?xml version="1.0" encoding="utf-8"?>
<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="com.example.manish.jsonfilterapp.UnsortedActivity">
 
 
 
    <ListView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/unsortedlist"
        android:layout_alignParentBottom="true"
        android:layout_alignParentRight="true"
        android:layout_alignParentEnd="true"
        />
 
 
 
</RelativeLayout>

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

UnsortedActivity.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
package com.example.manish.jsonfilterapp;
 
import android.app.ProgressDialog;
import android.content.Context;
import android.content.SharedPreferences;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
 
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
 
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
 
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Set;
 
public class UnsortedActivity extends AppCompatActivity {
 
 
    ListView unsortedlist;
    LaptopAdapter laptopAdapter;String mn;
    ArrayList<Laptop> laptopList= new ArrayList<Laptop>();
    ArrayList<String> jsonString = new ArrayList<String>();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_unsorted);
 
        unsortedlist = (ListView) findViewById(R.id.unsortedlist);
 
 
        SharedPreferences sp = getSharedPreferences("SHARED_PREF_NAME", Context.MODE_PRIVATE);
        String jsonString = sp.getString("jsonString",null);
        JSONArray jsonArray = null;
        try {
            jsonArray = new JSONArray(jsonString);
        } catch (JSONException e) {
            e.printStackTrace();
        }
 
        for(int i=0;i<jsonArray.length();i++){
 
 
        try{
 
        JSONObject jsonObject = jsonArray.getJSONObject(i);
        String modelname = "Modelname:" + jsonObject.getString("modelname");
        mn = 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);
 
}catch (Exception e){
 
 
}
        }
 
 
        laptopAdapter=new LaptopAdapter(UnsortedActivity.this,R.layout.list_layout, laptopList);
 
        unsortedlist.setAdapter(laptopAdapter);
 
        laptopAdapter.notifyDataSetChanged();
 
 
 
 
    }
 
}

  • 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.

activity_sortedbybrand.xml
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
<?xml version="1.0" encoding="utf-8"?>
<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="com.example.manish.jsonfilterapp.Sortedbybrand">
 
 
 
    <ListView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/unsortedlist"
        android:layout_alignParentBottom="true"
        android:layout_alignParentRight="true"
        android:layout_alignParentEnd="true"
        />
 
</RelativeLayout>

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

Sortedbybrand.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
package com.example.manish.jsonfilterapp;
 
import android.content.Context;
import android.content.SharedPreferences;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ListView;
 
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
 
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
 
public class Sortedbybrand extends AppCompatActivity {
 
    ListView unsortedlist;
    LaptopAdapter laptopAdapter;String mn;
    ArrayList<Laptop> laptopList= new ArrayList<Laptop>();
    String jsonString; JSONArray jsonArray;
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_sortedbybrand);
 
        unsortedlist = (ListView) findViewById(R.id.unsortedlist);
 
//data being retreived through SharedPreferences .
        SharedPreferences sharedPreferences = getSharedPreferences("SHARED_PREF_NAME", Context.MODE_PRIVATE);
        jsonString = sharedPreferences.getString("jsonString",null);
 
//conversion of jsonString to jsonArray
        try {
             jsonArray = new JSONArray(jsonString);
        } catch (JSONException e) {
            e.printStackTrace();
        }
 
//sortedJSONArray would contain the sorted JSONObjects.
            JSONArray sortedJsonArray = new JSONArray();
            List<JSONObject> jsonValues = new ArrayList<JSONObject>();
 
            for (int i = 0; i < jsonArray.length(); i++) {
                try {
                    jsonValues.add(jsonArray.getJSONObject(i));
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
//The following section feeds the sorted data into the sortedJsonArray
            Collections.sort( jsonValues, new Comparator<JSONObject>() {
                //You can change "brand" with "price" if you want to sort by price
                private static final String KEY_NAME = "brand";
 
                @Override
                public int compare(JSONObject a, JSONObject b) {
                    String valA = new String();
                    String valB = new String();
 
                    try {
                        valA = (String) a.get(KEY_NAME);
                        valB = (String) b.get(KEY_NAME);
                    }
                    catch (JSONException e) {
                        //do something
                    }
 
                    return valA.compareTo(valB);
                    //if you want to change the sort order, simply use the following:
                    //return -valA.compareTo(valB);
                }
            });
 
            for (int i = 0; i < jsonArray.length(); i++) {
                sortedJsonArray.put(jsonValues.get(i));
            }
 
 
        for(int i=0;i<sortedJsonArray.length();i++){
 
            try {
                JSONObject jsonObject = sortedJsonArray.getJSONObject(i);
                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");
//The data from each JSONObject is copied to an Object of Class Laptop
                Laptop laptop = new Laptop(modelname,ram,os,price,screensize,brand);
//The objects of class Laptop are thereby added into the ArrayList i.e laptopList. This will be used
//as we'll set the adapter to the listView.
                laptopList.add(laptop);
 
            } catch (JSONException e) {
                e.printStackTrace();
            }
 
 
//the list_layout and laptopList are passed to the Adapter here.
            laptopAdapter=new LaptopAdapter(Sortedbybrand.this,R.layout.list_layout, laptopList);
 
            unsortedlist.setAdapter(laptopAdapter);
 
            laptopAdapter.notifyDataSetChanged();
        }
 
    }
}

  • 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.

activity_sortedbyprice
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<?xml version="1.0" encoding="utf-8"?>
<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="com.example.manish.jsonfilterapp.Sortedbyprice">
 
    <ListView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/unsortedlist"
        android:layout_alignParentBottom="true"
        android:layout_alignParentRight="true"
        android:layout_alignParentEnd="true"
        />
 
</RelativeLayout>

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

Sortedbyprice.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
package com.example.manish.jsonfilterapp;
 
import android.content.Context;
import android.content.SharedPreferences;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ListView;
 
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
 
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
 
public class Sortedbybrand extends AppCompatActivity {
 
    ListView unsortedlist;
    LaptopAdapter laptopAdapter;String mn;
    ArrayList<Laptop> laptopList= new ArrayList<Laptop>();
    String jsonString; JSONArray jsonArray;
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_sortedbybrand);
 
        unsortedlist = (ListView) findViewById(R.id.unsortedlist);
 
//data being retreived through SharedPreferences .
        SharedPreferences sharedPreferences = getSharedPreferences("SHARED_PREF_NAME", Context.MODE_PRIVATE);
        jsonString = sharedPreferences.getString("jsonString",null);
 
//conversion of jsonString to jsonArray
        try {
             jsonArray = new JSONArray(jsonString);
        } catch (JSONException e) {
            e.printStackTrace();
        }
 
//sortedJSONArray would contain the sorted JSONObjects.
            JSONArray sortedJsonArray = new JSONArray();
            List<JSONObject> jsonValues = new ArrayList<JSONObject>();
 
            for (int i = 0; i < jsonArray.length(); i++) {
                try {
                    jsonValues.add(jsonArray.getJSONObject(i));
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
//The following section feeds the sorted data into the sortedJsonArray
            Collections.sort( jsonValues, new Comparator<JSONObject>() {
                //You can change "brand" with "price" if you want to sort by price
                private static final String KEY_NAME = "brand";
 
                @Override
                public int compare(JSONObject a, JSONObject b) {
                    String valA = new String();
                    String valB = new String();
 
                    try {
                        valA = (String) a.get(KEY_NAME);
                        valB = (String) b.get(KEY_NAME);
                    }
                    catch (JSONException e) {
                        //do something
                    }
 
                    return valA.compareTo(valB);
                    //if you want to change the sort order, simply use the following:
                    //return -valA.compareTo(valB);
                }
            });
 
            for (int i = 0; i < jsonArray.length(); i++) {
                sortedJsonArray.put(jsonValues.get(i));
            }
 
 
        for(int i=0;i<sortedJsonArray.length();i++){
 
            try {
                JSONObject jsonObject = sortedJsonArray.getJSONObject(i);
                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");
//here,data from each JSONObject is copied to an Object of Class Laptop
                Laptop laptop = new Laptop(modelname,ram,os,price,screensize,brand);
//The objects of class Laptop are thereby added into the ArrayList i.e laptopList. This will be used
//as we'll set the adapter to the listView.
                laptopList.add(laptop);
 
            } catch (JSONException e) {
                e.printStackTrace();
            }
 
 
//the list_layout and laptopList are passed to the Adapter here.
            laptopAdapter=new LaptopAdapter(Sortedbybrand.this,R.layout.list_layout, laptopList);
 
            unsortedlist.setAdapter(laptopAdapter);
 
            laptopAdapter.notifyDataSetChanged();
        }
 
    }
}

  • 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.

activity_filterresults.xml
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<?xml version="1.0" encoding="utf-8"?>
<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="com.example.manish.jsonfilterapp.Filterresults">
 
    <ListView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/unsortedlist"
        android:layout_alignParentBottom="true"
        android:layout_alignParentRight="true"
        android:layout_alignParentEnd="true"
        />
 
</RelativeLayout>

  • 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.

Filterresults.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
package com.example.manish.jsonfilterapp;
 
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ListView;
import android.widget.Toast;
 
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
 
import java.util.ArrayList;
 
public class Filterresults extends AppCompatActivity {
 
    ListView unsortedlist;
    LaptopAdapter laptopAdapter;String mn;
    ArrayList<Laptop> laptopList= new ArrayList<Laptop>();
    String jsonString; JSONArray jsonArray;
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_filterresults);
 
 
        unsortedlist = (ListView) findViewById(R.id.unsortedlist);
//here, the data in String is being retreived.
        SharedPreferences sharedPreferences = getSharedPreferences("SHARED_PREF_NAME", Context.MODE_PRIVATE);
        jsonString = sharedPreferences.getString("jsonString",null);
//here, string to jsonArray conversion takes place
        try {
            jsonArray = new JSONArray(jsonString);
        } catch (JSONException e) {
            e.printStackTrace();
        }
 
        for(int i=0;i<jsonArray.length();i++){
 
 
            try {
                JSONObject jsonObject = jsonArray.getJSONObject(i);
                String price1= jsonObject.getString("price");
                //simple if statement allows only those jsonObjects to be added the laptopList where price is less than 40000.
                if(Integer.parseInt(price1)<40000) {
 
                    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);
                }
 
 
                } catch (JSONException e) {
                e.printStackTrace();
            }
            Toast.makeText(Filterresults.this,"Filtered as Price less than 40000", Toast.LENGTH_SHORT).show();
 
 
            laptopAdapter=new LaptopAdapter(Filterresults.this,R.layout.list_layout, laptopList);
 
            unsortedlist.setAdapter(laptopAdapter);
 
            laptopAdapter.notifyDataSetChanged();
 
 
        }
 
        }
    }

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

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

  • 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.

 Filter JSON Source Download 

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.

Sharing is Caring:

  • Tweet
  • Share on Tumblr
  • More
  • Pocket
  • Print
  • Email

Related

Filed Under: Android Advance, Android Application Development Tagged With: filter json android example, filter json data, sort and filter json

About Manish Kumar

Hello, I am Manish Kumar. I am a B.Tech Student at NIT Jamshedpur. Fortunately, I find myself quite passionate about Computers and Technology. Android is my most recent Crush.

Comments

  1. Ashok says

    September 7, 2016 at 12:54 pm

    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
    • Manish Kumar says

      September 7, 2016 at 2:44 pm

      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. Ness Tyagi says

    October 6, 2016 at 6:00 am

    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
    • Manish Kumar says

      November 2, 2016 at 6:36 pm

      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. Alexandre Conceição says

    October 16, 2016 at 3:28 am

    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
    • Manish Kumar says

      November 2, 2016 at 6:28 pm

      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
      • Alexandre Conceição says

        November 10, 2016 at 9:31 pm

        Ok

        But, where I implemente this method?

        Sorry, but I’m beginner.

        Reply
  4. Fotis Pegios says

    November 2, 2016 at 8:29 am

    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. Nikhil says

    February 24, 2017 at 1:46 pm

    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. ana says

    March 8, 2017 at 5:25 pm

    I want search results to be clickable and on click detailes presented. How can i do that?

    Reply
  7. Akeem says

    September 12, 2017 at 4:12 pm

    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
  8. Sean Grove says

    November 20, 2017 at 11:29 am

    Hi there.
    Really need you to contact me. need your expert help.

    Reply
  9. Pasquale says

    June 3, 2018 at 7:42 am

    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 Reply to Alexandre Conceição Cancel reply

Your email address will not be published. Required fields are marked *

Search




Download our Android App

Simplified Coding in Google Play

About Me

Belal Khan

Hello I am Belal Khan, founder and owner of Simplified Coding. I am currently pursuing MCA from St. Xavier's College, Ranchi. I love to share my knowledge over Internet.

Connect With Me

Follow @codesimplified
Simplified Coding

Popular Tutorials

  • Android JSON Parsing – Retrieve From MySQL Database
  • Android Login and Registration Tutorial with PHP MySQL
  • Android Volley Tutorial – Fetching JSON Data from URL
  • Android Upload Image to Server using Volley Tutorial
  • Android TabLayout Example using ViewPager and Fragments
  • Retrieve Data From MySQL Database in Android using Volley
  • Firebase Cloud Messaging Tutorial for Android
  • Android Volley Tutorial – User Registration and Login
  • Android Upload Image to Server Using PHP MySQL
  • Android Navigation Drawer Example using Fragments




About Simplified Coding

Simplified Coding is a blog for all the students learning programming. We are providing various tutorials related to programming and application development. You can get various nice and simplified tutorials related to programming, app development, graphics designing and animation. We are trying to make these things simplified and entertaining. We are writing text tutorial and creating video and visual tutorials as well. You can check about the admin of the blog here and check out our sitemap

Quick Links

  • Advertise Here
  • Privacy Policy
  • Disclaimer
  • About
  • Contact Us
  • Write for Us

Categories

Android Advance Android Application Development Android Beginners Android Intermediate Ionic Framework Tutorial JavaScript Kotlin Android Others PHP Advance PHP Tutorial React Native

Copyright © 2017 · Simplified Coding· All rights Reserved. And Our Sitemap.All Logos & Trademark Belongs To Their Respective Owners·

loading Cancel
Post was not sent - check your email addresses!
Email check failed, please try again
Sorry, your blog cannot share posts by email.