How fix " Not a primitive array" - java

I trying to parse this json.
[
{
"id": 2,
"name": "612",
"code": "auditorium 612"
},
{
"id": 3,
"name": "613",
"code": "auditorium 613"
}
]
JSONException returns an error " Not a primitive array". I tryed to parse JsonObjectRequest, but another error occurred. Finally I came to option JsonArrayRequest
W/System.err: org.json.JSONException: Not a primitive array: class org.json.JSONArray
at org.json.JSONArray.<init>(JSONArray.java:116)
at com.example.dyplom.MainActivity$4.onResponse(MainActivity.java:126)
at com.example.dyplom.MainActivity$4.onResponse(MainActivity.java:122)
at com.android.volley.toolbox.JsonRequest.deliverResponse(JsonRequest.java:90)
at com.android.volley.ExecutorDelivery$ResponseDeliveryRunnable.run(ExecutorDelivery.java:102)
at android.os.Handler.handleCallback(Handler.java:790)
W/System.err: at android.os.Handler.dispatchMessage(Handler.java:99)
W/System.err: at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6494)
at java.lang.reflect.Method.invoke(Native Method)
W/System.err: at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
W/System.err: at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)
Here is the parser method.
private void loadStrings()
{
String url_head = "http://10.0.2.2:8080/rStrings";
JsonArrayRequest request = new JsonArrayRequest(Request.Method.GET,url_head, null, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
try {
JSONArray jsonArray_string_list = new JSONArray(response);
main_name_rString = new String[jsonArray_string_list.length()];
main_code_rString = new String[jsonArray_string_list.length()];
for (int i = 0; i < jsonArray_string_list.length();i++){
JSONObject string_params_string_list = jsonArray_string_list.getJSONObject(i);
Long string_id = string_params_string_list.getLong("id");
String string_name = string_params_string_list.getString("name");
String string_code = string_params_string_list.getString("code");
main_id_rSting[i]=string_id;
main_name_rString[i] = string_name;
main_code_rString[i] = string_code;
Log.i("Id", String.valueOf(main_id_rSting[i]));
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(), "Error", Toast.LENGTH_SHORT).show();
error.printStackTrace();
}
});
mQueue.add(request);
}
I looked at similar questions, but I didn't really find anything. How can I fix it? Maybe I don't see smth.

If the onResponse method already received the (JSONArray response), you don't need to create again a new JSONArray in the next line in your code. It would help if I can see the line where the error happen.

Related

Error when converting a string to JSONObject. What can it be caused by? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 14 hours ago.
Improve this question
When trying to convert a JSON string to a JSONObject in Java, a RuntimeError comes out
Here is my implementation of this in Java
buttonSubmit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
textViewError.setVisibility(View.GONE);
phone = String.valueOf(editTextPhone.getText());
password = String.valueOf(editTextPassword.getText());
RequestQueue queue = Volley.newRequestQueue(getApplicationContext());
String url ="http://192.168.0.113/microgatgets/login.php";
StringRequest stringRequest = new StringRequest(Request.Method.POST, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
String status = jsonObject.getString("status");
String message = jsonObject.getString("message");
if (status.equals("success")) {
Toast.makeText(MainActivity.this, "Авторизация успешна!", Toast.LENGTH_SHORT).show();
name = jsonObject.getString("name");
phone = jsonObject.getString("phone");
apiKey = jsonObject.getString("apiKey");
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("logged", "true");
editor.putString("name", name);
editor.putString("phone", phone);
editor.putString("apiKey", apiKey);
editor.apply();
Intent intent = new Intent(getApplicationContext(), CardActivity.class);
startActivity(intent);
finish();
}
else {
textViewError.setText(message);
textViewError.setVisibility(View.VISIBLE);
}
} catch (JSONException e) {
throw new RuntimeException(e);
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
textViewError.setText(error.getLocalizedMessage());
textViewError.setVisibility(View.VISIBLE);
}
}){
protected Map<String, String> getParams(){
Map<String, String> paramV = new HashMap<>();
paramV.put("phone", phone);
paramV.put("password", password);
return paramV;
}
};
queue.add(stringRequest);
}
});
And here is the JSON string itself
{ "status": "failed", "message": "All fields are required" }
Stack trace
FATAL EXCEPTION: main
Process: com.example.microgadgets, PID: 25538
java.lang.RuntimeException: org.json.JSONException: Value <br of
java.lang.String cannot be converted to JSONObject at com.example.microgadgets.MainActivity$1$1.onResponse(MainActivity.java:96)
at com.example.microgadgets.MainActivity$1$1.onResponse(MainActivity.java:64)
at com.android.volley.toolbox.StringRequest.deliverResponse(StringRequest.java:82)
at com.android.volley.toolbox.StringRequest.deliverResponse(StringRequest.java:29)
at com.android.volley.ExecutorDelivery$ResponseDeliveryRunnable.run(ExecutorDelivery.java:102)
at android.os.Handler.handleCallback(Handler.java:955)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:228)
at android.app.ActivityThread.main(ActivityThread.java:8689)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:613)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1085)
Caused by: org.json.JSONException: Value <br of type java.lang.String cannot be converted to JSONObject
at org.json.JSON.typeMismatch(JSON.java:112)
at org.json.JSONObject.<init>(JSONObject.java:169)
at org.json.JSONObject.<init>(JSONObject.java:182)
at com.example.microgadgets.MainActivity$1$1.onResponse(MainActivity.java:68)
at com.example.microgadgets.MainActivity$1$1.onResponse(MainActivity.java:64) 
at com.android.volley.toolbox.StringRequest.deliverResponse(StringRequest.java:82) 
at com.android.volley.toolbox.StringRequest.deliverResponse(StringRequest.java:29) 
at com.android.volley.ExecutorDelivery$ResponseDeliveryRunnable.run(ExecutorDelivery.java:102) 
at android.os.Handler.handleCallback(Handler.java:955) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:228) 
at android.app.ActivityThread.main(ActivityThread.java:8689) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:613) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1085) 
I hope I added what I needed. If that's not the case, correct me, and I'm also writing all this because I just need to add some text. In response, I get a JSON string from the backend for my application

Convert a Gson Array within an Object

I am trying to extract "levels" from this server response. I am a bit new to Android Development. I need help parsing this API response to a List of a POJO.
{
"levels": [
{
"id": 1,
"level": 0,
"name": "Level 0"
},
{
"id": 2,
"level": 1,
"name": "Level 1"
}
]
}
A kotlin Data Class for the Level:
data class Level(var id:Int, var level: Int, var name: String?=null)
Here is a custom Gson Deserializer
JsonDeserializer:
public class RestDeserializer<T> implements JsonDeserializer<T> {
private Class<T> clasz;
private String key;
public RestDeserializer(Class<T> clasz, String key) {
this.clasz = clasz;
this.key = key;
}
#Override
public T deserialize(
JsonElement jsonElement,
Type type,
JsonDeserializationContext jsonDeserializationContext
) throws JsonParseException{
JsonElement content = jsonElement.getAsJsonObject().get(key);
return new Gson().fromJson(content, clasz);
}
}
Retrofit Client:
interface LevelService {
#GET("api/levels")
fun getLevels():Call<List<Level>>
companion object {
fun levels(context: Context): LevelService{
Gson gson = new GsonBuilder()
.registerTypeAdapter(Level.class, new RestDeserializer<>(Level[].class, "levels"))
.create();
val retrofit = Retrofit.Builder()
.addConverterFactory(GsonConverterFactory.create(gson))
.baseUrl(Constants.BASE_URL)
.client(httpClient.build())
.build();
return retrofit.create(LevelService::class.java)
}
}
}
Finally Call:
fun getLevels(){
val apiService = LevelService.levels(applicationContext)
apiService.getLevels().enqueue(object : Callback<List<Level>>{
override fun onFailure(call: Call<List<Level>>?, t: Throwable?) {
Log.d("Error: FATAL)", "Error:(")
t!!.printStackTrace()
}
override fun onResponse(call: Call<List<Level>>?, response: Response<List<Level>>?) {
if (response!!.isSuccessful){
Log.d("SUCCESS", response.body().toString())
}
else{
Log.d("Error:)", response.errorBody().toString())
}
}
})
}
But it is failing giving an errorI hope its clear:
java.lang.IllegalStateException: Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 2
Any help is greatly appreciated!!
StakeTrace is as follows:
W/System.err: java.lang.IllegalStateException: Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 2 path $
at com.google.gson.stream.JsonReader.beginArray(JsonReader.java:350)
at com.google.gson.internal.bind.CollectionTypeAdapterFactory$Adapter.read(CollectionTypeAdapterFactory.java:80)
at com.google.gson.internal.bind.CollectionTypeAdapterFactory$Adapter.read(CollectionTypeAdapterFactory.java:61)
at retrofit2.converter.gson.GsonResponseBodyConverter.convert(GsonResponseBodyConverter.java:39)
W/System.err: at retrofit2.converter.gson.GsonResponseBodyConverter.convert(GsonResponseBodyConverter.java:27)
at retrofit2.ServiceMethod.toResponse(ServiceMethod.java:122)
at retrofit2.OkHttpCall.parseResponse(OkHttpCall.java:217)
at retrofit2.OkHttpCall$1.onResponse(OkHttpCall.java:116)
at okhttp3.RealCall$AsyncCall.execute(RealCall.java:153)
at okhttp3.internal.NamedRunnable.run(NamedRunnable.java:32)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
at java.lang.Thread.run(Thread.java:818)
You have to change RestDeserializer to get the values from JsonArray rather than directly from JsonObject.
JsonArray array = je.getAsJsonObject().getAsJsonArray(key);

How to Parse Json Objects of Json Object and of Object (outdated) [duplicate]

This question already has answers here:
How to parse JSON in Java
(36 answers)
Closed 5 years ago.
I'm trying to parse multiple objects,Bellow i'm receiving Json Sample The requirement completed and my question now outdated, can someone please up-vote to help me for asking next question? Will he helpfull for and thanks for
{
"0": //outer objects are multiples, i just post one object for sample
{
"id": "1",
"name": "B2 MR1",
"description":
{
"0": //it is also multiple objects m just showing one
{
"title": "Carve the Future",
"description": "Welcome to Meeting Room 1",
"push_notification": "Carve the Future",
}
}
},//after that the next obj will be show
.
.
}
In second object 1 i also have above keys and values, i can't handel it, here is my Model.
public class JsonModel {
private String id; //getter setter
private String name; //getter setter
List<InnerDescprtion> description; //getter setter
}
Here is my InnerDescprtion Model
private class InnerDescprtion {
private String id; //getter setter
private String title; //getter setter
}
And below is my java code for parsing it using Gson,
JsonModel outterModelClass= null;
List<JsonModel> listObj = new ArrayList<>();
for (int i = 0; i < responseJson.length(); i++) {
try {
outterModelClass= new Gson().fromJson(responseJson.getString(String.valueOf(i)), JsonModel.class);
listObj.add(outterModelClass); //here i'm getting exception,,
} catch (JSONException e) {
e.printStackTrace();
}
}
I get the solution, Please up-vote to help me.
If it is possible for you I would change the json to something like this:
[{
"id": "1",
"name": "B2 MR1",
"description": [{
"id" : "1-1",
"title": "Carve the Future",
"description": "Welcome to Meeting Room 1",
"push_notification": "Carve the Future"
}]
},
{
"id": "2",
"name": "B2 MR2",
"description": [{
"id" : "2-1",
"title": "Carve the Future 2",
"description": "Welcome to Meeting Room 2",
"push_notification": "Carve the Future 2"
}]
}
]
Then your approach should work with just a few changes:
BufferedReader br = new BufferedReader(new FileReader("c:/test/test.json"));
Type listType = new TypeToken<ArrayList<JsonModel>>(){}.getType();
List<JsonModel> outterModels = new Gson().fromJson(br, listType);
If you can't change the json I would suggest to use another JSON library like json simple and extract everything manually.
Your 'listObj' should be defined this way:
ArrayList<JsonModel> listObj = new ArrayList<JsonModel>();
Well that is a nasty looking JSON. However I recommend you use volley android library. I had a task with somewhat similar problem. Only there was a single object inside of another object. To include volley in your project, update your build.gradle app module with compile 'com.android.volley:volley:1.0.0' inside dependencies{}. baseUrl is the url where you are fetching the JSON from.
Then you can do something like:
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.GET,
baseUrl,
null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
// Parsing json object response
// response will be a json object
for (int i=0; i<response.length(); i++){
JSONObject obj = response.getJSONObject(i);
//id
//name
try{
for (int j=0; j<obj.length() ; j++) {
JSONObject description = obj.getJSONObject(j);
//title
//description
//push notification
}
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(),
"Error: " + e.getMessage(),
Toast.LENGTH_LONG).show();
}
}
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(),
"Error: " + e.getMessage(),
Toast.LENGTH_LONG).show();
}
hidepDialog();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
VolleyLog.d(TAG,"Error: "+ volleyError.getMessage() );
Toast.makeText(getApplicationContext(), volleyError.getMessage(), Toast.LENGTH_SHORT).show();
hidepDialog();
}
});
//adding request to request queue
AppController.getmInstance().addToRequestQueue(jsonObjReq);
Add this in your parseJSON(){} method or whatever you've named it.
I have not tried doing what you are trying do to. But it seems doable, with the use of volley library.

Android: Unable to display JSON Data, unknown reason

There is no error in the app, the logcat also does not show anything useful, the app doesn't crash, but, it also doesn't show anything. Here is the type of JSON response I'm receiving:
{
"backdrop_path": "/mmxxEpTqVdwBlu5Pii7tbedBkPC.jpg",
"created_by": [
{
"id": 1216615,
"name": "Andrew Kreisberg",
"profile_path": "/giFmwdBAw6uwC8yeHPaW6dq6YT8.jpg"
},
{
"id": 211962,
"name": "Geoff Johns",
"profile_path": "/xkaRZu1o1NILQ4PcRXqnjOrJ0Y0.jpg"
}
],
"episode_run_time": [
44
],
"first_air_date": "2014-10-07",
"genres": [
{
"id": 18,
"name": "Drama"
},
{
"id": 10765,
"name": "Sci-Fi & Fantasy"
}
],
"homepage": "http://www.cwtv.com/shows/the-flash/",
"id": 60735,
"in_production": true,
"languages": [
"en"
],
"last_air_date": "2017-04-25",
"name": "The Flash",
"networks": [
{
"id": 71,
"name": "The CW"
}
],
"number_of_episodes": 65,
"number_of_seasons": 3,
"origin_country": [
"US"
],
"original_language": "en",
"original_name": "The Flash",
"overview": "After a particle accelerator causes a freak storm, CSI Investigator Barry Allen is struck by lightning and falls into a coma. Months later he awakens with the power of super speed, granting him the ability to move through Central City like an unseen guardian angel. Though initially excited by his newfound powers, Barry is shocked to discover he is not the only \"meta-human\" who was created in the wake of the accelerator explosion -- and not everyone is using their new powers for good. Barry partners with S.T.A.R. Labs and dedicates his life to protect the innocent. For now, only a few close friends and associates know that Barry is literally the fastest man alive, but it won't be long before the world learns what Barry Allen has become...The Flash.",
"popularity": 50.611816,
"poster_path": "/lUFK7ElGCk9kVEryDJHICeNdmd1.jpg",
"production_companies": [
{
"name": "Warner Bros. Television",
"id": 1957
},
{
"name": "DC Entertainment",
"id": 9993
},
{
"name": "Berlanti Productions",
"id": 27711
}
],
"seasons": [
{
"air_date": "2016-04-19",
"episode_count": 5,
"id": 79954,
"poster_path": null,
"season_number": 0
},
{
"air_date": "2014-10-07",
"episode_count": 23,
"id": 60523,
"poster_path": "/hJysBrladxYuP5065vCAf91KcyB.jpg",
"season_number": 1
},
{
"air_date": "2015-10-06",
"episode_count": 23,
"id": 66922,
"poster_path": "/8xWZPVX1cv9V5YD1RPeLj9QZDE9.jpg",
"season_number": 2
},
{
"air_date": "2016-10-04",
"episode_count": 19,
"id": 77888,
"poster_path": "/6F8v0n37xbGY4syGcW6pRcB9BcY.jpg",
"season_number": 3
}
],
"status": "Returning Series",
"type": "Scripted",
"vote_average": 6.7,
"vote_count": 984
}
Here is a screenshot of what the app is displaying:
Click here to see the image
Please note that the main poster, backdrop and all the other things including the tabLayout are a part of the MainActivity, the viewPager consists of 5 fragments of which 2 work fine in this activity; one is supposed to work and is working when I use it with another activity but doesn't work here and the other two don't work at all.
The MainActivity is able to load the data fine. Before now, I was trying to send a Bundle from this activity to the rest fragments, but out of five, three turned out to be null, the rest two are still loading the data just fine. Now, I'm using a function in MainActivity which returns the data and then am using the getActivity() method in the fragments, I know that I won't be able to use these fragments anywhere else. Now, I've checked everything and the fragments are receiving the data, but even now, they aren't displaying anything. Here is the code parsing the JSON, I'm using a recyclerView, also I'm using Volley inside AsyncTask so that the default messgaes are displayed only when everything is set:
private class connectToTheInternet extends AsyncTask<String, Void, Void> {
#Override
protected Void doInBackground(String... strings) {
StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d("receivedData", response);
try {
JSONObject parentObject = new JSONObject(response);
Log.d("receivedData", response);
JSONArray genreArray = parentObject.getJSONArray("genres");
for (int i = 0; i < genreArray.length(); i++) {
JSONObject tempObject = genreArray.getJSONObject(i);
if (i < genreArray.length() - 1) {
genreCollector = genreCollector + tempObject.getString("name") + ", ";
} else
genreCollector = genreCollector + tempObject.getString("name");
}
genre.setText(genreCollector);
if (genreArray.length() == 1) {
genreTag.setText("Genres: ");
} else
genreTag.setText("Genre: ");
JSONArray creatorArray = parentObject.getJSONArray("created_by");
for (int i = 0; i < creatorArray.length(); i++) {
JSONObject tempObject = creatorArray.getJSONObject(i);
if (i < creatorArray.length() - 1) {
creatorName = creatorName + tempObject.getString("name") + ", ";
} else {
creatorName = creatorName + tempObject.getString("name");
}
}
createdBy.setText(creatorName);
JSONArray runTimeArray = parentObject.getJSONArray("episode_run_time");
int arrayLength = runTimeArray.length();
for (int i = 0; i < runTimeArray.length(); i++) {
//No need for a tempObject, as the values in this array don't have a 'key'.....
runTimeCollector += runTimeArray.getInt(i);
}
runTimeCollector = runTimeCollector / arrayLength;
runtime.setText(runTimeCollector);
numberOfSeasons.setText(parentObject.getInt("number_of_seasons"));
numberOfEpisodes.setText(parentObject.getInt("number_of_episodes"));
lastAirDate.setText(convertDate(parentObject.getString("last_air_date")));
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(getContext(), e.getLocalizedMessage(), Toast.LENGTH_SHORT).show();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getContext(), "Error Detected", Toast.LENGTH_SHORT).show();
}
});
RequestQueue requestQueue = Volley.newRequestQueue(getContext());
requestQueue.add(stringRequest);
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
runTimeTag.setText("RunTime:");
numberOfSeasonsTag.setText("Number Of Seasons:");
numberOfEpisodesTag.setText("Number Of Episodes:");
lastAirDateTag.setText("Last Air Date:");
createdByTag.setText("Created By:");
overViewTag.setText("OVERVIEW:");
}
}
Here is the logcat trace:
04-01 09:23:54.292 1503-1503/com.example.android.jsontutorial W/System.err: org.json.JSONException: No value for credits
04-01 09:23:54.292 1503-1503/com.example.android.jsontutorial W/System.err: at org.json.JSONObject.get(JSONObject.java:389)
04-01 09:23:54.292 1503-1503/com.example.android.jsontutorial W/System.err: at org.json.JSONObject.getJSONObject(JSONObject.java:609)
04-01 09:23:54.292 1503-1503/com.example.android.jsontutorial W/System.err: at com.example.android.jsontutorial.credits$1.onResponse(credits.java:109)
04-01 09:23:54.293 1503-1503/com.example.android.jsontutorial W/System.err: at com.example.android.jsontutorial.credits$1.onResponse(credits.java:103)
04-01 09:23:54.293 1503-1503/com.example.android.jsontutorial W/System.err: at com.android.volley.toolbox.StringRequest.deliverResponse(StringRequest.java:60)
04-01 09:23:54.293 1503-1503/com.example.android.jsontutorial W/System.err: at com.android.volley.toolbox.StringRequest.deliverResponse(StringRequest.java:30)
04-01 09:23:54.293 1503-1503/com.example.android.jsontutorial W/System.err: at com.android.volley.ExecutorDelivery$ResponseDeliveryRunnable.run(ExecutorDelivery.java:99)
04-01 09:23:54.293 1503-1503/com.example.android.jsontutorial W/System.err: at android.os.Handler.handleCallback(Handler.java:751)
04-01 09:23:54.293 1503-1503/com.example.android.jsontutorial W/System.err: at android.os.Handler.dispatchMessage(Handler.java:95)
04-01 09:23:54.293 1503-1503/com.example.android.jsontutorial W/System.err: at android.os.Looper.loop(Looper.java:154)
04-01 09:23:54.293 1503-1503/com.example.android.jsontutorial W/System.err: at android.app.ActivityThread.main(ActivityThread.java:6077)
04-01 09:23:54.293 1503-1503/com.example.android.jsontutorial W/System.err: at java.lang.reflect.Method.invoke(Native Method)
04-01 09:23:54.293 1503-1503/com.example.android.jsontutorial W/System.err: at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)
04-01 09:23:54.293 1503-1503/com.example.android.jsontutorial W/System.err: at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
04-01 09:24:09.710 1503-1682/com.example.android.jsontutorial D/Volley: [132] BasicNetwork.logSlowRequests: HTTP response for request=<[ ] https://api.themoviedb.org/3/tv/top_rated?api_key=43630259102f25bfa2d21a3039b&language=en-US&page=1 0x89bd75e7 NORMAL 1> [lifetime=22435], [size=18147], [rc=200], [retryCount=1]
04-01 09:36:07.024 1503-1510/com.example.android.jsontutorial W/art: Suspending all threads took: 5.062ms
04-01 09:39:12.493 1503-1510/com.example.android.jsontutorial W/art: Suspending all threads took: 26.896ms
Please help as I'm new and don't know what to do.....
P.S. 'Credits' is the name of another java class that is supposed to display a list of all the celebrities acting in that particular movie. This isn't supposed to hinder the functioning of the other two classes that aren't displaying any data.
You are accessing credits key value which is not exiting in your json. So please try to get credits value like this, it will get credits key value if its exits in json otherwise it will skip.
if your credit value is string then please try to use like
String credit = jsonObject.optString("credits")
if your credit value is JSONObject then please try to use like
JSONObject credit = jsonObject.optJSONObject("credits")
if your credit value is JSONArray then please try to use like
JSONArray credit = jsonObject.optJSONArray("credits")
The important bit seems to be org.json.JSONException: No value for credits. Are you trying to get a tag called credits (that doesn't exist in your JSON data)? If so, do a check like
if(jsonObject.has("credits")) {
...
}

Why I get java.util.ConcurrentModificationException error?

I'm having troubles with this code:
protected void onPostExecute(ArrayList<Example> examples){
for(Example i : examples)
{
customAdapter.add(i);
}
listExamples.setAdapter(customAdapter);
}
where listExamples it's a ListView that I have in my mainActivity layout.
The error that it gives to me it's the java.util.ConcurrentModificationException error. I know that it happens when you modify, for example, an ArrayList inside the loop but here I don't really modify my ArrayList of values. I just add the objects of Example into my CustomAdapter (which is not iterating in the loop).
Note: As you can see, this code it's wrap in the onPostExecute part of my AsynkTask method.
I look on the Internet questions and here in Stackoverflow but I coudn't solve my problem. In all the questions that I have seen I see that they have an ArrayList that they are modifying inside the loop, but it is not my case.
If any of you have idea about how to solve it or if I'm wrong with the concepts that I put above please let me know.
Thanks in advance!
EDIT: The stack trace of my log console (I simplified it by post only the Error logs)
06-05 02:22:31.891 24678-24678/ccom.example.user.project E/﹕ appName=com.example.user.project, acAppName=/system/bin/surfaceflinger
06-05 02:22:31.891 24678-24678/com.example.user.project E/﹕ 0
06-05 02:22:31.891 24678-24678/com.example.user.project E/﹕ appName=com.example.user.project, acAppName=/system/bin/surfaceflinger
06-05 02:22:31.891 24678-24678/com.example.user.project E/﹕ 0
06-05 02:22:32.953 24678-24678/com.example.user.project E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.example.user.project, PID: 24678
java.util.ConcurrentModificationException
at java.util.ArrayList$ArrayListIterator.next(ArrayList.java:573)
at com.example.user.project.MainActivity$chargeExample.onPostExecute(MainActivity.java:192)
at com.example.user.project.MainActivity$chargeExample.onPostExecute(MainActivity.java:131)
at android.os.AsyncTask.finish(AsyncTask.java:632)
at android.os.AsyncTask.access$600(AsyncTask.java:177)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:645)
at android.os.Handler.dispatchMessage(Handler.java:110)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:5333)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:828)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:644)
at dalvik.system.NativeStart.main(Native Method)
EDIT 2: Here is my asynktask method and the code in doInBackground()
class chargeExample extends AsyncTask<Void, Integer, ArrayList<Example>> {
protected void onPreExecute(){
}
protected ArrayList<Example> doInBackground(Void... params) {
String url = "url of my GET method of my API REST";
HttpGet method = new HttpGet(url);
method.setHeader("content-type", "application/json");
try{
HttpResponse response = httpClient.execute(method);
String responseString = EntityUtils.toString(response.getEntity());
JSONArray responseJSON = new JSONArray(responseString);
for(int i=0; i<responseJSON.length(); i++){
JSONObject object = responseJSON.getJSONObject(i);
int idMain = object.getInt("idMain");
String date = object.getString("date");
String name = object.getString("name");
double value = object.getDouble("value");
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-M-dd");
Date datePar = sdf.parse(date);
examp.add(new Example(idMain, datePar, name, value));
}
}catch(Exception ex){
Log.e("ServicioRest", ex.toString());
}
return examp;
}
From your comments it seems that the list you are iterating over examples is the same list that backs the customAdapter adapter, which means that when you add/remove items from customAdapter the items will also be added/removed from the list that examples refers to. In this case, to prevent the exception, you can do something like this:
class chargeExample extends AsyncTask<Void, Integer, ArrayList<Example>> {
protected void onPreExecute(){
}
protected ArrayList<Example> doInBackground(Void... params) {
ArrayList<Example> newList = new ArrayList<Example>();
String url = "url of my GET method of my API REST";
HttpGet method = new HttpGet(url);
method.setHeader("content-type", "application/json");
try{
HttpResponse response = httpClient.execute(method);
String responseString = EntityUtils.toString(response.getEntity());
JSONArray responseJSON = new JSONArray(responseString);
for(int i=0; i<responseJSON.length(); i++){
JSONObject object = responseJSON.getJSONObject(i);
int idMain = object.getInt("idMain");
String date = object.getString("date");
String name = object.getString("name");
double value = object.getDouble("value");
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-M-dd");
Date datePar = sdf.parse(date);
newList.add(new Example(idMain, datePar, name, value));
}
}catch(Exception ex){
Log.e("ServicioRest", ex.toString());
}
return newList;
}
and in the onPostExecute(...)
protected void onPostExecute(ArrayList<Example> examples){
for(Example i : examples)
{
customAdapter.add(i);
}
customAdapter.notifyDataSetChanged();
}

Categories