JSON stands for JavaScript Object Notation.It is an independent data exchange format and is the best alternative for XML. JSON is very light weight, structured, easy to parse and much human readable.
In this tutorial we are going to learn how to parse JSON in android.
In this tutorial we will use Http Requests since we will work on server. So, if you are not familiar how to use Http Requests then you can check Http Request tutorial.
An JSON file consist of many components. Here is the table defining the components of an JSON file and their description −
Component | Description |
---|---|
Array([) | In a JSON file , square bracket ([) represents a JSON array. |
Objects({) | In a JSON file, curly bracket ({) represents a JSON object. |
Key | A JSON object contains a key that is just a string. Pairs of key/value make up a JSON object. |
Value | Each key has a value that could be string , integer or double e.t.c. |
Following is the sample JSON that we are going to parse in this tutorial. This is very simple JSON which gives us list of information like name, location and phone number array.
In this tutorial we will parse data from local json file and also from server file.
1. Local JSON file that will be in .txt or .json extension kept in assests folder.
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 |
{ "data": [ { "name": "Andrew", "location": "India", "phone": [ 8899002211, 7799881122 ] }, { "name": "Phil", "location": "Pune", "phone": [ 9900112211, 9881122112 ] }, { "name": "AndroHub", "location": "Bangalore", "phone": [ 9881221122, 9881122333 ] } ] } |
2. Server file that is my blogs recent posts JSON data.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
{ "status": "ok", "count": 10, "count_total": 39, "pages": 4, "posts": [ { "id": 474, "type": "post", "slug": "android-date-and-time-picker-dialog", "url": "https://androhub.com/android-date-and-time-picker-dialog/", "status": "publish", "title": "Android Date and Time Picker Dialog", "title_plain": "Android Date and Time Picker Dialog", "content": "<strong>Date Picker Dialog</strong> and.............", "excerpt": null, "date": "2015-07-15 16:41:27", "modified": "2015-07-15 16:41:27", "categories": [ . . . . . |
In general all the JSON nodes will start with a square bracket or with a curly bracket. The difference between [ and { is, the square bracket ([) represents starting of an JSONArray node whereas curly bracket ({) represents JSONObject. So while accessing these nodes we need to call appropriate method to access the data.
If your JSON node starts with [, then we should use getJSONArray() method. Same as if the node starts with {, then we should use getJSONObject() method.
There are several methods provided by JSON class for better parsing JSON files. These methods are listed below −
Method | Description |
---|---|
get(String name) | This method just Returns the value but in the form of Object type. |
getBoolean(String name) | This method returns the boolean value specified by the key. |
getDouble(String name) | This method returns the double value specified by the key. |
getInt(String name) | This method returns the integer value specified by the key. |
getLong(String name) | This method returns the long value specified by the key. |
length() | This method returns the number of name/value mappings in this object. |
names() | This method returns an array containing the string names in this object. |
In this tutorial, we are going to learn how to Parse JSON data from local Json file and Server Json data.
1. Create a new project in Eclipse by navigating to File ⇒ New Android ⇒ Application Project and fill required details. (I kept my main activity name as MainActivity.java).
2. As we are fetching the JSON by making HTTP calls, we need to add INTERNET permission in our AndroidManifest.xml file. Open AndroidManifest.xml and add the following permission.
1 |
<uses-permission android:name="android.permission.INTERNET" /> |
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 |
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.json_demo" android:versionCode="1" android:versionName="1.0" > <uses-sdk android:minSdkVersion="8" android:targetSdkVersion="22" /> <!-- Internet permission to fetch data from server and this permission is mandatory while working with server --> <uses-permission android:name="android.permission.INTERNET" /> <application android:allowBackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" > <activity android:name=".MainActivity" android:label="@string/app_name" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest> |
3. Open res ⇒ values ⇒ strings.xml and add below string values. This are some strings that i used in this tutorial.
1 2 3 4 5 6 7 8 9 10 11 |
<?xml version="1.0" encoding="utf-8"?> <resources> <string name="app_name">JSONParser Demo</string> <string name="hello_world">Hello world!</string> <string name="action_settings">Settings</string> <string name="local_file">Read JSON Data from Local File</string> <string name="server_file">Read JSON Data from Server</string> <string name="show_data">Parsed JSON Data</string> </resources> |
4. Now, for local Json file create a dummyjson.txt or dummyjson.json and copy from its location and paste it under assests directory.
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 |
{ "data": [ { "name": "Andrew", "location": "India", "phone": [ 8899002211, 7799881122 ] }, { "name": "Phil", "location": "Pune", "phone": [ 9900112211, 9881122112 ] }, { "name": "AndroHub", "location": "Bangalore", "phone": [ 9881221122, 9881122333 ] } ] } |
5. For reading this local JSON file from assests folder i had created a method that will read the data from text file and return me as String.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
private String loadJSONFromAsset() {// this method will read the text file // from assests folder and return the // file in string format String json = null; try { InputStream is = getAssets().open("your file name like dummyjson.txt");// int size = is.available(); byte[] buffer = new byte[size]; is.read(buffer); is.close(); json = new String(buffer, "UTF-8"); } catch (IOException ex) { ex.printStackTrace(); return null; } return json; } |
6. Open your activity_main.xml file and add this code for basic layout of this tutorial. In this layout we have two buttons for executing different json task and one listview for displaying parsed data.
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 |
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="fill_parent" android:layout_height="fill_parent" android:background="#d3d3d3" android:orientation="vertical" > <Button android:id="@+id/read_data_from_localfile" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_gravity="center_horizontal" android:layout_margin="5dp" android:gravity="center" android:padding="10dp" android:text="@string/local_file" /> <Button android:id="@+id/read_data_from_server" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_gravity="center_horizontal" android:layout_margin="5dp" android:gravity="center" android:padding="5dp" android:text="@string/server_file" /> <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_marginLeft="5dp" android:padding="7dp" android:id="@+id/parsed_showdata_text" android:text="@string/show_data" android:textColor="#000000" android:textSize="15sp" /> <View android:layout_width="fill_parent" android:layout_height="1px" android:layout_marginLeft="5dp" android:layout_marginRight="5dp" android:background="#ffffff" /> <ListView android:id="@+id/show_jsondata" android:layout_width="fill_parent" android:layout_height="fill_parent" android:layout_marginTop="2dp" > </ListView> </LinearLayout> |
7. Now, for showing parsed data we need custom listview and for custom listview we need custom layout. So create a new layout naming custom_listview.xml and add the following code to it.
You can see how to make Simple and Custom ListView if you are new.
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 |
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="wrap_content" android:background="#ffffff" android:orientation="vertical" android:padding="5dp" > <TextView android:id="@+id/name" android:layout_width="fill_parent" android:layout_height="wrap_content" android:padding="5dp" android:singleLine="true" android:text="Surender kumar" android:textColor="#000000" android:textSize="17sp" /> <TextView android:id="@+id/location" android:layout_width="fill_parent" android:layout_height="wrap_content" android:paddingLeft="5dp" android:paddingRight="5dp" android:singleLine="true" android:text="Bangalore" android:textColor="#00ff00" android:textSize="15sp" /> <TextView android:id="@+id/phone_number" android:layout_width="fill_parent" android:layout_height="wrap_content" android:paddingLeft="5dp" android:paddingRight="5dp" android:paddingTop="3dp" android:singleLine="false" android:text="998589569" android:textColor="#ff00" android:textSize="14sp" /> </LinearLayout> |
8. Now, we have to create a class that will be the setter and getter for parsed data for custom ListView. In this class i had set the setter and getter for both local json file and server json file, so that we can used as per our need.
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 |
package com.json_demo; public class JSONData_Model { /** Local Json Parser Getter and Setter **/ private String name, location; private String[] phoneNumber; public JSONData_Model(String name, String location, String[] phoneNumber) { this.name = name; this.location = location; this.phoneNumber = phoneNumber; } public String getName() { return name; } public String getLocation() { return location; } public String[] getPhoneNumber() { return phoneNumber; } /** ---------------------------------------------- **/ /** Sever Json Parser Getter and Setter **/ private String date, status, title; public JSONData_Model(String title, String status, String date) { this.date = date; this.status = status; this.title = title; } public String getDate() { return date; } public String getTitle() { return title; } public String getStatus() { return status; } /** ----------------------------------------------------- **/ } |
9. For custom adapter create a class naming JSONData_Adapter.java. This will inflate custom layout over listview. In this i had used if and else for determining from which the adapter is called like “LOCAL” or “SERVER”. And according to it i displayed data.
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.json_demo; import java.util.ArrayList; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.TextView; public class JSONData_Adapter extends BaseAdapter { private Context context; private ArrayList<JSONData_Model> jsonList; private String from = "";// "from" variable is used to check from which // parser the adapter is called public JSONData_Adapter(Context context, ArrayList<JSONData_Model> arrayList, String from) { this.context = context; this.jsonList = arrayList; this.from = from; } @Override public int getCount() { return jsonList.size(); } @Override public JSONData_Model getItem(int position) { return jsonList.get(position); } @Override public long getItemId(int position) { return position; } @Override public View getView(int position, View view, ViewGroup parent) { LayoutInflater inflater = (LayoutInflater) context .getSystemService(Context.LAYOUT_INFLATER_SERVICE); ViewHolder holder = null; if (view == null) { holder = new ViewHolder(); view = inflater.inflate(R.layout.custom_listview, parent, false); holder.name = (TextView) view.findViewById(R.id.name); holder.location = (TextView) view.findViewById(R.id.location); holder.phone = (TextView) view.findViewById(R.id.phone_number); // If adapter is called from local json parser then get the data // from local json parser getter if (from.equalsIgnoreCase("Local")) { holder.name.setText(jsonList.get(position).getName()); holder.location.setText(jsonList.get(position).getLocation()); String[] contactNumber = jsonList.get(position) .getPhoneNumber(); String contact = ""; for (int i = 0; i < contactNumber.length; i++) { contact += contactNumber[i] + " "; } holder.phone.setText(contact); } // Else If adapter is called from server json parser then get the // data from server json parser getter else if (from.equalsIgnoreCase("Server")) { holder.name.setText(jsonList.get(position).getTitle()); holder.location.setText(jsonList.get(position).getStatus()); holder.phone.setText(jsonList.get(position).getDate()); } // Else display error else { holder.name.setText("Error in parsing."); } view.setTag(holder); } else { holder = (ViewHolder) view.getTag(); } return view; } // ViewHolder to hold the views private class ViewHolder { TextView name, location, phone; } } |
10. Now for fetching JSON data we have to parse the data in proper format. First check the start of Json data i.e. ‘[‘ or ‘{‘ and parse according to it.
So, if Json data is starting from ‘{‘ means this is JSON Object then use :
1 |
JSONObject jsonObject = new JSONObject("data"); |
If Json data is starting from ‘[‘ means JSON Array then use :
1 |
JSONArray postsArray = new JSONArray("data"); |
For Parsing JSON data from Local file i used this method :
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 |
private ArrayList<JSONData_Model> ReadDataFromLocalFile() { ArrayList<JSONData_Model> jsonArrayList = new ArrayList<JSONData_Model>(); try { JSONObject jsonObject = new JSONObject(loadJSONFromAsset());// JsonObject // get // from // local // assests // text // file JSONArray jsonArray = jsonObject.getJSONArray("data");// "data" // keyvalue // contains // the // jsonarray // Check if jsonArray is null or not and length should be greater // than 0 if (jsonArray != null) { if (jsonArray.length() > 0) { // Loop to all jsonarray items for (int i = 0; i < jsonArray.length(); i++) { String[] contactNumberArray = null;// String array that // will store phone // numbers JSONObject newJsonObject = jsonArray.getJSONObject(i);// Now // jsonarray // contains // jsonObject // so // it // should // pe // parsed // again // jsonobject String name = newJsonObject.getString("name");// "name" // keyvalue // contain // name String location = newJsonObject.getString("location");// "location" // keyvalue // conatin // location String contact_number = newJsonObject .getString("phone");// "phone" keyvalue conatins // phonearray JSONArray phoneArray = new JSONArray(contact_number);// so // the // contact_number // string // will // parse // into // jsonArray if (phoneArray.length() > 0) { contactNumberArray = new String[phoneArray.length()]; for (int j = 0; j < phoneArray.length(); j++) { contactNumberArray[j] = phoneArray.getString(j);// string // array // will // store // the // number // array } } jsonArrayList.add(new JSONData_Model(name, location, contactNumberArray));// finally add the data to // arrayList } } } } catch (JSONException e) { e.printStackTrace(); // If an exception occurs the arraylist will return null return null; } return jsonArrayList; } |
Similarly we can parse the Server JSON data.
11. Finally add the following code to your MainActivity.java. In this activity I used two different methods for loading JSON data from Local file and from Server file. And I used AsyncTask for processing JSON data. I had added comments to each line to make it more understandable.
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 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 |
package com.json_demo; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.util.EntityUtils; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import android.app.ProgressDialog; import android.content.Context; import android.os.AsyncTask; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.ListView; import android.widget.TextView; public class MainActivity extends AppCompatActivity implements OnClickListener { private static Button localFile, serverData; private static ListView showParsedData; private static TextView showdatatext; private static JSONData_Adapter adapter; private static String call_url = "https://androhub.com/api/get_recent_posts/";// Call // url // that // contain // json // data // IDs to for both type of parsers private static final int LocalFileId = 0; private static final int ServerFileID = 1; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); init(); setListeners(); hideListView(); } // Initiaize all views in activity private void init() { localFile = (Button) findViewById(R.id.read_data_from_localfile); serverData = (Button) findViewById(R.id.read_data_from_server); showParsedData = (ListView) findViewById(R.id.show_jsondata); showdatatext = (TextView) findViewById(R.id.parsed_showdata_text); } // Set Listeners on all three buttons private void setListeners() { localFile.setOnClickListener(this); serverData.setOnClickListener(this); } // Show listview and text private void showListView() { showdatatext.setVisibility(View.VISIBLE); showParsedData.setVisibility(View.VISIBLE); } // Hide listview and text private void hideListView() { showdatatext.setVisibility(View.GONE); showParsedData.setVisibility(View.GONE); } @Override public void onClick(View v) { switch (v.getId()) { case R.id.read_data_from_localfile: // Execute the Asynctask new ReadJSONDataTask(MainActivity.this, LocalFileId).execute(); break; case R.id.read_data_from_server: // Execute the Asynctask new ReadJSONDataTask(MainActivity.this, ServerFileID).execute(); break; } } // Background task to parse json Data private class ReadJSONDataTask extends AsyncTask<Void, Void, Void> { ProgressDialog pd; Context context; int id; // Id to execute the particular task in background like..local // or server ArrayList<JSONData_Model> jsonData = new ArrayList<JSONData_Model>();// Arraylist // for // setter public ReadJSONDataTask(Context context, int id) { this.context = context; this.id = id; } @Override protected void onPreExecute() { super.onPreExecute(); // Progress Dialog to show while task is running pd = new ProgressDialog(context); pd.setIndeterminate(true); pd.setCancelable(false); pd.setCanceledOnTouchOutside(false); pd.setMessage("Please wait..nLoading data"); pd.show(); } @Override protected Void doInBackground(Void... params) { // Check the send id and call the method according to it if (id == LocalFileId) { jsonData = ReadDataFromLocalFile(); } else if (id == ServerFileID) { jsonData = ReadDataFromServer(); } return null; } @Override protected void onPostExecute(Void result) { super.onPostExecute(result); // After background task the post method will set adapter over // listview if (jsonData != null) { // the adapter will be called according to send IDs if (id == LocalFileId) { adapter = new JSONData_Adapter(context, jsonData, "Local"); showParsedData.setAdapter(adapter); adapter.notifyDataSetChanged(); // Show listview after setting adapter showListView(); } else if (id == ServerFileID) { adapter = new JSONData_Adapter(context, jsonData, "Server"); showParsedData.setAdapter(adapter); adapter.notifyDataSetChanged(); showListView(); } } // After setting adapter the dilaog should be dismissed if (pd.isShowing()) pd.dismiss(); } } // Method that will return the jsonData in arraylist form after parsing data // from local text file private ArrayList<JSONData_Model> ReadDataFromLocalFile() { ArrayList<JSONData_Model> jsonArrayList = new ArrayList<JSONData_Model>(); try { JSONObject jsonObject = new JSONObject(loadJSONFromAsset());// JsonObject // get // from // local // assests // text // file JSONArray jsonArray = jsonObject.getJSONArray("data");// "data" // keyvalue // contains // the // jsonarray // Check if jsonArray is null or not and length should be greater // than 0 if (jsonArray != null) { if (jsonArray.length() > 0) { // Loop to all jsonarray items for (int i = 0; i < jsonArray.length(); i++) { String[] contactNumberArray = null;// String array that // will store phone // numbers JSONObject newJsonObject = jsonArray.getJSONObject(i);// Now // jsonarray // contains // jsonObject // so // it // should // pe // parsed // again // jsonobject String name = newJsonObject.getString("name");// "name" // keyvalue // contain // name String location = newJsonObject.getString("location");// "location" // keyvalue // conatin // location String contact_number = newJsonObject .getString("phone");// "phone" keyvalue conatins // phonearray JSONArray phoneArray = new JSONArray(contact_number);// so // the // contact_number // string // will // parse // into // jsonArray if (phoneArray.length() > 0) { contactNumberArray = new String[phoneArray.length()]; for (int j = 0; j < phoneArray.length(); j++) { contactNumberArray[j] = phoneArray.getString(j);// string // array // will // store // the // number // array } } jsonArrayList.add(new JSONData_Model(name, location, contactNumberArray));// finally add the data to // arrayList } } } } catch (JSONException e) { e.printStackTrace(); // If an exception occurs the arraylist will return null return null; } return jsonArrayList; } // Method that will return the jsonData in arraylist form after parsing data // from server private ArrayList<JSONData_Model> ReadDataFromServer() { ArrayList<JSONData_Model> jsonArrayList = new ArrayList<JSONData_Model>(); try { HttpClient client = new DefaultHttpClient();// Default httpclient // for request HttpGet httpget = new HttpGet(call_url);// HttpGet method to get the // data from URL HttpResponse response = client.execute(httpget);// HttpResponse // after executing // httpGet method // via client HttpEntity entity = response.getEntity();// Entity will get the // respone data String data = EntityUtils.toString(entity);// now finally entity // will convert into // string and data will // fetched in string // format Log.e("data", data);// Log for fetched data JSONObject jsonObject = new JSONObject(data);// Main data is in // JsonObject form if (jsonObject != null) { // The data contains many values but we'll parse only needed // values String posts = jsonObject.getString("posts");// Posts contains // the all posts JSONArray postsArray = new JSONArray(posts);// "posts" is in // array so // jsonArray will // used to parse if (postsArray != null) { if (postsArray.length() > 0) { for (int i = 0; i < postsArray.length(); i++) { JSONObject postsObject = postsArray .getJSONObject(i);// Now jsonArray contains // josnObject // Now this posts jsonObject contains many values // but we'll fetch required data String title = postsObject.getString("title");// "title" // contains // title // of // post String status = postsObject.getString("status");// "status" // contains // status // of // post String published_date = postsObject .getString("date");// "date" contains // published_date of // post jsonArrayList.add(new JSONData_Model(title, status, published_date));// finally add the data to // arrayList } } } } } catch (Exception e) { e.printStackTrace(); return null; } return jsonArrayList; } // Read file from assets folder and return data in json string private String loadJSONFromAsset() {// this method will read the text file // from assests folder and return the // file in string format String json = null; try { InputStream is = getAssets().open("dummyjson.txt"); int size = is.available(); byte[] buffer = new byte[size]; is.read(buffer); is.close(); json = new String(buffer, "UTF-8"); } catch (IOException ex) { ex.printStackTrace(); return null; } return json; } } |
12. Finally, all done – run the app and you will get the output as shown in video.
Thanks.
Subscribe to us and get the latest news.