Вот код с помощью которого я сортирую json-массив похожий на ваш.
//Сортировка JSON массива
String strJson;
try {
strJson=jsondb.loadFromFile(jsondb.getWorkDir().getAbsolutePath()+File.separator+"phones.json");
JSONObject dataJsonObj = null;
JSONObject newJsonObj = null;
dataJsonObj = new JSONObject(strJson);
newJsonObj = new JSONObject();
JSONArray phones = dataJsonObj.getJSONArray("phones");
JSONArray newphones=new JSONArray();
int iNumID=0;
int iMasCount=phones.length();
for (int j=0; j<iMasCount; j++) {
int iMaxValue=-1;
int iNumInAray=-1;
for (int i=0; i<phones.length(); i++) {
JSONObject phone = phones.getJSONObject(i);
int iNum = phone.getInt("num");
if (iNum>iMaxValue) {
iMaxValue=iNum;
iNumInAray=i;
}
}//for (int i=0; i<iMasCount; i++)
//Есть кандидат
JSONObject newJsonObjPhone = new JSONObject();
newJsonObjPhone.put("id",++iNumID);
newJsonObjPhone.put("name",phones.getJSONObject(iNumInAray).getString("name"));
newJsonObjPhone.put("phone",phones.getJSONObject(iNumInAray).getString("phone"));
newJsonObjPhone.put("num",phones.getJSONObject(iNumInAray).getString("num"));
newphones.put(newJsonObjPhone);
//Удаляю кандидата из прошлого массива
phones = removeJSONArray(phones,iNumInAray);
}//for (int j=0; j<iMasCount; j++)
newJsonObj.put("data","dbphones");
newJsonObj.put("phones",newphones);
File oldFile = new File(jsondb.getWorkDir().getAbsolutePath()+File.separator+"phones.json");
if (oldFile.exists()) oldFile.delete();
jsondb.saveInFile("phones.json",newJsonObj.toString(4));
Toast.makeText(this, "Сортировка завершена", Toast.LENGTH_LONG).show();
}//try
catch (JSONException e) {
//e.printStackTrace();
Toast.makeText(this, "Ошибка Json", Toast.LENGTH_LONG).show();
}//catch (JSONException e)
Функция removeJSONArray
public JSONArray removeJSONArray( JSONArray jarray,int pos) {
JSONArray Njarray=new JSONArray();
try{
for(int i=0;i<jarray.length();i++){
if(i!=pos)
Njarray.put(jarray.get(i));
}
}catch (Exception e){e.printStackTrace();}
return Njarray;
}
Массив вида
{
"data": "dbphones",
"phones": [
{
"id": 1,
"name": "Абонент1",
"phone": "910xxxxxxx",
"num": "223"
},
{
"id": 2,
"name": "Абонент2",
"phone": "910xxxxxxx",
"num": "210"
},
...
]
}
Сортирую по кол-ву вызовов, вам можно переделать под свои нужды
raiting
. По кнопке "Новое", по ключуdate
. "Все" - по умолчанию. Разобрался с функциейCollections.sort
. Json строку преобразовываю вarrayList
, но как сортировать массив несколько раз в одном активити по нажатию кнопки?