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.
- 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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
<?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
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 |
<?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
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 |
<?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
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 |
<?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.
1 2 3 |
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.
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 |
<?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.
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 167 168 |
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.
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 |
<?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.
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 |
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.
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 |
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.
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 |
<?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.
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 |
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.
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.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.
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 |
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.
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.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.
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 |
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.
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.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.
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 |
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.
1 2 3 |
<uses-permission android:name="android.permission.INTERNET" /> |
- That’s it:). Run the app the wait to see the Toast saying data fetched Successfully.
- If you are facing troubles then download my source code for this filter JSON project from below.
[sociallocker id=1372] Filter JSON Source Download [/sociallocker]
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.