I am building one app in which I request a PHP file from server. This PHP file returns a JSONArray having JSONObjects as its elements e.g.,
[
{
In case if someone returns with the same question for Android platform, you cannot use the inbuilt remove()
method if you are targeting for Android API-18 or less. The remove()
method is added on API level 19. Thus, the best possible thing to do is to extend the JSONArray
to create a compatible override for the remove()
method.
public class MJSONArray extends JSONArray {
@Override
public Object remove(int index) {
JSONArray output = new JSONArray();
int len = this.length();
for (int i = 0; i < len; i++) {
if (i != index) {
try {
output.put(this.get(i));
} catch (JSONException e) {
throw new RuntimeException(e);
}
}
}
return output;
//return this; If you need the input array in case of a failed attempt to remove an item.
}
}
EDIT As Daniel pointed out, handling an error silently is bad style. Code improved.
JSONArray jArray = new JSONArray();
jArray.remove(position); // For remove JSONArrayElement
Note :- If remove()
isn't there in JSONArray
then...
API 19 from Android (4.4) actually allows this method.
Call requires API level 19 (current min is 16): org.json.JSONArray#remove
Right Click on Project Go to Properties
Select Android from left site option
And select Project Build Target greater then API 19
Hope it helps you.
Try this code
ArrayList<String> list = new ArrayList<String>();
JSONArray jsonArray = (JSONArray)jsonObject;
int len = jsonArray.length();
if (jsonArray != null) {
for (int i=0;i<len;i++){
list.add(jsonArray.get(i).toString());
}
}
//Remove the element from arraylist
list.remove(position);
//Recreate JSON Array
JSONArray jsArray = new JSONArray(list);
Edit:
Using ArrayList
will add "\"
to the key and values. So, use JSONArray
itself
JSONArray list = new JSONArray();
JSONArray jsonArray = new JSONArray(jsonstring);
int len = jsonArray.length();
if (jsonArray != null) {
for (int i=0;i<len;i++)
{
//Excluding the item at position
if (i != position)
{
list.put(jsonArray.get(i));
}
}
}
i guess you are using Me version, i suggest to add this block of function manually, in your code (JSONArray.java) :
public Object remove(int index) {
Object o = this.opt(index);
this.myArrayList.removeElementAt(index);
return o;
}
In java version they use ArrayList, in ME Version they use Vector.
To Remove some element from Listview in android then it will remove your specific element and Bind it to listview.
BookinhHistory_adapter.this.productPojoList.remove(position);
BookinhHistory_adapter.this.notifyDataSetChanged();
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;
}