Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing Object from JSONArray

I have an application that gets an api key and account name from a webservice, I am storing this apikey and account name for further use(multiple accounts and apikeys).

because you can only store primitive types in the sharedPreferences I parse the JSONArray toString. In another part of the application the user must be able to remove an account from his app. So I retrieve the string and Parse it back to an JSONArray.

how do I remove an JSONObject from the array and save it so I can parse it back to an string and save it again?

like image 943
Maikel Bollemeijer Avatar asked Mar 06 '26 05:03

Maikel Bollemeijer


2 Answers

You should convert it in arraylist and remove object and create jsonarray,,,

ArrayList<String> list = new ArrayList<String>();
//First Position remove
list.remove(0);
JSONArray jsArray = new JSONArray(list);
like image 179
Samir Mangroliya Avatar answered Mar 07 '26 17:03

Samir Mangroliya


i use:

public static 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;

}
like image 23
Fabio Guerra Avatar answered Mar 07 '26 19:03

Fabio Guerra



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!