Error of JSONObject cannot be converted to JSONArray - arrays

I am not able to pass the data from API json to my textview respectively
I am getting "org.json.JSONObject cannot be converted to JSONArray" error
ERRORS :
W/System.err: org.json.JSONException: Value {"message":"accurate","cod":"200","count":1,"list":[{"id":1252948,"name":"Warangal","coord":{"lat":18,"lon":79.5833},"main":{"temp":315.66,"feels_like":314.6,"temp_min":315.66,"temp_max":315.66,"pressure":1002,"humidity":16,"sea_level":1002,"grnd_level":975},"dt":1590404957,"wind":{"speed":2.13,"deg":129},"sys":{"country":"IN"},"rain":null,"snow":null,"clouds":{"all":53},"weather":[{"id":803,"main":"Clouds","description":"broken clouds","icon":"04d"}]}]}
of type org.json.JSONObject cannot be converted to JSONArray
W/System.err: at org.json.JSON.typeMismatch(JSON.java:112)
This is my MainActivity code :
public class MainActivity extends AppCompatActivity {
TextView temp, sunraise, sunsets, wind, pressure, visibility, humidity;
EditText search;
ConstraintLayout constraintLayout;
ImageButton search_btn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
temp = findViewById(R.id.temp);
sunraise = findViewById(R.id.sunrise);
sunsets = findViewById(R.id.sunset);
wind = findViewById(R.id.wind);
pressure = findViewById(R.id.pressure);
visibility = findViewById(R.id.visibility);
humidity = findViewById(R.id.humidity);
search = findViewById(R.id.your_city);
constraintLayout = findViewById(R.id.constraintLayout);
search_btn = findViewById(R.id.search_btn);
search_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ConnectivityManager ConnectionManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
assert ConnectionManager != null;
NetworkInfo networkInfo = ConnectionManager.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnected()) {
new WeatherData().execute();
} else {
Snackbar snackbar = Snackbar.make(constraintLayout, "check your Internet connection", Snackbar.LENGTH_LONG);
snackbar.show();
}
}
});
}
class WeatherData extends AsyncTask<String, Void, String> {
String City = search.getText().toString();
#Override
protected String doInBackground(String... strings) {
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url("https://community-open-weather-map.p.rapidapi.com/find?type=link%252C%20accurate&units=imperial%252C%20metric&q=warangal")
.get()
.addHeader("x-rapidapi-host", "community-open-weather-map.p.rapidapi.com")
.addHeader("x-rapidapi-key", "a65ed4164bmshecc6a41b1453609p12d370jsn36dc92fffc6d")
.build();
try {
Response response = client.newCall(request).execute();
return response.body().string();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String s) {
if (s != null) {
try {
JSONArray jsonObject = new JSONArray(s);
if (jsonObject.length() > 0) {
JSONArray list = jsonObject.getJSONArray(Integer.parseInt("list"));
JSONObject o = list.getJSONObject(Integer.parseInt("0"));
JSONObject main = o.getJSONObject("main");
String temperature = main.getString("temp");
String press = main.getString("pressure");
temp.setText(temperature);
pressure.setText(press);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
}
This is my JSON :
{
"message":"accurate",
"cod":"200","count":1,
"list":
[{
"id":1252948,
"name":"Warangal",
"coord":
{
"lat":18,
"lon":79.5833
},
"main":
{
"temp":317.1,
"feels_like":316.2,
"temp_min":317.1,
"temp_max":317.1,
"pressure":1003,
"humidity":15,
"sea_level":1003,
"grnd_level":976
},
"dt":1590397763,
"wind":
{
"speed":1.96,
"deg":117
},
"sys":
{
"country":"IN"
},
"rain":null,
"snow":null,
"clouds":{"all":36
},
"weather":
[{
"id":802,
"main":"Clouds",
"description":"scattered clouds",
"icon":"03d"
}]
}]
}
I am just testing to display the json output into my respective textview.After my code is succesfull i will functionalize the search field to get data from API.
Can anyone help me out from this error !
Thank you !

First check if its a json array or json object before assigning if (json instanceof JSONObject)
Any why are you parsing string to integer?

Related

JSONArray cannot be converted to JSONObject error when used as similar code

I get this error when I did the same this to my register method, I used this on my Login and it works well, but in register I get the error that the array cannot be converted to JSONObject, I am trying to put the array to convert it to JSONObject to send it to my PHP code for the database
This is my register method
private void registerUser() {
final String phone = phonenumber.getText().toString().trim();
final String lname = lastname.getText().toString().trim();
final String fname = fullname.getText().toString().trim();
final String mname = middlename.getText().toString().trim();
final String add = address.getText().toString().trim();
final String count = country.getText().toString().trim();
//first we will do the validations
if (TextUtils.isEmpty(lname)) {
lastname.setError("Please your Last Name");
lastname.requestFocus();
return;
}
if (TextUtils.isEmpty(fname)) {
fullname.setError("Please enter your First Name");
fullname.requestFocus();
return;
}
if (TextUtils.isEmpty(add)) {
address.setError("Please enter your Address");
fullname.requestFocus();
return;
}
StringRequest stringRequest = new StringRequest(Request.Method.POST, URLs.URL_REGISTER,
new Response.Listener<String>() {
#Override
public void onResponse(String Response) {
try {
//converting response to json object
JSONObject obj = new JSONObject(Response);
//if no error in response
if (!obj.getBoolean("error")) {
Toast.makeText(getApplicationContext(), obj.getString("message"), Toast.LENGTH_SHORT).show();
//getting the user from the response
JSONObject userJson = obj.getJSONObject("user");
//creating a new user object
User user = new User(
userJson.getString("phone_number"),
userJson.getString("lastname"),
userJson.getString("fullname"),
userJson.getString("middleinitial"),
userJson.getString("country"),
userJson.getString("address")
);
//storing the user in shared preferences
SharedPrefManager.getInstance(getApplicationContext()).userLogin(user);
//starting the profile activity
finish();
startActivity(new Intent(getApplicationContext(), MainActivity.class));
} else {
Toast.makeText(getApplicationContext(), obj.getString("message"), Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_SHORT).show();
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("phone_number", phone);
params.put("lastname", lname);
params.put("fullname", fname);
params.put("middleinitial", mname);
params.put("country", count);
params.put("address",add);
return params;
}
};
VolleySingleton.getInstance(this).addToRequestQueue(stringRequest);
}
this code got the error of JSON Array cannot be converted while my Login Code with the same format is working
this is my login code:
private void userLogin(){
//first getting the values
final String phonenumber = etNumber.getText().toString();
//validating inputs
if (TextUtils.isEmpty(phonenumber)) {
etNumber.setError("Please enter your Number");
etNumber.requestFocus();
return;
}
//if everything is fine
StringRequest stringRequest = new StringRequest(Request.Method.POST, URLs.URL_LOGIN,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
//converting response to json object
JSONObject obj = new JSONObject(response);
//if no error in response
if (!obj.getBoolean("error")) {
Toast.makeText(getApplicationContext(), obj.getString("message"), Toast.LENGTH_SHORT).show();
//getting the user from the response
JSONObject userJson = obj.getJSONObject("user");
//creating a new user object
User user = new User(
userJson.getString("phone_number"),
userJson.getString("lastname"),
userJson.getString("fullname"),
userJson.getString("middleinitial"),
userJson.getString("country"),
userJson.getString("address")
);
//storing the user in shared preferences
SharedPrefManager.getInstance(getApplicationContext()).userLogin(user);
//starting the profile activity
finish();
startActivity(new Intent(getApplicationContext(), MainActivity.class));
} else {
Toast.makeText(getApplicationContext(), obj.getString("message"), Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_SHORT).show();
}
})
{
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("phone_number", phonenumber);
return params;
}
};
VolleySingleton.getInstance(this).addToRequestQueue(stringRequest);
}
and the error I got on my Logs is this:
W/System.err: org.json.JSONException: Value [] of type org.json.JSONArray cannot be converted to JSONObject
at org.json.JSON.typeMismatch(JSON.java:112)
at org.json.JSONObject.<init>(JSONObject.java:168)
at org.json.JSONObject.<init>(JSONObject.java:181)
at com.example.redwallet.Register$4.onResponse(Register.java:127)
W/System.err: at com.example.redwallet.Register$4.onResponse(Register.java:120)
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:883)
at android.os.Handler.dispatchMessage(Handler.java:100)
at android.os.Looper.loop(Looper.java:224)
at android.app.ActivityThread.main(ActivityThread.java:7562)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:539)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:950)

Android: Parsing JSON. No value for...?

I am trying to parse JSON data generated by an API.Here is the json I am trying to parse:
{
"response":{
"legislator":[
{
"#attributes":{
"cid":"N00033987",
"firstlast":"Doug LaMalfa",
"lastname":"LAMALFA",
"party":"R",
"office":"CA01",
"gender":"M",
"first_elected":"2012",
"exit_code":"0",
"comments":"",
"phone":"202-225-3076",
"fax":"530-534-7800",
"website":"http:\/\/lamalfa.house.gov",
"webform":"https:\/\/lamalfa.house.gov\/contact\/email-me",
"congress_office":"322 Cannon House Office Building",
"bioguide_id":"L000578",
"votesmart_id":"29713",
"feccandid":"H2CA02142",
"twitter_id":"RepLaMalfa",
"youtube_url":"https:\/\/youtube.com\/RepLaMalfa",
"facebook_id":"RepLaMalfa",
"birthdate":"1960-07-02"
}
The response json object inside of the entire response is throwing me off. I cant get to the legislator array. The logcat gives me this error:
How can I modify my method to get to the legislator json array?
Here is my parsing method:
private void getData() {
final ProgressDialog progressDialog = new ProgressDialog(this);
progressDialog.setMessage("Loading...");
progressDialog.show();
StringRequest stringRequest = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
progressDialog.dismiss();
try {
JSONObject jsonObject = new JSONObject(response);
JSONObject responseObj = jsonObject.getJSONObject("response");
JSONArray array = responseObj.getJSONArray("legislator");
for(int i = 0; i < array.length(); i++){
JSONObject attributesObj = array.getJSONObject(i);
//create object
Legs leg = new Legs(attributesObj.getString("firstlast"),
attributesObj.getString("party"),
attributesObj.getString("office"),
attributesObj.getString("gender"),
attributesObj.getString("birthdate"),
attributesObj.getString("first_elected"),
attributesObj.getString("phone"),
attributesObj.getString("website"),
attributesObj.getString("congress_office"),
attributesObj.getString("twitter_id"),
attributesObj.getString("youtube_url"),
attributesObj.getString("facebook_id"));
legList.add(leg);
}
adapter = new LegRvAdapter(Legislators.this, legList);
myrv.setAdapter(adapter);
}catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
Log.e("Volley", volleyError.toString());
progressDialog.dismiss();
}
});
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}

Getting a null Array from a method

I've created a method that shall return a two-dimensional Array, everything works perfectly as the array is being correctly filled in the method's try.
But once I display the array on onCreate(), it's returning null.
public class ListTickets extends AppCompatActivity {
public String[][] ticketTab ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.list_tickets);
ticketTab = new String[Integer.valueOf(nbTicket)][nbTicketTab];
DisplayArray(getTicketsHTTP());
}
private String[][] getTicketsHTTP() {
final JsonObjectRequest getRequest = new JsonObjectRequest(Request.Method.GET, URL, null,
new Response.Listener<JSONObject>()
{
#Override
public void onResponse(JSONObject response) {
try {
JSONArray Jdata = response.getJSONArray("data");
for (int i=0; i < Jdata.length(); i++) {
try {
JSONObject oneTicket = Jdata.getJSONObject(i);
titreTicket = oneTicket.getString("1");
slaTicket = oneTicket.getString("30");
dateDebutTicket = oneTicket.getString("15");
urgenceTicket = oneTicket.getString("10");
statutTicket = oneTicket.getString("12");
idTicket = oneTicket.getString("2");
} catch (JSONException e) {
Log.e("Err", e.getMessage());
}
ticketTab[i][0] = titreTicket;
ticketTab[i][1] = slaTicket;
ticketTab[i][2] = dateDebutTicket;
ticketTab[i][3] = urgenceText(urgenceTicket);
ticketTab[i][4] = calculTempsRestant(dateDebutTicket, slaTicket, dateEchanceTicket);
ticketTab[i][5] = String.valueOf(ticketEnretard);
ticketTab[i][6] = statutTicket;
ticketTab[i][7] = idTicket;
}
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener()
{
#Override
public void onErrorResponse(VolleyError error) {
Log.e("Error.Response", error.toString());
}
}
){
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> params = new HashMap<String, String>();
params.put("App-Token",FirstEverActivity.App_Token);
params.put("Session-Token",session_token);
return params;
}
};
// add it to the RequestQueue
queue.add(getRequest);
return ticketTab;
}
}
I declared ticketTab outside the onCreate because when I declare it inside the method, I cannot change it inside the try.
How can I return the array correctly?
In your onCreate you are using this line:
ticketTab = new String[Integer.valueOf(nbTicket)][nbTicketTab];
and those values, nbTicket and nbTicketTab are not declared anywhere in your code, maybe that's why they are returning null, you have to initialize them and asign values.

No value for JSONArray

Problem with JSONArray. This is my code, help me
This is my JsonObject and error..
Json errore: No value for {"Username":"rafyluc","Record":"500"}{"Username":"inkinati","Record":"600"}{"Username":"rafyluc","Record":"500"}{"Username":"inkinati","Record":"600"}
public class ListaAlunni extends AppCompatActivity {
private static ArrayList<Alunni> alunni;
AlunniListAdapter customAdapter;
private String TAG = ListaAlunni.class.getSimpleName();
private static String url = "http://192.168.1.11:80/webservice/lista.php";
ArrayList<HashMap<String, String>> itemList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.lista_alunni);
getSupportActionBar().setTitle("Lista Alunni");
alunni = new ArrayList<Alunni>(10);
popola();
}
private void setTextLista() {
ListView ll = (ListView) findViewById(R.id.lista);
ll.setAdapter(new AlunniListAdapter(ListaAlunni.this, R.layout.lista_row, alunni));
}
private void popola() {
new AsyncTask<Object, Object, Object>() {
#Override
protected void onPreExecute() {
alunni = new ArrayList<Alunni>(10);
}
#Override
protected Object doInBackground(Object... params) {
HttpHandler sh = new HttpHandler();
String jsonStr = sh.makeServiceCall(url);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
Log.d("Debug_object", String.valueOf(jsonObj));
// Getting JSON Array node
// try {
//JSONArray jArray=new JSONArray(jsonStr);
JSONArray jArray = jsonObj.getJSONArray(jsonStr);
Log.d("DEBUG_json", String.valueOf(jArray));
for (int i = 0; i < jArray.length(); i++) {
JSONObject json_data = jArray.getJSONObject(i);
Log.i("TEST", "Username: " + json_data.getString("Username") +
", record: " + json_data.getString("Record")
);
String nome= json_data.getString("Username");
String record=json_data.getString("Record");
// alunni.add(new Alunni(nome,record));
HashMap<String, String> item = new HashMap<>();
item.put("Username", nome);
item.put("Record", record);
// adding item to item list
itemList.add(item);
}
} catch (final JSONException e) {
Log.e(TAG, "Json errore: " + e.getMessage());
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Json errore: " + e.getMessage(),
Toast.LENGTH_LONG)
.show();
}
});
}
} else {
Log.e(TAG, "Couldn't get json from server.");
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Couldn't get json from server. Check LogCat for possible errors!",
Toast.LENGTH_LONG)
.show();
}
});
}
return null;
}
#Override
protected void onPostExecute(Object o) {
setTextLista();
}
}.execute();
}
}
classe HttpHandler:
public class HttpHandler {
private static final String TAG = HttpHandler.class.getSimpleName();
public HttpHandler() {
}
public String makeServiceCall(String reqUrl) {
String response = null;
try {
URL url = new URL(reqUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
// read the response
InputStream in = new BufferedInputStream(conn.getInputStream());
response = convertStreamToString(in);
} catch (MalformedURLException e) {
Log.e(TAG, "MalformedURLException: " + e.getMessage());
} catch (ProtocolException e) {
Log.e(TAG, "ProtocolException: " + e.getMessage());
} catch (IOException e) {
Log.e(TAG, "IOException: " + e.getMessage());
} catch (Exception e) {
Log.e(TAG, "Exception: " + e.getMessage());
}
return response;
}
private String convertStreamToString(InputStream is) {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line;
try {
while ((line = reader.readLine()) != null) {
sb.append(line).append('\n');
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
}
Looking at your code, it seems JSONArray jArray = jsonObj.getJSONArray(jsonStr);
is causing the problem.
jsonObj.getJSONArray requires name of the property to be passed E.g. jsonObj.getJSONArray("array_property") but instead, it seems you are passing JSON string.
Also, before calling jsonObj.getJSONArray("array_property") you need to make sure that the array_property exists in the jsonObj

Test Actors in Play Framework but Database is shutdown

I am using Play 2.0.4 and I'm doing a test unit for actors who make use of the database.
The test begins well, but then at a given moment the connection with the database is closed and the actor who is running fails.
Code:
public class ActorTest extends Helpers {
private FakeApplication app;
private ActorSystem actorSystem;
private ActorRef actorRef;
private BankAccount account;
#Before
public void initTest() {
Map<String, String> params = new HashMap<String, String>();
params.put("db.default.driver", "com.mysql.jdbc.Driver");
params.put("db.default.url", "mysql://root:XXXX#localhost/YYY");
params.put("ebean.default", "models.*");
app = fakeApplication(params);
actorSystem = play.api.libs.concurrent.Akka.system(app.getWrappedApplication());
}
#Test
public void updateAccountTransaction() {
running(app, new Runnable() {
#Override
public void run() {
account = BankAccount.find.byId(new Long(1));
actorRef = actorSystem.actorOf(new Props(new UntypedActorFactory() {
#Override
public UntypedActor create() {
return new AccountTaskActor(account);
}
}));
Calendar fromDate = Calendar.getInstance();
....
....
Calendar toDate = Calendar.getInstance();
final InputRangeDateMessage param = new InputRangeDateMessage(fromDate, toDate);
junit.framework.Assert.assertNotNull(account);
Future<Object> future = Patterns.ask(actorRef, param, 1000000);
Promise<Object> sdf = Akka.asPromise(future);
Promise<Result> r2 = sdf.map(new Function<Object, Result>() {
#Override
public Result apply(Object response) throws Throwable {
if (response instanceof ErrorMessage) {
ErrorMessage e = (ErrorMessage) response;
System.out.println("Error Message " + e.getErrorText());
junit.framework.Assert.assertEquals(e.getErrorCode(), -1);
} else if (response instanceof BankAccountMessage) {
BankAccount a = ((BankAccountMessage) response).getAccount();
System.out.println("BankAccount " + a.accountsLastUpdate);
}
return ok();
}
});
Result test2;
test2 = async(r2);
}
});
}
}
AFAIK, you have to wait for the end of your Promise:
...
Result test2 = r2.get();

Resources