sort jsonarray of data in descending order - java

[
{
"id":"1",
"created_at":"2019-08-19 02:54:36",
"updated_at":"2019-09-04 15:00:05"
},
{
"id":"2",
"created_at":"2019-08-27 08:59:18",
"updated_at":"2019-09-04 14:59:14"
},
{
"id":"4",
"created_at":"2019-08-29 20:19:54",
"updated_at":"2019-09-04 14:58:53"
}
]
how do i sort json data according to "created_at" (2019-08-30,2019-08-29) data in descending order and set value to textview in android.

please try this
public static JSONArray sortJsonArray(JSONArray array) {
List<JSONObject> jsons = new ArrayList<JSONObject>();
for (int i = 0; i < array.length(); i++) {
jsons.add(array.getJSONObject(i));
}
Collections.sort(jsons, new Comparator<JSONObject>() {
#Override
public int compare(JSONObject lhs, JSONObject rhs) {
String lid = lhs.getString("created_at");
String rid = rhs.getString("created_at");
// Here you could parse string id to integer and then compare.
return lid.compareTo(rid);
}
});
return new JSONArray(jsons);
}

A solution using gson library:
public static void setSortedDate (String json, TextView tv) {
Type t = new TypeToken<List<DateModel>>(){}.getType();
Gson gson = new Gson();
List<DateModel> list = gson.fromJson(json, t);
Collections.sort(list, new Comparator<DateModel>(){
#Override
public int compare (DateModel p1, DateModel p2) {
DateFormat df = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
try {
Date d1 = df.parse(p1.created_at);
Date d2 = df.parse(p2.created_at);
return d2.compareTo(d1);
} catch (ParseException e) {
e.printStackTrace();
}
return 0;
}
});
int i = list.size();
for(DateModel d: list){
tv.append(d.created_at);
if(--i > 0) tv.append(", ");
}
}
Model class
public class DateModel {
String id;
String created_at;
String updated_at;
}
Usage
private static final String JSON = "[ { \"id\": \"1\", \"created_at\": \"2019-08-19 02:54:36\", \"updated_at\": \"2019-09-04 15:00:05\" }, { \"id\": \"2\", \"created_at\": \"2019-08-27 08:59:18\", \"updated_at\": \"2019-09-04 14:59:14\" }, { \"id\": \"4\", \"created_at\": \"2019-08-29 20:19:54\", \"updated_at\": \"2019-09-04 14:58:53\" }, { \"id\": \"5\", \"created_at\": \"2019-08-30 09:31:42\", \"updated_at\": \"2019-09-04 14:58:40\" } ]";
setSortedDate(JSON, tv);
Output
2019-08-30 09:31:42, 2019-08-29 20:19:54, 2019-08-27 08:59:18, 2019-08-19 02:54:36
Update
Here is the replacement of gson with standard java implementation
public static void setSortedDate (String json, TextView tv) {
List<DateModel> list = getListFromJson(json);
Collections.sort(list, new DateModelComparator());
int i = list.size();
for(DateModel d: list){
tv.append(d.created_at);
if(--i > 0) tv.append(", ");
}
}
private static List<DateModel> getListFromJson (String json) {
List<DateModel> list = new LinkedList<>();
try {
JSONArray array = new JSONArray(json);
for(int i=0;i<array.length();i++){
JSONObject obj = array.getJSONObject(i);
DateModel dm = new DateModel();
dm.id = obj.getString("id");
dm.created_at = obj.getString("created_at");
dm.updated_at = obj.getString("updated_at");
list.add(dm);
}
} catch (JSONException e) {
e.printStackTrace();
}
return list;
}
DateComparator class
public class DateModelComparator implements Comparator<DateModel> {
#Override
public int compare (DateModel p1, DateModel p2) {
DateFormat df = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
try {
Date d1 = df.parse(p1.created_at);
Date d2 = df.parse(p2.created_at);
return d2.compareTo(d1);
} catch (ParseException e) {
e.printStackTrace();
}
return 0;
}
}

Related

How to parsing JSON from presenter and set to RecyclerView(Android)

I try to get xml data then I parse it to JSON, I use OkHttp as a connection. I managed to get data from LOG but I can't display it in my RecyclerView, when I LOG to adapter and the result is size 0
I set the response to the model and sharedpreference
The point of the problem is that I just don't understand how to take the response from the presenter then I set it to the adapter in the main Fragment.
public class ParentCategories {
#SerializedName("idkategori")
#Expose
private String idkategori;
#SerializedName("namakategori")
#Expose
private String namakategori;
#SerializedName("fileicon")
#Expose
private String fileicon;
#SerializedName("subkategori")
#Expose
private SubCategories subkategori;
public ParentCategories(Parcel in) {
this.idkategori = in.readString();
this.namakategori = in.readString();
this.fileicon = in.readString();
}
public ParentCategories() {
}
public String getIdkategori() {
return idkategori;
}
public void setIdkategori(String idkategori) {
this.idkategori = idkategori;
}
public String getNamakategori() {
return namakategori;
}
public void setNamakategori(String namakategori) {
this.namakategori = namakategori;
}
public String getFileicon() {
return fileicon;
}
public void setFileicon(String fileicon) {
this.fileicon = fileicon;
}
public SubCategories getSubkategori() {
return subkategori;
}
public void setSubkategori(SubCategories subkategori) {
this.subkategori = subkategori;
}
}
public class CategoriesPresenter {
....
public void onResponse(Call call, Response response) throws IOException {
String mMessage = response.body().string();
JSONObject jsonObj = null;
try {
jsonObj = XML.toJSONObject(mMessage);
JSONObject jsonObject = new JSONObject(jsonObj.toString());
JSONObject object = jsonObject.getJSONObject("posh");
String attr2 = object.getString("resultcode");
com.davestpay.apphdi.helper.Log.d("hasil", String.valueOf(object));
if (attr2.equalsIgnoreCase("0000")) {
String idAgen = object.getString("idagen");
int jumlahKategori = object.getInt("jumlahkategori");
JSONArray category = object.getJSONArray("kategori");
List<ParentCategories> parentCategories = new ArrayList<ParentCategories>();
for (int i = 0; i < category.length(); i++) {
ParentCategories categories = new ParentCategories();
JSONObject c = category.getJSONObject(i);
Log.d(TAG, "onResponseC: "+c);
String idKategori = c.getString("idkategori");
String namaKategori = c.getString("namakategori");
Log.d(TAG, "onResponseNamaKategori: "+namaKategori);
String fileIcon = c.getString("fileicon");
JSONObject subCategories = c.getJSONObject("subkategori");
JSONArray subCategory = subCategories.getJSONArray("kategori2");
Log.d(TAG, "onResponseSubCategories: "+subCategory);
for (int subCatPosition = 0; subCatPosition < subCategory.length(); subCatPosition++) {
SecondCategories secondCategories = new SecondCategories();
List<SecondCategories> listSecondCategories = new ArrayList<>();
JSONObject sc = subCategory.getJSONObject(subCatPosition);
String secIdKategori = sc.getString("idkategori");
String secNamaKategori = sc.getString("namakategori");
String secFileIcon = sc.getString("fileicon");
secondCategories.setIdkategori(secIdKategori);
secondCategories.setNamakategori(secNamaKategori);
secondCategories.setFileicon(secFileIcon);
listSecondCategories.add(secondCategories);
}
categories.setIdkategori(idKategori);
categories.setNamakategori(namaKategori);
categories.setFileicon(fileIcon);
parentCategories.add(categories);
Log.d(TAG, "onResponseFinalCategories: "+parentCategories);
}
iCategories.onSuccessCategories(parentCategories);
preferenceHelper.clear(PreferenceHelper.CATEGORIES);
preferenceHelper.putList(PreferenceHelper.CATEGORIES, parentCategories);
} else {
Log.d(TAG, "onResponse: ");
}
} catch (JSONException e) {
com.davestpay.apphdi.helper.Log.e("JSON exception", e.getMessage());
e.printStackTrace();
}
}
}
private void getInit() {
if (preferenceHelper != null) {
idAgen = preferenceHelper.getString(PreferenceHelper.ID_AGEN);
namaAgen = preferenceHelper.getString(PreferenceHelper.NAMA_AGEN);
password = preferenceHelper.getString(PreferenceHelper.PASSWORD);
categories = preferenceHelper.getList(PreferenceHelper.CATEGORIES, ParentCategories[].class);
}
authPresenter = new AuthPresenter(getContext());
presenter = new CategoriesPresenter();
presenter.setBaseView(this);
presenter.onCreate(getContext());
if (authPresenter.isLoggedIn()) {
// kategori.setText(categories.toString());
presenter.getCategories(idAgen, password, counter);
}
kategori = mView.findViewById(R.id.kategori);
categories = new ArrayList<>();
rvMain = mView.findViewById(R.id.rv_categories);
adapter = new CategoriesListViewAdapter(getContext(), categories);
layoutManager = new LinearLayoutManager(getdActivity());
adapter.notifyDataSetChanged();
rvMain.setLayoutManager(layoutManager);
rvMain.setAdapter(adapter);
}
This is the problem.
categories = new ArrayList<>();
Here, you are initialising categories to new ArrayList<>(); It is like you are creating a new arraylist.
Just remove this line.

How to print the json to listview included two data?

I want to display two data on listview through the json input. All the code are alter from internet which I got error. I have not clear logic to understand the meaning of the code. Please give me advice and alter my code.
private void displayArrayList(String jsonStr){
String[] from = {"eventName", "date"};
int[] to = {R.id.eventName, R.id.date};
SimpleAdapter simpleAdapter = new SimpleAdapter (
getActivity(),convertToWordArrayList(jsonStr), R.layout.listview_layout,from,to);
simpleAdapter.notifyDataSetChanged();
listView.setAdapter(simpleAdapter);
}
private ArrayList<HashMap<String, ActivityInfo>> convertToWordArrayList(String jsonStr){
JSONObject jsonObject ;
ArrayList<HashMap<String, ActivityInfo>> arrayList = new ArrayList<HashMap<String, ActivityInfo>>();
try{
jsonObject = new JSONObject(jsonStr);
JSONArray jsonArray=jsonObject.getJSONArray("article");
for (int i=0;i<jsonArray.length();i++){
JSONObject jsonObjRow=jsonArray.getJSONObject(i);
ActivityInfo activityInfo =new ActivityInfo();
activityInfo.eventName = jsonObjRow.getString("eventName");
activityInfo.date = jsonObjRow.getString("date");
HashMap<String, String> map= new HashMap<String, ActivityInfo>();
map.put("eventName", activityInfo.eventName );
map.put("date", activityInfo.date);
JSONArray jsonArray2=jsonObjRow.getJSONArray("content");
for (int j=0;j<jsonArray2.length();j++) {
JSONObject jsonObjRow2 = jsonArray2.getJSONObject(j);
activityInfo.review = jsonObjRow2.getString("review");
}
arrayList.add(activityInfo);
}
}catch (JSONException e){
e.printStackTrace();
}
return arrayList;
}
ActivityInfo class (using the serializable to got the result )
public class ActivityInfo implements Serializable {
String eventName;
String date ;
public void setEventName(String eventName){
this.eventName =eventName ;
}
public String toString(){
return this.eventName;
}
}
Json Response is no problem
{
"article":[
{
"activityId":"5c5d8addd404c",
"eventName":"running",
"date":"2019-02-08",
"content":[
{
"review":"you there"
},
{
"review":"please go away"
},
]
},
{
"activityId":"5c5d8b318df62",
"eventName":"basketball",
"date":"2019-02-13",
"content":[
{
"review":"confirm again"
}
]
},
{
"activityId":"5c5d8b9308018",
"eventName":"playing",
"date":"2019-02-16",
"content":[
{
"review":"provid of you"
}
]
}
]
}
I totally do it like this:
public class menuCreation()
{
public string Category { get; set; }
public string ItemName { get; set; }
public string Price { get; set; }
public string FileName { get; set; }
public menuCreation[] Arr { get; set; }
Stream responseStream = response.GetResponseStream();
StreamReader reader = new StreamReader(responseStream);
string json = (reader.ReadToEnd());
List<menuCreation> items = JsonConvert.DeserializeObject<List<menuCreation>>(json);
Arr = items.ToArray();
}
menuCreation mc = new menuCreation();
foreach (var item in mc.Arr)
{
PictureBox pb = new PictureBox();
pb.Tag = item.ItemName;
pb.Name = item.Price;
}
You can see, I reach itemName with class object.So, you can add listview with this method.
This is your Model Class..
ActivityInfo.java
public class ActivityInfo implements Serializable {
String eventName;
String date;
public void setEventName(String eventName){
this.eventName = eventName ;
}
public String getEventName(){
return this.eventName;
}
public void setDate(String date){
this.date = date;
}
public String getDate(){
return date;
}
}
This will be your final errorfree code..
private void displayArrayList(String jsonStr){
String[] from = {"eventName", "date"};
int[] to = {R.id.eventName, R.id.date};
SimpleAdapter simpleAdapter = new SimpleAdapter (
getActivity(),convertToWordArrayList(jsonStr), R.layout.listview_layout,from,to);
simpleAdapter.notifyDataSetChanged();
listView.setAdapter(simpleAdapter);
}
private ArrayList<HashMap<String,String>> convertToWordArrayList(String jsonStr){
JSONObject jsonObject;
ArrayList<HashMap<String,String>> arrayList = new ArrayList();
try{
jsonObject = new JSONObject(jsonStr);
JSONArray jsonArray=jsonObject.getJSONArray("article");
for (int i=0;i<jsonArray.length();i++){
JSONObject jsonObjRow=jsonArray.getJSONObject(i);
HashMap<String,String> hashMap=new HashMap<>();//create a hashmap to store the data in key value pair
hashMap.put("eventName",jsonObjRow.getString("eventName"));
hashMap.put("date",jsonObjRow.getString("date"));
JSONArray jsonArray2=jsonObjRow.getJSONArray("content");
/*If you want to get Content Reviews from Json, you need to make another attributes like Content in ActivityInfo Class*/
arrayList.add(hashmap);
}
}catch (JSONException e){
e.printStackTrace();
}
return arrayList;
}

Volley post method JSONArray

anyone can suggest me how to POST volley JSONArray body like
{
"mobileNo":"9876543210",
"dobDocuments" : [
"http://server.com/test/uploads/users/5ae699bb8ec8d8218f18c3b4/5ae699f58ec8d8218f18c3b5/dob_proofs/DOB Proof1.jpg","http://server.com/test/uploads/users/5ae699bb8ec8d8218f18c3b4/5ae699f58ec8d8218f18c3b5/dob_proofs/DOB Proof2.jpg"
],
"educationDocuments" : [
"http://server.com/test/uploads/users/5ae699bb8ec8d8218f18c3b4/5ae699f58ec8d8218f18c3b5/edu_proofs/EDU Proof1.jpg","http://server.com/test/uploads/users/5ae699bb8ec8d8218f18c3b4/5ae699f58ec8d8218f18c3b5/edu_proofs/EDU Proof2.jpg"
],
"addressDocuments" : [
"http://server.com/test/uploads/users/5ae699bb8ec8d8218f18c3b4/5ae699f58ec8d8218f18c3b5/add_proofs/ADD Proof1.jpg","http://server.com/test/uploads/users/5ae699bb8ec8d8218f18c3b4/5ae699f58ec8d8218f18c3b5/add_proofs/ADD Proof2.jpg"
]
}
for this instance I've Hashmap which contains this array data.
I searched lot but not getting proper solution for this type.
Thank you..!
Try this
JSONObject sendObject = new JSONObject();
try {
JSONArray dobDocuments = new JSONArray();
dobDocuments.put("https://stackoverflow.com/questions/50128021/volley-post-method-jsonarray");
dobDocuments.put("https://stackoverflow.com/questions/50128021/volley-post-method-jsonarray");
JSONArray educationDocuments = new JSONArray();
educationDocuments.put("https://stackoverflow.com/questions/50128021/volley-post-method-jsonarray");
educationDocuments.put("https://stackoverflow.com/questions/50128021/volley-post-method-jsonarray");
JSONArray addressDocuments = new JSONArray();
addressDocuments.put("https://stackoverflow.com/questions/50128021/volley-post-method-jsonarray");
addressDocuments.put("https://stackoverflow.com/questions/50128021/volley-post-method-jsonarray");
sendObject.put("dobDocuments", dobDocuments);
sendObject.put("educationDocuments", addressDocuments);
sendObject.put("addressDocuments", addressDocuments);
sendObject.put("mobileNo", "9876543210");
} catch (JSONException e) {
}
Log.e("JSONObject",sendObject.toString());
OUTPUT
{
"dobDocuments": ["https:\/\/stackoverflow.com\/questions\/50128021\/volley-post-method-jsonarray", "https:\/\/stackoverflow.com\/questions\/50128021\/volley-post-method-jsonarray"],
"educationDocuments": ["https:\/\/stackoverflow.com\/questions\/50128021\/volley-post-method-jsonarray", "https:\/\/stackoverflow.com\/questions\/50128021\/volley-post-method-jsonarray"],
"addressDocuments": ["https:\/\/stackoverflow.com\/questions\/50128021\/volley-post-method-jsonarray", "https:\/\/stackoverflow.com\/questions\/50128021\/volley-post-method-jsonarray"],
"mobileNo": "9876543210"
}
If you want to use model classes and comfortable with GSON.
Add this to build.gradle
implementation 'com.google.code.gson:gson:2.8.4'
Create class for your request/response
class MyRequest {
private String mobileNo;
private String[] dobDocuments;
private String[] educationDocuments;
private String[] addressDocuments;
public String getMobileNo() {
return mobileNo;
}
public void setMobileNo(String mobileNo) {
this.mobileNo = mobileNo;
}
public String[] getDobDocuments() {
return dobDocuments;
}
public void setDobDocuments(String[] dobDocuments) {
this.dobDocuments = dobDocuments;
}
public String[] getEducationDocuments() {
return educationDocuments;
}
public void setEducationDocuments(String[] educationDocuments) {
this.educationDocuments = educationDocuments;
}
public String[] getAddressDocuments() {
return addressDocuments;
}
public void setAddressDocuments(String[] addressDocuments) {
this.addressDocuments = addressDocuments;
}
}
Now create JSONObject
try {
MyRequest myRequest = new MyRequest();
myRequest.setMobileNo("9876543210");
myRequest.setDobDocuments(new String[] {"http://server.com/test/uploads/users/5ae699bb8ec8d8218f18c3b4/5ae699f58ec8d8218f18c3b5/dob_proofs/DOB Proof1.jpg","http://server.com/test/uploads/users/5ae699bb8ec8d8218f18c3b4/5ae699f58ec8d8218f18c3b5/dob_proofs/DOB Proof2.jpg"});
myRequest.setEducationDocuments(new String[]{ "http://server.com/test/uploads/users/5ae699bb8ec8d8218f18c3b4/5ae699f58ec8d8218f18c3b5/edu_proofs/EDU Proof1.jpg","http://server.com/test/uploads/users/5ae699bb8ec8d8218f18c3b4/5ae699f58ec8d8218f18c3b5/edu_proofs/EDU Proof2.jpg"});
myRequest.setAddressDocuments(new String[]{"http://server.com/test/uploads/users/5ae699bb8ec8d8218f18c3b4/5ae699f58ec8d8218f18c3b5/add_proofs/ADD Proof1.jpg","http://server.com/test/uploads/users/5ae699bb8ec8d8218f18c3b4/5ae699f58ec8d8218f18c3b5/add_proofs/ADD Proof2.jpg"});
JSONObject jsonObject = new JSONObject(new Gson().toJson(myRequest));
Log.e("jsonObject", jsonObject.toString());
} catch (JSONException e) {
e.printStackTrace();
}

how to map a JSON to a java model class

I need to map JSON obj to a class and its arrays to ArrayList in Android and it should have all the children data as well. (with nested arraylists too) and i need to convert updated data list again to jsonobject
my json string is
{
"type": "already_planted",
"crops": [
{
"crop_id": 1,
"crop_name": "apple",
"crop_details": [
{
"created_id": "2017-01-17",
"questions": [
{
"plants": "10"
},
{
"planted_by": "A person"
}
]
},
{
"created_id": "2017-01-30",
"questions": [
{
"plants": "15"
},
{
"planted_by": "B person"
}
]
}
]
},
{
"crop_id": 2,
"crop_name": "Cashew",
"crop_details": [
{
"created_id": "2017-01-17",
"questions": [
{
"plants": "11"
},
{
"planted_by": "c person"
}
]
}
]
}
]
}
First of all, you need to create the class that you are going to map JSON inside.
Fortunately, there is a website that can do it for you here
secondly, you can use google Gson library for easy mapping
1. add the dependency.
dependencies {
implementation 'com.google.code.gson:gson:2.8.6'
}
2. from your object to JSON.
MyData data =new MyData() ; //initialize the constructor
Gson gson = new Gson();
String Json = gson.toJson(data ); //see firstly above above
//now you have the json string do whatever.
3. from JSON to object .
String jsonString =doSthToGetJson(); //http request
MyData data =new MyData() ;
Gson gson = new Gson();
data= gson.fromJson(jsonString,MyData.class);
//now you have Pojo do whatever
for more information about gson see this tutorial.
If you use JsonObject, you can define your entity class as this:
public class Entity {
String type;
List<Crops> crops;
}
public class Crops {
long crop_id;
String crop_name;
List<CropDetail> crop_details;
}
public class CropDetail {
String created_id;
List<Question> questions;
}
public class Question {
int plants;
String planted_by;
}
public void convert(String json){
JsonObject jsonObject = new JsonObject(jsonstring);
Entity entity = new Entity();
entity.type = jsonObject.optString("type");
entity.crops = new ArrayList<>();
JsonArray arr = jsonObject.optJSONArray("crops");
for (int i = 0; i < arr.length(); i++) {
JSONObject crops = arr.optJSONObject(i);
Crops cps = new Crops();
cps.crop_id = crops.optLong("crop_id");
cps.crop_name = crops.optString("crop_name");
cps.crop_details = new ArrayList<>();
JsonArray details = crops.optJsonArray("crop_details");
// some other serialize codes
..........
}
}
So you can nested to convert your json string to an entity class.
Here is how I do it without any packages, this do the work for me for small use cases:
My modal class:
package prog.com.quizapp.models;
import org.json.JSONException;
import org.json.JSONObject;
public class Question {
private String question;
private String correct_answer;
private String answer_a;
private String answer_b;
private String answer_c;
private String answer_d;
public Question() {
}
public Question(String question, String answer_a, String answer_b, String answer_c, String answer_d, String correct_answer) {
this.question = question;
this.answer_a = answer_a;
this.answer_b = answer_b;
this.answer_c = answer_c;
this.answer_d = answer_d;
this.correct_answer = correct_answer;
}
public String getQuestion() {
return question;
}
public void setQuestion(String question) {
this.question = question;
}
public String getCorrect_answer() {
return correct_answer;
}
public void setCorrect_answer(String correct_answer) {
this.correct_answer = correct_answer;
}
public String getAnswer_a() {
return answer_a;
}
public void setAnswer_a(String answer_a) {
this.answer_a = answer_a;
}
public String getAnswer_b() {
return answer_b;
}
public void setAnswer_b(String answer_b) {
this.answer_b = answer_b;
}
public String getAnswer_c() {
return answer_c;
}
public void setAnswer_c(String answer_c) {
this.answer_c = answer_c;
}
public String getAnswer_d() {
return answer_d;
}
public void setAnswer_d(String answer_d) {
this.answer_d = answer_d;
}
#Override
public String toString() {
return "Question{" +
"question='" + question + '\'' +
", correct_answer='" + correct_answer + '\'' +
", answer_a='" + answer_a + '\'' +
", answer_b='" + answer_b + '\'' +
", answer_c='" + answer_c + '\'' +
", answer_d='" + answer_d + '\'' +
'}';
}
public static Question fromJson(JSONObject obj) throws JSONException {
return new Question(
obj.getString("question"),
obj.getString("answer_a"),
obj.getString("answer_b"),
obj.getString("answer_c"),
obj.getString("answer_d"),
obj.getString("correct_answer"));
}
}
And I have another class to get the json file from assets directory and mapped JsonObject to my model class Question:
package prog.com.quizapp.utils;
import android.content.Context;
import android.util.Log;
import org.json.JSONObject;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Iterator;
import prog.com.quizapp.models.Question;
public class JsonSqlQueryMapper {
private Context mContext;
public JsonSqlQueryMapper(Context context) {
this.mContext = context;
}
private static final String TAG = "JsonSqlQueryMapper";
public JSONObject loadJSONFromAsset() {
String json = null;
try {
InputStream is = mContext.getAssets().open("quiz_app.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;
}
try {
JSONObject quizObject = new JSONObject(json).getJSONObject("quiz");
return quizObject;
} catch (Exception e) {
Log.d(TAG, "loadJSONFromAsset: " + e.getMessage());
return null;
}
}
public ArrayList<Question> generateInsertQueryForJsonObjects() {
ArrayList<Question> questions = new ArrayList<>();
JSONObject jsonObject = loadJSONFromAsset();
try {
Iterator<String> iter = jsonObject.keys();
while (iter.hasNext()) {
String key = iter.next();
JSONObject value = jsonObject.getJSONObject(key);
Question question = Question.fromJson(value.getJSONObject("question_two"));
questions.add(question);
Log.d(TAG, "generateInsertQueryForJsonObjects: " + question.getAnswer_a());
}
} catch (Exception e) {
e.printStackTrace();
}
return questions;
}
}
And in my MainActivity -> onCreate:
JsonSqlQueryMapper mapper = new JsonSqlQueryMapper(MainActivity.this);
mapper.generateInsertQueryForJsonObjects();
To check that everything working as I want. Here is the json file if you want to check https://github.com/Blasanka/android_quiz_app/blob/sqlite_db_app/app/src/main/assets/quiz_app.json
Regards!

How to sort JSONArray of JSONObject which contain another JSONObject?

I am able to sort JSONArray of JSONObject but I stuck when I need to sort array like follows:
[{
"key1": "value1",
"key2": "value2",
"key3": {
"key4": "value4",
"key5": "value5"
}
}, {
"key1": "value1",
"key2": "value2",
"key3": {
"key4": "value4",
"key5": "value5"
}
}]
I want to sort this array on "Key4".
Here is my code while sorting on key1
public static JSONArray sortJsonArray(JSONArray array, final String key) throws JSONException
{
List<JSONObject> jsons = new ArrayList<JSONObject>();
for (int i = 0; i < array.length(); i++) {
jsons.add(array.getJSONObject(i));
}
Collections.sort(jsons, new Comparator<JSONObject>() {
#Override
public int compare(JSONObject lhs, JSONObject rhs) {
String lid = null;
String rid = null;
try {
lid = lhs.getString(key);
rid = rhs.getString(key);
} catch (JSONException e) {
e.printStackTrace();
}
// Here you could parse string id to integer and then compare.
return lid.compareTo(rid);
}
});
return new JSONArray(jsons);
}
Just compare lhs.getJSONObject("key3").getString("key4") to rhs.getJSONObject("key3").getString("key4").
Just pasting my code Here(As per #cricket_007 Helps), May this help some others:
public static JSONArray sortJsonArrayOpenDate(JSONArray array) throws JSONException {
List<JSONObject> jsons = new ArrayList<JSONObject>();
for (int i = 0; i < array.length(); i++) {
jsons.add(array.getJSONObject(i));
}
Collections.sort(jsons, new Comparator<JSONObject>() {
#Override
public int compare(JSONObject lhs, JSONObject rhs) {
String lid = null;
String rid = null;
try {
lid = lhs.getJSONObject("key3").getString("key4");
rid = rhs.getJSONObject("key3").getString("key4");
} catch (JSONException e) {
e.printStackTrace();
}
return lid.compareTo(rid);
}
});
return new JSONArray(jsons);
}

Categories