I want to parse JSON from local file stored in asset folder and set it to recyclerview in android. But recyclerview is not populating.
Can anyone please tell me whats wrong with this?
I have tried many answers from here, but its not working.
JSON
{
"box": [
{
"text" : "text1 "
},
{
"text" : "text2"
},
{
"text" : "text3"
},
...............
]
}
CODE
private String loadJSONFromAsset() {
String json = null;
try {
InputStream is = getAssets().open("file.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;
}
private void RequestJson() {
recyclerView = findViewById(R.id.mRecycler);
List<Box> data=new ArrayList<>();
try {
JSONObject json = new JSONObject(loadJSONFromAsset());
JSONArray tablelist = json.getJSONArray("box");
for (int i = 0; i < tablelist.length(); i++) {
JSONObject AllTable = tablelist.getJSONObject(i);
Box items2 = new Box();
items2.setText(AllTable.getString("text"));
data.add(items2);
}
mAdapter = new BoxAdapter(MainActivity.this, data);
recyclerView.setAdapter(mAdapter);
recyclerView.setLayoutManager(new LinearLayoutManager(MainActivity.this));
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(MainActivity.this, e.toString(), Toast.LENGTH_LONG).show();
}
}
change this things. and make sure data not empty.
mAdapter = new BoxAdapter(MainActivity.this, data);
recyclerView.setLayoutManager(new LinearLayoutManager(MainActivity.this));
recyclerView.setAdapter(mAdapter);
mAdapter.notifyDataSetChanged();
Related
I try to get information from this link
and I don't get it !
This is my code:
String s = getJSONFile();
String myDataArray[] = {};
try{
JSONObject reportJSON = new JSONObject();
JSONArray dateJSON = reportJSON.getJSONArray("terrestrial_date");
myDataArray = new String[dateJSON.length()];
for (int i = 0; i <dateJSON.length(); i++){
JSONObject jsonObject = dateJSON.getJSONObject(i);
myDataArray[i] = jsonObject.getString("terrestrial_date");
}
}catch (JSONException e){
e.printStackTrace();
}
ArrayAdapter<String> stringAdapter = new ArrayAdapter<String>(getApplicationContext(), R.layout.row, myDataArray);
if (mListView != null){
mListView.setAdapter(stringAdapter);
}
}
this is the getJSONFile method:
public String getJSONFile() {
String json = null;
try {
InputStream is = getResources().openRawResource(R.raw.weather_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;
}
Thanks for help :)
You should use GSON librari and for the Model of this code http://www.jsonschema2pojo.org/
This is so easy.
terrstial_date is a String of report. try this,
String date=jsonObject.getString("terestial_date");
also your json parsing structere is not correct accroding to your json
{
"report": {
"terrestrial_date": "2017-10-13",
"sol": 1844,
"ls": 73.0,
"min_temp": -81.0,
"min_temp_fahrenheit": -113.8,
"max_temp": -28.0,
"max_temp_fahrenheit": -18.4,
"pressure": 869.0,
"pressure_string": "Higher",
"abs_humidity": null,
"wind_speed": null,
"wind_direction": "--",
"atmo_opacity": "Sunny",
"season": "Month 3",
"sunrise": "2017-10-13T10:59:00Z",
"sunset": "2017-10-13T22:43:00Z"
}
}
This is how you can get response from OkHttp
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url("http://marsweather.ingenology.com/v1/latest/?format=json")
.get()
.build();
try {
Response response = client.newCall(request).execute();
String json = response.body().string();
JSONObject jsonObject = new JSONObject(json);
JSONObject reportJson = jsonObject.getJSONObject("report"); // your report object.
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
Put your Json file in your assets folder with .json extension and use this method to get JsonString from it
public String loadJSONFromAsset(String fileName) {
String json = null;
try {
InputStream is = getAssets().open(fileName);
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 get the String using this function like this
String jsonString = MyApplication.loadJSONFromAsset(this,"yourJsonFileName.json");
and Parse like that
try{
JSONObject responce = new JSONObject(jsonString);
JSONArray report= responce.getJSONObject("report");
String terrestrial_date = report.getString("terrestrial_date");
}catch (JSONException e){
e.printStackTrace();
}
this is my code after all the change:
public void find_weather() {
String url = "http://marsweather.ingenology.com/v1/latest/?format=json";
JsonObjectRequest jor = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONObject main_object = response.getJSONObject("results");
JSONArray array = response.getJSONArray("");
JSONObject object = array.getJSONObject(0);
String date = object.getString("date");
String tempMin = String.valueOf(main_object.getDouble("min_temp"));
String tempMax = String.valueOf(main_object.getDouble("max_temp"));
String atmo_opacity = object.getString("atmo_opacity");
mMaxTemp.setText("max_temp");
mMinTemp.setText("min_temp");
mAtmoOpacity.setText("atmo_opacity");
Calendar calendar = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("EEEE-MM-dd");
String formatted_data = sdf.format(calendar.getTime());
mDate.setText(formatted_data);
double temp_max_int = Double.parseDouble(tempMax);
double temp_min_int = Double.parseDouble(tempMin);
mMaxTemp.setText(String.valueOf(i));
mMinTemp.setText(String.valueOf(i));
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
RequestQueue queue = Volley.newRequestQueue(this);
queue.add(jor);
You are doing in wrong way
1.report is a JsonObject inside your response means you have your report inside another JsonObject. First you have to parse your response to get report data
2.terrestrial_date is a string data so you have to use report.getJsonString("terrestrial_date") you are using reportJSON.getJSONArray("terrestrial_date"); which is used for Array data
For, more information get a look here How to parse JSON in Android
Try this,
String s = getJSONFile();
String terrestrial_date = "";
try{
JSONObject responce = new JSONObject(s);
JSONObject report= responce.getJSONObject("report");
terrestrial_date = report.getString("terrestrial_date");
}catch (JSONException e){
e.printStackTrace();
}
EDIT
Try, Volley for fetching JSON data
First you need to add dependency of volley in build.gradle file-:
dependencies {
compile 'com.android.volley:volley:1.0.0'
}
Then use following code to fetch or parse your JSON data
// Tag used to cancel the request
String url = "http://marsweather.ingenology.com/v1/latest/?format=json";
StringRequest strReq = new StringRequest(Request.Method.GET,
url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d(TAG, response.toString());
String terrestrial_date = "";
try{
JSONObject responce = new JSONObject(response);
JSONObject report= responce.getJSONObject("report");
terrestrial_date = report.getString("terrestrial_date");
}catch (JSONException e){
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d(TAG, "Error: " + error.getMessage());
}
});
// Adding request to request queue
Volley.newRequestQueue(this).add(strReq);
SCREENSHOT
As, You can see the screenshot above. I am getting response with the same code
I am trying to extract some data from a json array file, i followed the steps from
Reading a Json Array in android
a snippit of the json array:
[
{
"JobNo": 1,
"JobTime": 30,
"JobDate": "20170911",
"WorkerTime": 27,
"JobTimeError": -3
},
{
"JobNo": 2,
"JobTime": 22,
"JobDate": "20170911",
"WorkerTime": 21,
"JobTimeError": -1
},
What i want to be able to do is, extract the data and store them into their own arrays, JobNo to JobNo array, etc. the following code is my attempt, but it doesn't store the values (crashes at toast because it says no data in array).
thanks
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Spinner staticSpinner = (Spinner) findViewById(R.id.static_spinner);
ArrayList<Integer> JobNo = new ArrayList<>();
ArrayList<Integer> JobTime= new ArrayList<>();
ArrayList<String> JobDate= new ArrayList<>();
ArrayList<Integer> WorkerTime= new ArrayList<>();
ArrayList<Integer> JobTimeError = new ArrayList<>();
try {
JSONObject json = new JSONObject(loadJSONFromAsset());
JSONArray jArray = json.getJSONArray("Data");
for (int i = 0; i < jArray.length(); i++) {
JSONObject json_data = jArray.getJSONObject(i);
int JobN = json_data.getInt("JobNo");
int JobT = json_data.getInt("JobTime");
String JobD = json_data.getString("JobDate");
int WorkT = json_data.getInt("WorkerTime");
int JobTE = json_data.getInt("JobTimeError");
JobNo.add(JobN);
JobTime.add(JobT);
JobDate.add(JobD);
WorkerTime.add(WorkT);
JobTimeError.add(JobTE);
}
}
catch (JSONException e) {
e.printStackTrace();
}
Toast.makeText(this,
JobDate.get(1),
Toast.LENGTH_LONG).show();
}
public String loadJSONFromAsset() {
String json = null;
try {
InputStream is = getAssets().open("convertcsv.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;
}
Your JSON String is not a JSON object, it is a JSON Array, So use:
JSONArray jArray = new JSONArray (loadJSONFromAsset());
I have the following code to retrieve Json from raw file:
#Override
protected RecyclerView.Adapter getAdapter() {
if (adapter == null) {
String jsonStr = readRawFile();
Gson gson = new Gson();
VideoPage videoPage = gson.fromJson(jsonStr, VideoPage.class);
adapter = new VideoAdapter(videoPage);
}
return adapter;
}
String readRawFile() {
String content = "";
Resources resources = getContext().getResources();
InputStream is = null;
try {
is = resources.openRawResource(R.raw.video_list);
byte buffer[] = new byte[is.available()];
is.read(buffer);
content = new String(buffer);
} catch (IOException e) {
e.printStackTrace();
} finally {
if (is != null) {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return content;
}
File video_list.json : enter image description here
"data": [
{
"title": "Video 1",
"imgUrl": "http://example.com/",
"videoUrl": "http://example.com/",
"docUrl": "http://example.com/"
},
{
"title": "Video 2",
"imgUrl": "http://example.com//",
"videoUrl": "http://example.com/",
"docUrl": "http://example.com/"
},
Now I do not want to get Json from this video_list file, I want to get the Json file from an url containing Json. Can someone help me code again?
I'm having trouble loading objects from an JSON file, the idea is to store objects in the JSON file and return an array of objects, is there any easier way doing this? Or is there any better solution than JSON for doing this?
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_student_list);
TextView studentlistTextView = (TextView)findViewById(R.id.studentlistTextView);
ArrayList<students> studentArray = loadJSONFromAsset();
try {
studentlistTextView.setText(studentArray.get(0).getName());
}catch(Exception e){
e.printStackTrace();
}
}
public ArrayList<students> loadJSONFromAsset() {
ArrayList<students> studentArray = new ArrayList<>();
String json = null;
try {
InputStream is = getAssets().open("jsonstudent");
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;
}
try {
JSONObject obj = new JSONObject(json);
JSONArray m_jArry = obj.getJSONArray("students");
for (int i = 0; i < m_jArry.length(); i++) {
JSONObject jo_inside = m_jArry.getJSONObject(i);
students student = new students();
student.setName(jo_inside.getString("name"));
student.setLastname(jo_inside.getString("lastname"));
student.setNumber(jo_inside.getString("number"));
studentArray.add(student);
}
} catch (JSONException e) {
e.printStackTrace();
}
return studentArray;
}
}
This is my JSON file
{ "student" : [
{"name" : "hans", "lastname" : "rosenboll", "number" : "5325235" }
]}
You can use Gson and Shared Preference to store objects in the JSON file and return an array of objects:
private final String PERSONAL_INFO = "personal_info";
public void putPersonalInfo(Profile info) {
Gson gson = new Gson();
String json = gson.toJson(info);
getAppPreference().edit().putString(PERSONAL_INFO, json).commit();
}
public Profile getPersonalInfo() {
Gson gson = new Gson();
return gson.fromJson(getAppPreference().getString(PERSONAL_INFO, null), Profile.class);
}
here my jsonArray data like:
[{"LeadId":4,
"CoreLeadId":0,
"CompanyId":7,
"AccountNo":"5675",
"ScheduleOn":"2015-05-11T00:00:00"},
{"LeadId":7,
"CoreLeadId":2,
"CompanyId":8,
"AccountNo":"sample string 4",
"ScheduleOn":"2015-12-01T15:04:23.217"}]
i want to sort by dateandtime(ScheduleOn) and put into listview. below i side i send snnipt of my code where i set adapter. can we sort into listItemService. Please help me.
JSONArray jsonArray = dpsFunctionFlow.getAllServiceDetail("1");
listItemService = new Gson().fromJson(jsonArray.toString(),
new TypeToken<List<AppointmentInfoDto>>() {
}.getType());
mAdapter = new AdapterAppointment(getActivity(), listItemService);
listView.setAdapter(mAdapter);
You should be able to use Collections.sort(...) passing in a Comparator that will compare 2 AppointmentInfoDto objects.
Collections.sort(listItemService, new Comparator<AppointmentInfoDto>() {
#Override public int compare(AppointmentInfoDto l, AppointmentInfoDto r) {
// Compare l.ScheduleOn and r.ScheduleOn
}
}
/// Sort JSON By any Key for date
public static JSONArray sortJsonArray(JSONArray array,final String key, final boolean isCase) {
List<JSONObject> jsonsList = new ArrayList<JSONObject>();
try {
for (int i = 0; i < array.length(); i++) {
jsonsList.add(array.getJSONObject(i));
}
Collections.sort(jsonsList, new Comparator<JSONObject>() {
#Override
public int compare(JSONObject v_1, JSONObject v_2) {
String CompareString1 = "", CompareString2 = "";
try {
CompareString1 = v_1.getString(key); //Key must be present in JSON
CompareString2 = v_2.getString(key); //Key must be present in JSON
} catch (JSONException ex) {
// Json Excpetion handling
}
return CompareString1.compareTo(CompareString2);
}
});
} catch (JSONException ex) {
// Json Excpetion handling
}
return new JSONArray(jsonsList);
}
// _Sort JSON for any String Key value.........
public static JSONArray sortJsonArray(JSONArray array,final String key, final boolean isCase) {
List<JSONObject> jsonsList = new ArrayList<JSONObject>();
try {
for (int i = 0; i < array.length(); i++) {
jsonsList.add(array.getJSONObject(i));
}
Collections.sort(jsonsList, new Comparator<JSONObject>() {
#Override
public int compare(JSONObject v_1, JSONObject v_2) {
String CompareString1 = "", CompareString2 = "";
try {
CompareString1 = v_1.getString(key); //Key must be present in JSON
CompareString2 = v_2.getString(key); //Key must be present in JSON
} catch (JSONException ex) {
// Json Excpetion handling
}
return isCase ? CompareString1.compareTo(CompareString2) : CompareString1.compareToIgnoreCase(CompareString2);
}
});
} catch (JSONException ex) {
// Json Excpetion handling
}
return new JSONArray(jsonsList);
}