How to display items from JSON file to spinner - java

I am trying to display a list on a spinner from a json file in asset folder. I found a tutorial but I think my format is wrong, please help!
also, will this process take time to load to the spinner if the list has up to 300 items?
here is my main activity
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Spinner spinner = (Spinner)findViewById(R.id.spinner);
ArrayList<String> items = getFood("food.json");
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.spinner_layout, R.id.txt, items);
spinner.setAdapter(adapter);
}
public ArrayList<String> getBanks(String fileName) {
JSONObject jsonObject = null;
try {
InputStream is = getResources().getAssets().open(fileName);
int size = is.available();
byte[] data = new byte[size];
is.read(data);
is.close();
String json = new String(data, "UTF-8");
jsonObject = new JSONObject(json);
if (jsonObject != null) {
for (int i = 0; i < jsonObject.length(); i++) {
JSONArray foodList = jsonObject.getJSONArray("data");
if(cList != null){
for(int j=0; i<cList.length(); j++){
JSONObject fList = foodList.getJSONObject(j);
String food_name = foodList.getString("name");
String food_code = foodList.getString("code");
}
}
}
}
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException je) {
je.printStackTrace();
}
return cList;
}
}
the structure of my response, saved as food.json
{
"status": "Successful",
"data": [
{
"code": "11",
"id": 1,
"name": "Apple"
},
{
"code": "22",
"id": 2,
"name": "Carrot"
},
{
"code": "33",
"id": 3,
"name": "Diamonds"
},
{
"code": " 44",
"id": 4,
"name": "Eggs"
},
{
"code": "55",
"id": 5,
"name": "Fish"
}
],
"message": "Action was successful"
}

For this task use jackson-jr (Size is very small and faster than other libraries like Gson, Jasckson core ...)
Considering Performance, it is the best option than other.
Now let's go to the solution
First import jackson-jr library to Your android project
implementation 'com.fasterxml.jackson.jr:jackson-jr-objects:2.10.0'
then create two model classes like this
public class Food {
private String status;
private List<Data> data;
private String message;
public Food() {
}
//getters and setters
}
public class Data {
private String code;
private int id;
private String name;
public Data() {
}
//getters and setters
}
Final step get data objects
import com.fasterxml.jackson.jr.ob.JSON;
private List<Data> getData() {
List<Data> data = null;
try {
// give your json file as a inputstream
//InputStream is = getResources().openRawResource(R.raw.food);
InputStream is = getResources().getAssets().open("food.json");
Food bean = JSON.std.beanFrom(Food.class, is);
data = bean.getData();
} catch (IOException e) {
e.printStackTrace();
}
return data;
}
You can do whatever after that using this list of Data...
For passing only food names
There are a lot of ways. Here is a simple way
in your onCreate method use below code
List<Data> data = getData();
List<String> foodNames = getFoodNamesFromData(data);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.spinner_layout, R.id.txt, foodNames);
// Your usual codes
and here is the getFoodNamesFromData() method
private List<String> getFoodNamesFromData(List<Data> dataList) {
List<String> foodNames = new ArrayList<>();
for(Data data :dataList){
String foodName = data.getName();
foodNames.add(foodName);
}
return foodNames;
}
Happy coding!!!

Why don't you create a custom class for following structure
{
"code": "11",
"id": 1,
"name": "Apple"
}
So that you can use GSON library to parse json into a list using TypeToken and it'll be easy to pass to a adapter.
You can do like,
List<YourClass> yourClass = Gson().fromJson(json.toString(),new TypeToken<List<YourClass>>(){}.getType())

Related

Gson append new object array to existing JSON file

i need some help appending new arrays into a existing file. I have a JSON file like this:
[
{
"name": "any",
"address": {
"street": "xxxx",
"number": 1
},
"email": "teste#gmail.com"
}
]
I want to insert new array, so my file will be like this:
[
{
"name": "any",
"address": {
"street": "xxxx",
"number": 1
},
"email": "test#gmail.com"
},
{
"name": "any2",
"address": {
"street": "yyyyy",
"number": 2
},
"email": "test2#gmail.com"
}
]
Here's my code:
Gson gson = new GsonBuilder().setPrettyPrinting().create();
ArrayList<Person> ps = new ArrayList<Person>();
// .... reading entries...
ps.add(new Person(name, address, email));
String JsonPerson = gson.toJson(ps);
File f = new File("jsonfile");
if (f.exists() && !f.isDirectory()) {
JsonReader jsonfile = new JsonReader(new FileReader("jsonfile"));
JsonParser parser = new JsonParser();
JsonElement element = parser.parse(jsonfile);
//here goes the new entry?
try (FileWriter file = new FileWriter("pessoas.json")) {
file.write(JsonPessoa);
file.close();
} catch (Exception e) {
e.printStackTrace();
}
So, what's the best way to do this?
Thanks in advance.
Gson really shines when combined with Pojos, so my suggestion would be use of mapped pojos. Consider below two classes.
public class Contact {
#SerializedName("address")
private Address mAddress;
#SerializedName("email")
private String mEmail;
#SerializedName("name")
private String mName;
// getters and setters...
}
public class Address {
#SerializedName("number")
private Long mNumber;
#SerializedName("street")
private String mStreet;
// getters and setters...
}
Read JSON and add new contact and convert it back to JSON, It also works for other way around seamlessly. Similarly you can use this approach for solve many use cases. Pass json array string by reading from file or using similar way, after
Gson gson = new Gson();
List<Contact> contacts = gson.fromJson("JSON STRING", new TypeToken<List<Contact>>() {}.getType());
Contact newContact = new Contact();
// set properties
contacts.add(newContact);
String json = gson.toJson(contacts);
There are tools like this one to create pojos from JSON.

How can i create the correct JSON data in an Android app required for a Java Jax RS REST POST Api accepting a List of JSON Objects

I have a Jax-Rs created REST endpoint as defined below:
//It will create the order for the customer who is occupying
//the table identified by the PathParam tableId
#Path("/order/{tableId}")
#POST
#Produces(MediaType.APPLICATION_JSON)
#Consumes(MediaType.APPLICATION_JSON )
public List<ItemOrder> giveOrder(#PathParam("tableId") int tableId, List<ItemOrder> itemOrderList){
Customer currentCustomer = Restaurant.getRestaurant().getCustomerArray().get(tableId);
for (int i = 0; i<itemOrderList.size(); i++){
currentCustomer.giveOrder(itemOrderList.get(i));
}
return itemOrderList;
}
Class ItemOrder has been defined as follows:
#XmlRootElement
public class ItemOrder {
private Item mItem;
private int mNumberOfPlates;
.....
......
.....
}
Class Item has been defined as follows:
#XmlRootElement
public class Item {
private int mItemId;
private String mName;
private float mPrice;
......
......
......
}
Now i am trying to send the JSON Post data from an Android client App as follows:
//Ordering Menu
JSONObject itemOrder1Item = new JSONObject();
JSONObject itemOrder1 = new JSONObject();
try {
itemOrder1Item.put("itemId", 11);
itemOrder1Item.put("itemName","Tea");
itemOrder1Item.put("itemPrice", 10);
itemOrder1.put("Item", itemOrder1Item);
itemOrder1.put("numberOfPlates", 10);
} catch (JSONException e) {
e.printStackTrace();
}
JSONObject itemOrder2Item = new JSONObject();
JSONObject itemOrder2 = new JSONObject();
try {
itemOrder2Item.put("itemId", 22);
itemOrder2Item.put("itemName","Coffee");
itemOrder2Item.put("itemPrice", 20);
itemOrder2.put("Item", itemOrder2Item);
itemOrder2.put("numberOfPlates", 10);
} catch (JSONException e) {
Log.d("Message",e.getMessage());
}
JSONArray jsonArray = new JSONArray();
jsonArray.put(itemOrder1);
jsonArray.put(itemOrder2);
JSONObject itemsOrderListObj = new JSONObject();
try {
itemsOrderListObj.put("itemOrderList", jsonArray);
} catch (JSONException e) {
e.printStackTrace();
}
HTTPAsyncTask asyncTask = new HTTPAsyncTask(getActivity().getApplicationContext(),c, null, itemsOrderListObj, "POST");
asyncTask.execute("http://10.0.2.2:8080/restaurant1/webapi/restaurant/waiters/menus/order/2");
}
But it is throwing some error saying the POST data is not correct. While developing the REST Api i have seen that the server is able to accept data as follows:
[
{
"item": {
"itemId": 11,
"itemName": "Tea",
"itemPrice": 10
},
"numberOfPlates": 5
},
{
"item": {
"itemId": 22,
"itemName": "Coffee",
"itemPrice": 20
},
"numberOfPlates": 5
},
{
"item": {
"itemId": 33,
"itemName": "Bread",
"itemPrice": 30
},
"numberOfPlates": 5
}
]
Now how will i be able to create this JSON Data in my Android app.
Need the help badly.
Used GSON. Its pretty simple as follows;
List<ItemOrder> itemsOrderListObj = new ArrayList<>();
itemsOrderListObj.add(new ItemOrder(new Item(11, "Tea", 10), 10));
itemsOrderListObj.add(new ItemOrder(new Item(22, "Coffee", 20), 10));
itemsOrderListObj.add(new ItemOrder(new Item(33, "Bread", 30), 10));
String itemsOrderListStringJSON = new Gson().toJson(itemsOrderListObj);
Log.i("JSONPOSTDATA", itemsOrderListStringJSON );
HTTPAsyncTask asyncTask = new HTTPAsyncTask(getActivity().getApplicationContext(),c, null, itemsOrderListStringJSON, "POST");
asyncTask.execute("http://10.0.2.2:8080/restaurant1/webapi/restaurant/waiters/menus/order/2");

How to make a dictionary application using Oxford Dictionary api?

This is the code which I got from the documentations, I get that, I receive the result in JSON format. But I only need the meaning of the word. So can anyone tell me how do I extract only the meaning of the searched word, rather getting the whole JSON file. I am new to android development, Please help me.
package com.example.hsekar.dictionarytestbeta;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import javax.net.ssl.HttpsURLConnection;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
new CallbackTask().execute(dictionaryEntries());
}
private String dictionaryEntries() {
final String language = "en";
final String word = "Ace";
final String word_id = word.toLowerCase(); //word id is case sensitive and lowercase is required
return "https://od-api.oxforddictionaries.com:443/api/v1/entries/" + language + "/" + word_id;
}
//in android calling network requests on the main thread forbidden by default
//create class to do async job
private class CallbackTask extends AsyncTask<String, Integer, String> {
#Override
protected String doInBackground(String... params) {
//TODO: replace with your own app id and app key
final String app_id = "10742428";
final String app_key = "ada344f3a7a7c7de0315fb78c5c9d6f9";
try {
URL url = new URL(params[0]);
HttpsURLConnection urlConnection = (HttpsURLConnection) url.openConnection();
urlConnection.setRequestProperty("Accept","application/json");
urlConnection.setRequestProperty("app_id",app_id);
urlConnection.setRequestProperty("app_key",app_key);
// read the output from the server
BufferedReader reader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
StringBuilder stringBuilder = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
stringBuilder.append(line + "\n");
}
return stringBuilder.toString();
}
catch (Exception e) {
e.printStackTrace();
return e.toString();
}
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
Log.d("This will be my result",result);
}
}
}
The following is my output. I am just printing it in the Logcat but once I get the concept , I will start working on the project.
This will be my result: {
"metadata": {
"provider": "Oxford University Press"
},
"results": [
{
"id": "ace",
"language": "en",
"lexicalEntries": [
{
"entries": [
{
"etymologies": [
"Middle English (denoting the ‘one’ on dice): via Old French from Latin as ‘unity, a unit’"
],
"grammaticalFeatures": [
{
"text": "Singular",
"type": "Number"
}
],
"homographNumber": "000",
"senses": [
{
"definitions": [
"a playing card with a single spot on it, ranked as the highest card in its suit in most card games"
],
"domains": [
"Cards"
],
"examples": [
{
"registers": [
"figurative"
],
"text": "life had started dealing him aces again"
},
{
"text": "the ace of diamonds"
}
],
"id": "m_en_gbus0005680.006"
},
{
"definitions": [
"a person who excels at a particular sport or other activity"
],
"domains": [
"Sport"
],
"examples": [
{
"text": "a motorcycle ace"
}
],
"id": "m_en_gbus0005680.010",
"registers": [
"informal"
],
"subsenses": [
{
"definitions": [
"a pilot who has shot down many enemy aircraft"
],
"domains": [
"Air Force"
],
"examples": [
{
"text": "a Battle of Britain ace"
}
],
"id": "m_en_gbus0005680.011"
}
]
},
{
"definitions": [
"(in tennis and similar games) a service that an opponent is unable to return and thus wins a point"
],
"domains": [
"Tennis"
So my question is how do I extract only the 'meaning' part from this output?
The Json result that you have mentioned is incomplete.the objects in the result are not closed.By the way this is how you get the results from json string.
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
try {
JSONObject js = new JSONObject(result);
JSONArray results = js.getJSONArray("results");
for(int i = 0;i<results.length();i++){
JSONObject lentries = results.getJSONObject(i);
JSONArray la = lentries.getJSONArray("lexicalEntries");
for(int j=0;j<la.length();j++){
JSONObject entries = la.getJSONObject(j);
JSONArray e = entries.getJSONArray("entries");
for(int i1=0;i1<e.length();i1++){
JSONObject senses = la.getJSONObject(i1);
JSONArray s = entries.getJSONArray("senses");
JSONObject d = s.getJSONObject(0);
JSONArray de = d.getJSONArray("definitions");
def = de.getString(0);
}
}
}
Log.e("def",def);
} catch (JSONException e) {
e.printStackTrace();
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
//Log.d("This will be my result",result);
String def = "";
try {
JSONObject js = new JSONObject(result);
JSONArray results = js.getJSONArray("results");
for (int i = 0; i < results.length(); i++) {
JSONObject lentries = results.getJSONObject(i);
JSONArray la = lentries.getJSONArray("lexicalEntries");
for (int j = 0; j < la.length(); j++) {
JSONObject entries = la.getJSONObject(j);
JSONArray e = entries.getJSONArray("entries");
for (int k= 0; k < e.length(); k++) {
JSONObject senses = e.getJSONObject(k);
JSONArray s = senses.getJSONArray("senses");
JSONObject d = s.getJSONObject(0);
JSONArray de = d.getJSONArray("definitions");
def = de.getString(0);
}
}
}
Log.e("def", def);
} catch (JSONException e) {
e.printStackTrace();
}
//Log.d("This will be my result",result);
}

Issues with JSON Parsing Android

I have Json like this:
{
"id": 226112,
"name": "name",
"min": 1,
"km": "0.33",
"url": "5___2_2.htm",
"departures": [
{
"type": "DATA",
"departures": {
"5": [
"04",
"19",
"34",
"47",
"59"
],
"6": [
"11",
"23",
"35",
"47",
"59"
]
etc..
And I try to parse it:
private static final String TAG_DEPARTURES = "departures";
private static final String TAG_TYPE = "type";
private static final String TAG_DEPARTURES2 = "departures";
private static String TAG_HOUR = "5";
...
example
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
timetables = jsonObj.getJSONArray(TAG_DEPARTURES);
for (int i = 0; i < timetables.length(); i++) {
JSONObject c = timetables.getJSONObject(i);
String type = c.getString(TAG_TYPE);
JSONObject departures = c.getJSONObject(TAG_DEPARTURES2);
String hour = departures.getString(TAG_HOUR);
HashMap<String, String> timetable = new HashMap<String, String>();
timetable.put(TAG_TYPE, type);
timetable.put(TAG_DEPARTURES2, hour);
timetableList.add(timetable);
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
...
Finally I get this:
DATA ["04","19","34","47","59"]
And this is String
["04","19","34","47","59"]
I would like to get String[] tab, where:
tab[0] = "04";
tab[1] = "19";
...
I think your json returned is not like you want.maybe you want an array for the key:5,6,but your json showed in question is just a string,so if you can control the json returned by server,please change its format to an string array.
If you can't control the json returned,you should extract the real string by yourself.Like this:
public String[] extractArray(final String str){
final String strNoBrace = str.substring(1,str.length()-1);
String[] tempResult = strNoBrace.split(",");
if(tempResult==null) return null;
String[] result = new String[tempResult.size()];
for(int i=0,size=tempResult.size();i<size;++i){
String temp = tempResult[i];
result[i] = temp.substring(1,temp.length()-1);
}
return result;
}

How can I parse a local JSON file from assets folder into a ListView?

I'm currently developing a physics app that is supposed to show a list of formulas and even solve some of them (the only problem is the ListView)
This is my main layout
<?xml version="1.0" encoding="utf-8"?>
<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="wrap_content"
android:measureWithLargestChild="false"
android:orientation="vertical"
tools:context=".CatList">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#drawable/titlebar">
<TextView
android:id="#+id/Title1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:text="#string/app_name"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textColor="#ff1c00"
android:textIsSelectable="false" />
</RelativeLayout>
<ListView
android:id="#+id/listFormulas"
android:layout_width="match_parent"
android:layout_height="wrap_content">
</ListView>
</LinearLayout>
And this is my main activity
package com.wildsushii.quickphysics;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import org.json.JSONException;
import org.json.JSONObject;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.content.res.AssetManager;
import android.view.Menu;
import android.widget.ListView;
public class CatList extends Activity {
public static String AssetJSONFile(String filename, Context context) throws IOException {
AssetManager manager = context.getAssets();
InputStream file = manager.open(filename);
byte[] formArray = new byte[file.available()];
file.read(formArray);
file.close();
return new String(formArray);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_cat_list);
ListView categoriesL = (ListView) findViewById(R.id.listFormulas);
ArrayList<HashMap<String, String>> formList = new ArrayList<HashMap<String, String>>();
Context context = null;
try {
String jsonLocation = AssetJSONFile("formules.json", context);
JSONObject formArray = (new JSONObject()).getJSONObject("formules");
String formule = formArray.getString("formule");
String url = formArray.getString("url");
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
//My problem is here!!
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.cat_list, menu);
return true;
}
}
I actually know I can make this without using JSON but I need more practice parsing JSON. By the way, this is the JSON
{
"formules": [
{
"formule": "Linear Motion",
"url": "qp1"
},
{
"formule": "Constant Acceleration Motion",
"url": "qp2"
},
{
"formule": "Projectile Motion",
"url": "qp3"
},
{
"formule": "Force",
"url": "qp4"
},
{
"formule": "Work, Power, Energy",
"url": "qp5"
},
{
"formule": "Rotary Motion",
"url": "qp6"
},
{
"formule": "Harmonic Motion",
"url": "qp7"
},
{
"formule": "Gravity",
"url": "qp8"
},
{
"formule": "Lateral and Longitudinal Waves",
"url": "qp9"
},
{
"formule": "Sound Waves",
"url": "qp10"
},
{
"formule": "Electrostatics",
"url": "qp11"
},
{
"formule": "Direct Current",
"url": "qp12"
},
{
"formule": "Magnetic Field",
"url": "qp13"
},
{
"formule": "Alternating Current",
"url": "qp14"
},
{
"formule": "Thermodynamics",
"url": "qp15"
},
{
"formule": "Hydrogen Atom",
"url": "qp16"
},
{
"formule": "Optics",
"url": "qp17"
},
{
"formule": "Modern Physics",
"url": "qp18"
},
{
"formule": "Hydrostatics",
"url": "qp19"
},
{
"formule": "Astronomy",
"url": "qp20"
}
]
}
I have tried a lot of things and even delete the entire project to make a new one :(
As Faizan describes in their answer here:
First of all read the Json File from your assests file using below code.
and then you can simply read this string return by this function as
public String loadJSONFromAsset() {
String json = null;
try {
InputStream is = getActivity().getAssets().open("yourfilename.json");
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;
}
and use this method like that
try {
JSONObject obj = new JSONObject(loadJSONFromAsset());
JSONArray m_jArry = obj.getJSONArray("formules");
ArrayList<HashMap<String, String>> formList = new ArrayList<HashMap<String, String>>();
HashMap<String, String> m_li;
for (int i = 0; i < m_jArry.length(); i++) {
JSONObject jo_inside = m_jArry.getJSONObject(i);
Log.d("Details-->", jo_inside.getString("formule"));
String formula_value = jo_inside.getString("formule");
String url_value = jo_inside.getString("url");
//Add your values in your `ArrayList` as below:
m_li = new HashMap<String, String>();
m_li.put("formule", formula_value);
m_li.put("url", url_value);
formList.add(m_li);
}
} catch (JSONException e) {
e.printStackTrace();
}
For further details regarding JSON Read HERE
With Kotlin have this extension function to read the file return as string.
fun AssetManager.readAssetsFile(fileName : String): String = open(fileName).bufferedReader().use{it.readText()}
Parse the output string using any JSON parser.
{ // json object node
"formules": [ // json array formules
{ // json object
"formule": "Linear Motion", // string
"url": "qp1"
}
What you are doing
Context context = null; // context is null
try {
String jsonLocation = AssetJSONFile("formules.json", context);
So change to
try {
String jsonLocation = AssetJSONFile("formules.json", CatList.this);
To parse
I believe you get the string from the assests folder.
try
{
String jsonLocation = AssetJSONFile("formules.json", context);
JSONObject jsonobject = new JSONObject(jsonLocation);
JSONArray jarray = (JSONArray) jsonobject.getJSONArray("formules");
for(int i=0;i<jarray.length();i++)
{
JSONObject jb =(JSONObject) jarray.get(i);
String formula = jb.getString("formule");
String url = jb.getString("url");
}
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
Just summarising #libing's answer with a sample that worked for me.
val gson = Gson()
val todoItem: TodoItem = gson.fromJson(this.assets.readAssetsFile("versus.json"), TodoItem::class.java)
private fun AssetManager.readAssetsFile(fileName : String): String = open(fileName).bufferedReader().use{it.readText()}
Without this extension function the same can be achieved by using BufferedReader and InputStreamReader this way:
val i: InputStream = this.assets.open("versus.json")
val br = BufferedReader(InputStreamReader(i))
val todoItem: TodoItem = gson.fromJson(br, TodoItem::class.java)
Method to read JSON file from Assets folder and return as a string object.
public static String getAssetJsonData(Context context) {
String json = null;
try {
InputStream is = context.getAssets().open("myJson.json");
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;
}
Log.e("data", json);
return json;
}
Now for parsing data in your activity:-
String data = getAssetJsonData(getApplicationContext());
Type type = new TypeToken<Your Data model>() {
}.getType();
<Your Data model> modelObject = new Gson().fromJson(data, type);
If you are using Kotlin in android then you can create Extension function.
Extension Functions are defined outside of any class - yet they reference the class name and can use this. In our case we use applicationContext.
So in Utility class you can define all extension functions.
Utility.kt
fun Context.loadJSONFromAssets(fileName: String): String {
return applicationContext.assets.open(fileName).bufferedReader().use { reader ->
reader.readText()
}
}
MainActivity.kt
You can define private function for load JSON data from assert like this:
lateinit var facilityModelList: ArrayList<FacilityModel>
private fun bindJSONDataInFacilityList() {
facilityModelList = ArrayList<FacilityModel>()
val facilityJsonArray = JSONArray(loadJSONFromAsserts("NDoH_facility_list.json")) // Extension Function call here
for (i in 0 until facilityJsonArray.length()){
val facilityModel = FacilityModel()
val facilityJSONObject = facilityJsonArray.getJSONObject(i)
facilityModel.Facility = facilityJSONObject.getString("Facility")
facilityModel.District = facilityJSONObject.getString("District")
facilityModel.Province = facilityJSONObject.getString("Province")
facilityModel.Subdistrict = facilityJSONObject.getString("Facility")
facilityModel.code = facilityJSONObject.getInt("code")
facilityModel.gps_latitude = facilityJSONObject.getDouble("gps_latitude")
facilityModel.gps_longitude = facilityJSONObject.getDouble("gps_longitude")
facilityModelList.add(facilityModel)
}
}
You have to pass facilityModelList in your ListView
FacilityModel.kt
class FacilityModel: Serializable {
var District: String = ""
var Facility: String = ""
var Province: String = ""
var Subdistrict: String = ""
var code: Int = 0
var gps_latitude: Double= 0.0
var gps_longitude: Double= 0.0
}
In my case JSON response start with JSONArray
[
{
"code": 875933,
"Province": "Eastern Cape",
"District": "Amathole DM",
"Subdistrict": "Amahlathi LM",
"Facility": "Amabele Clinic",
"gps_latitude": -32.6634,
"gps_longitude": 27.5239
},
{
"code": 455242,
"Province": "Eastern Cape",
"District": "Amathole DM",
"Subdistrict": "Amahlathi LM",
"Facility": "Burnshill Clinic",
"gps_latitude": -32.7686,
"gps_longitude": 27.055
}
]
Using OKIO
implementation("com.squareup.okio:okio:3.0.0-alpha.4")
With Java:
public static String readJsonFromAssets(Context context, String filePath) {
try {
InputStream input = context.getAssets().open(filePath);
BufferedSource source = Okio.buffer(Okio.source(input));
return source.readByteString().string(Charset.forName("utf-8"));
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
With Kotlin:
fun readJsonFromAssets(context: Context, filePath: String): String? {
try {
val source = context.assets.open(filePath).source().buffer()
return source.readByteString().string(Charset.forName("utf-8"))
} catch (e: IOException) {
e.printStackTrace()
}
return null
}
and then...
String data = readJsonFromAssets(context, "json/some.json"); //here is my file inside the folder assets/json/some.json
Type reviewType = new TypeToken<List<Object>>() {}.getType();
if (data != null) {
Object object = new Gson().fromJson(data, reviewType);
}
Source code How to fetch Local Json from Assets folder
https://drive.google.com/open?id=1NG1amTVWPNViim_caBr8eeB4zczTDK2p
{
"responseCode": "200",
"responseMessage": "Recode Fetch Successfully!",
"responseTime": "10:22",
"employeesList": [
{
"empId": "1",
"empName": "Keshav",
"empFatherName": "Mr Ramesh Chand Gera",
"empSalary": "9654267338",
"empDesignation": "Sr. Java Developer",
"leaveBalance": "3",
"pfBalance": "60,000",
"pfAccountNo.": "12345678"
},
{
"empId": "2",
"empName": "Ram",
"empFatherName": "Mr Dasrath ji",
"empSalary": "9999999999",
"empDesignation": "Sr. Java Developer",
"leaveBalance": "3",
"pfBalance": "60,000",
"pfAccountNo.": "12345678"
},
{
"empId": "3",
"empName": "Manisha",
"empFatherName": "Mr Ramesh Chand Gera",
"empSalary": "8826420999",
"empDesignation": "BusinessMan",
"leaveBalance": "3",
"pfBalance": "60,000",
"pfAccountNo.": "12345678"
},
{
"empId": "4",
"empName": "Happy",
"empFatherName": "Mr Ramesh Chand Gera",
"empSalary": "9582401701",
"empDesignation": "Two Wheeler",
"leaveBalance": "3",
"pfBalance": "60,000",
"pfAccountNo.": "12345678"
},
{
"empId": "5",
"empName": "Ritu",
"empFatherName": "Mr Keshav Gera",
"empSalary": "8888888888",
"empDesignation": "Sararat Vibhag",
"leaveBalance": "3",
"pfBalance": "60,000",
"pfAccountNo.": "12345678"
}
]
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_employee);
emp_recycler_view = (RecyclerView) findViewById(R.id.emp_recycler_view);
emp_recycler_view.setLayoutManager(new LinearLayoutManager(EmployeeActivity.this,
LinearLayoutManager.VERTICAL, false));
emp_recycler_view.setItemAnimator(new DefaultItemAnimator());
employeeAdapter = new EmployeeAdapter(EmployeeActivity.this , employeeModelArrayList);
emp_recycler_view.setAdapter(employeeAdapter);
getJsonFileFromLocally();
}
public String loadJSONFromAsset() {
String json = null;
try {
InputStream is = EmployeeActivity.this.getAssets().open("employees.json"); //TODO Json File name from assets folder
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;
}
private void getJsonFileFromLocally() {
try {
JSONObject jsonObject = new JSONObject(loadJSONFromAsset());
String responseCode = jsonObject.getString("responseCode");
String responseMessage = jsonObject.getString("responseMessage");
String responseTime = jsonObject.getString("responseTime");
Log.e("keshav", "responseCode -->" + responseCode);
Log.e("keshav", "responseMessage -->" + responseMessage);
Log.e("keshav", "responseTime -->" + responseTime);
if(responseCode.equals("200")){
}else{
Toast.makeText(this, "No Receord Found ", Toast.LENGTH_SHORT).show();
}
JSONArray jsonArray = jsonObject.getJSONArray("employeesList"); //TODO pass array object name
Log.e("keshav", "m_jArry -->" + jsonArray.length());
for (int i = 0; i < jsonArray.length(); i++)
{
EmployeeModel employeeModel = new EmployeeModel();
JSONObject jsonObjectEmployee = jsonArray.getJSONObject(i);
String empId = jsonObjectEmployee.getString("empId");
String empName = jsonObjectEmployee.getString("empName");
String empDesignation = jsonObjectEmployee.getString("empDesignation");
String empSalary = jsonObjectEmployee.getString("empSalary");
String empFatherName = jsonObjectEmployee.getString("empFatherName");
employeeModel.setEmpId(""+empId);
employeeModel.setEmpName(""+empName);
employeeModel.setEmpDesignation(""+empDesignation);
employeeModel.setEmpSalary(""+empSalary);
employeeModel.setEmpFatherNamer(""+empFatherName);
employeeModelArrayList.add(employeeModel);
} // for
if(employeeModelArrayList!=null) {
employeeAdapter.dataChanged(employeeModelArrayList);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
You have to write a function to read the Json File from your assests folder.
public String loadJSONFile() {
String json = null;
try {
InputStream inputStream = getAssets().open("yourfilename.json");
int size = inputStream.available();
byte[] byteArray = new byte[size];
inputStream.read(byteArray);
inputStream.close();
json = new String(byteArray, "UTF-8");
} catch (IOException e) {
e.printStackTrace();
return null;
}
return json;
}

Categories

Resources