Android studio JSONArray cannot be converted to JSONObject - java

I realise there are similar issues but I wasn't able to find one with the exact same issue as me.
I have an API which gets SQL data from a SQL server, that data is then send to the client as JSON.
The API returns the following:
[{"text1":"value1","text2":"value2"}]
I am trying to parse both values using the following java code:
which gives me the following error:
type org.json.JSONArray cannot be converted to JSONObject
private void jsonParse() {
String url = "http://192.168.0.197/api.php";
JsonArrayRequest request = new JsonArrayRequest(Request.Method.GET, url, null,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
try {
JSONArray jsonArray = new JSONArray(response);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject obj = jsonArray.getJSONObject(i);
String text1 = obj.getString("text1");
String text2 = obj.getString("text2");
mTextViewResult.append(text1 + ", " + text2 + "\n\n");
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
});
mQueue.add(request);
}
}```

in your method Parameter onResponse() you are passing a JSONObject instead of JSONArray. Convert that to either String parameter or JSONArray

public void onResponse(JSONArray response) {
try {
for (int i = 0; i < response.length(); i++) {
JSONObject obj = response.getJSONObject(i);
String text1 = obj.getString("text1");
String text2 = obj.getString("text2");
mTextViewResult.append(text1 + ", " + text2 + "\n\n");
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
Do not use JSONArray jsonArray = new JSONArray(response) , because response is already a JSONArray.

Related

How to send Body Data to GET Method Request android using volley?

I have an API which send me a JSON object when I send a token to the server , I use GET method and I have to send token in body, not headers, it works in postman correctly when I put token in body but I have volley server error in android studio and I entered error response.here is my codes:
ant solution???? please
private void getFreightsFromServer()
{
final String url =" https://parastoo.app/api/driver-cargo-list";
JSONObject jsonData = new JSONObject();
String token = G.getString("token");
try
{
jsonData.put("token", token);
} catch (JSONException e)
{
e.printStackTrace();
}
Response.Listener<JSONObject> listener = new Response.Listener<JSONObject>()
{
boolean isGet = false;
#RequiresApi(api = Build.VERSION_CODES.KITKAT)
#Override
public void onResponse(JSONObject response)
{
try
{
MyPost post = new MyPost();
JSONArray jsonArray = response.getJSONArray("results");
for (int i = 0; i < jsonArray.length(); i++)
{
JSONObject tempJsonObject = jsonArray.getJSONObject(i);
JSONObject jsonOriginCustomer = new JSONObject(tempJsonObject.getString("origin_customer"));
post.setOriginCity(jsonOriginCustomer.getString("customerCity"));
JSONObject jsonDestinationCustomer = new JSONObject(tempJsonObject.getString("destination_customer"));
Log.d("result", jsonDestinationCustomer.getString("customerCity"));
post.setDestinationCity(jsonDestinationCustomer.getString("customerCity"));
freightsList.add(post);
// isGet = true;
adapter.notifyDataSetChanged();
}
} catch (JSONException e)
{
e.printStackTrace();
}
}
};
Response.ErrorListener errorListener = new Response.ErrorListener()
{
#Override
public void onErrorResponse(VolleyError error)
{
Toast.makeText(getContext(), error.toString(), Toast.LENGTH_LONG).show();
Log.d("jdbvdc", error.toString());
error.printStackTrace();
}
};
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, jsonData, listener, errorListener);
Log.d("fhdhdcf",jsonData.toString());
final int socketTimeout = 100000;
RetryPolicy policy = new DefaultRetryPolicy(socketTimeout, 0, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
request.setRetryPolicy(policy);
AppSingleton.getInstance(getContext()).addToRequestQueue(request);
}
Please show the error message you have. Also I am not sure how ok it is to send something in a body of a GET request. This answer might help you:
HTTP GET with request body
It's better to use post method for this type of request.
But still if you want to use GET method then you should have to pass token in the URL.
Below is an example
final String username = etUname.getText().toString().trim();
final String password = etPass.getText().toString().trim();
URLline = "https://demonuts.com/Demonuts/JsonTest/Tennis/loginGETrequest.php?username="+username+"&password="+password;

JSON RPC response to Array Android

I managed to get results for a json rpc request, like this:
{"id":1,"jsonrpc":"2.0","result":{"channels":[{"channel":"Channel A ","channelid":2165,"label":"Channel A"},{"channel":"Channel B ","channelid":748,"label":"Channel B"} etc.
I would like to parse the reponse to an array where i can read channel,channelid and label at each iteration of a loop. but did not manage to get it.
Any help would be much appreciated.
Sorry not that experienced with programming , its al self-taught
Code for json rpc request :
String groupchannelsurl = "http://192.168.2.100:8080/jsonrpc?request={\"jsonrpc\": \"2.0\", \"method\": \"PVR.GetChannels\", \"params\": {\"channelgroupid\" : 9,\"properties\":[\"channel\"]}, \"id\": 1 }";
RequestQueue queue = Volley.newRequestQueue(this);
JsonObjectRequest getRequest = new JsonObjectRequest(Request.Method.GET, groupchannelsurl, null,
new Response.Listener<JSONObject>()
{
#Override
public void onResponse(JSONObject response) {
// display response
Log.d("Response", response.toString());
}
},
new Response.ErrorListener()
{
#Override
public void onErrorResponse(VolleyError error) {
Log.d("Error.Response", error.toString());
}
}
);
queue.add(getRequest);
The Android Developer documentation is really good if you get stuck.
JSONObject -
https://developer.android.com/reference/org/json/JSONObject.html
JSONArray - https://developer.android.com/reference/org/json/JSONArray.html
#Override
public void onResponse(JSONObject response) {
JSONArray channels = response.getJSONObject("result").getJSONArray("channels");
for (int i = 0; i < channels.length(); i++) {
JSONObject channel = channels.getJSONObject(i);
String channelName = channel.getString("channel");
int channelId = channel.getInt("channelid");
String channelLabel = channel.getString("label");
// ...
}
}
Hope this helps!
You can parse JSONObject like below
private void parseJsonObject(JSONObject responseObject) throws JSONException {
String id = responseObject.getString("id");
JSONArray jsonArray = responseObject.optJSONArray("channels");
if (jsonArray != null) {
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject arrayObject = (JSONObject) jsonArray.get(i);
String channel = arrayObject.getString("channel");
String channelId = arrayObject.getString("channelid");
}
}
}

get json that have integer with volley library

i have a problem with get json with volley library.
this is my json:
{"result":1}
the php code count rows in mysql database and show result in this json file.
the number of count is integer.
and this is my code for get this json:
private void getData () {
//url + id of row that want to count
String url = Config.DATA_URL_COUNT +"1";
StringRequest stringRequest = new StringRequest(url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
//loading.setVisibility(View.INVISIBLE);
showJSON(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// Toast.makeText(this,error.getMessage().toString(), Toast.LENGTH_LONG).show();
}
});
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
private void showJSON(String response) {
int name = 0;
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray result = jsonObject.getJSONArray(Config.TAG_RESULT);
JSONObject collegeData = result.getJSONObject(0);
name = jsonObject.getInt(Config.JSON_ARRAY);
} catch (JSONException e) {
e.printStackTrace();
}
String count = String.valueOf(name);
rowcount_kargozarybime.setText(count); //insert result in textview
}
and this is my php code:
<?php
if($_SERVER['REQUEST_METHOD']=='GET'){
$categoryid = $_GET['categoryid'];
define('HOST','144.76.10.250');
define('USER','cp21983_test');
define('PASS','*******');
define('DB','cp21983_marivanjobs');
$con = mysqli_connect(HOST,USER,PASS,DB);
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
mysqli_query($con,"SET character_set_results=utf8,character_set_client=utf8,character_set_connection=utf8, character_set_database=utf8,character_set_server=utf8");
$sql="SELECT * FROM jobs WHERE categoryid='".$categoryid."'";
if ($result=mysqli_query($con,$sql))
{
// Return the number of rows in result set
$rowcount=mysqli_num_rows($result);
echo json_encode(array("result"=>$rowcount));
// Free result set
mysqli_free_result($result);
}
mysqli_close($con);
}
i well be thankfull if anyone can help me.
Try using :
JSONObject respObject = new JSONObject(response);
int result = respObject.getInt("result");
This is a json object,not a json array. therefore use this code to get result count
JSONObject jsonObject = new JSONObject(response);
int count = jsonObject.getInt("result");
rowcount_kargozarybime.setText(String.valueOf(count));

Android: JSONObject with volley response

Im trying to download data from a server in the form of a JSON object, parse that object then use the data elsewhere in my app.
Ive created a class which downloads the data (confirmed with a Log.v statement)
The trouble is that i want to display the results in a RecyclerView and the List of objects that i generate after parsing the JSON response does not get generated until after the adapter method is called from my main class.
So my question is, given the code below, how can i ensure that the on response method only exits once the parseResponse method has finished. Currently i am returning the (Null) _releaseList from my requestAndPareseReleaseList method.
public class ParseReleaseJSON extends JSONObject {
String _url;
List<ReleaseInfo> _releaseList = Collections.emptyList();
ParseReleaseJSON(String url) {
super();
_url = url;
}
public List<ReleaseInfo> requestAndParseReleaseList(Context _context){
JsonObjectRequest jsObReq = new JsonObjectRequest(Request.Method.GET, _url, (String) null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
releaseList = parseResponse(response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.v("err", "nosuccess");
}
});
MySingleton.getInstance(_context).addToRequestQueue(jsObReq);
return _releaseList;
}
private List parseResponse(JSONObject response) {
List<ReleaseInfo> list = new ArrayList<>();
if(response == null || response.length() == 0){
return list;
}
try {
if(response.has("results")){
JSONArray resultsArray = response.getJSONArray("results");
for(int i = 0, j = 6; i < j; i++){
ReleaseInfo release = new ReleaseInfo();
JSONObject tempObj = resultsArray.getJSONObject(i);
release.title = tempObj.getString("title");
release.date = tempObj.getString("date");
list.add(release);
}
return list;
}
} catch (JSONException e) {
e.printStackTrace();
}
return list;
}
}

facebook sdk java query getting name from actor_id with graph API or url/http

How do I get the name of the actor_id in the same request, and display all the information from the table and the "name"?
SELECT permalink,actor_id FROM stream WHERE source_id=me()
then I want the name of the actor_id
I know I can use the actor_id results and get the name in a new request
SELECT name FROM user WHERE uid=actor_id
but, I need to display the permalink and the name together.
How do I get results from
https://graph.facebook.com/user_id?fields=name
Can I do a URL/https request to display the name with actor_id results I got?
You can make the multiple query using RequestBatch-
ArrayList<Request> requests = new ArrayList<Request>();
// Request-1
String streamQuery = "SELECT permalink,actor_id FROM stream WHERE source_id=me()";
Bundle args1 = new Bundle();
args1.putString("q", streamQuery);
Request request1 = new Request(session, "fql", args1, HttpMethod.GET);
request1.setCallback(new com.facebook.Request.Callback() {
#Override
public void onCompleted(Response response) {
GraphObject graphObject = response.getGraphObject();
String s = textViewResults.getText().toString();
if (graphObject != null) {
JSONObject jsonObject = graphObject.getInnerJSONObject();
try {
JSONArray array = jsonObject.getJSONArray("data");
for (int i = 0; i < array.length(); i++) {
JSONObject object = (JSONObject) array.get(i);
Log.d(TAG, "permalink = "+object.get("permalink"));
}
}
catch (JSONException e) {
e.printStackTrace();
}
}
}
});
requests.add(request1);
// Request-2
String userQuery = "SELECT name FROM user WHERE uid=actor_id";
Bundle args2=new Bundle();
args2.putString("q", userQuery);
Request request2 = new Request(session, "fql", args2, HttpMethod.GET);
request2.setCallback(new com.facebook.Request.Callback() {
#Override
public void onCompleted(Response response) {
GraphObject graphObject = response.getGraphObject();
String s = textViewResults.getText().toString();
if (graphObject != null) {
JSONObject jsonObject = graphObject.getInnerJSONObject();
try {
JSONArray array = jsonObject.getJSONArray("data");
for (int i = 0; i < array.length(); i++) {
JSONObject object = (JSONObject) array.get(i);
Log.d(TAG, "name = "+object.get("name"));
}
}
catch (JSONException e) {
e.printStackTrace();
}
}
}
});
requests.add(request2);
// Execute Batch
RequestBatch requestBatch=new RequestBatch(requests);
requestBatch.setTimeout(10000);
List<Response> responses = requestBatch.executeBatchAndWait();
Hope that helps. Good luck!
I was able to resolve the issue with this request, I got the solution from this [link]Facebook android sdk how to get the number of likes for a given page
the "id" is from the first query of the actor_id
Bundle params = new Bundle();
params.putString("id", id);
params.putString("fields", "name");
Request request = new Request(session, "search", params, HttpMethod.GET, new Request.Callback() {
public void onCompleted(Response response) { try {
JSONObject res = response.getGraphObject().getInnerJSONObject().getJSONArray("data").getJSONObject(0);
final String name = (String) res.get("name");

Categories