How to clear the data from a JSONArray
there is nothing like:
jsonArray.clear();
not even:
jsonArray.remove(index);
which was suggested here:
How do I remove a specific element from a JSONArray?
Thank you
How to clear the data from a JSONArray
there is nothing like:
jsonArray.clear();
not even:
jsonArray.remove(index);
which was suggested here:
How do I remove a specific element from a JSONArray?
Thank you
jsonArray = new JSONArray(new ArrayList<String>());
this is not a perfect answer but you can do like this,
jsonArray=new jsonArray("[{}]");
EDIT
As per suggestion in comment, you can also use below code:
jsonArray=new jsonArray();
Just made Local Variables
JSONArray jsonArray = new JSONArray();
jsonArray.put(productlist);
Every time jsonserver data add using local block if u declear global block then need for clear jsonarray
I don't think "new JSONArray()" is a good solution.
Sometimes you will need to access the JSONArray object from within an inner class,so you have to declare the JSONArray object as final, and then you can't assign it to a new one anymore.
The best way is to remove its elements by loop.
while(myjsonarray.length()>0)
{
myjsonarray.remove(0);
}
You said "there is nothing like jsonArray.remove(index);", and also tagged this question with "java", "android"
But now I am using Android Studio 3.6.3, and JSONArray class has this method, and you can find it in Android Studio official documents as well. Therefore, I guess you should edit the title of the question like "why my android studio doesn't has the full methods of JSONArray class"
I try everything but the only thing that worked for me was
jsonArray.clear();
or you can make it local variable again
JSONArray jsonArray = new JSONArray();
In the library I have, there doesn't seem to be any way to call clear()
of the private ArrayList
inside of the JSONObject
. It does however have public Object remove(int index)
. I am just using new JSONObject()
:(
jsonArray.clear();
This worked for me. I was using JSONArray from org.json (not org.json.simple) library.
You need to run a while loop across the length of the JSONArray and at each time delete the first index. the loop will reach a stage when the length of the JSONArray is zero to show the JSONArray is not empty and and cleared.
while (optionArray.length() > 0) {
optionArray.remove(0)
}