There is some issue with the JSONObjectRequest in Volley library to receive the JSON data. I suppose I am going wrong somewhere in receiving the JSON object in the Java code. Following is my JSON output coming as a response from the php file hosted on server:
{"workers":[
{"id":"1","name":"Raja","phonenumber":"66589952","occupation":"Plumber","location":"Salunke Vihar","rating":"4","Review":"Hard Worker","price":"80"},
{"id":"2","name":"Aman","phonenumber":"789456","occupation":"Plumber","location":"Wakad","rating":"4","Review":"Good","price":"80"}
],
"success":1}
Following is clode from the Java file where I am using the JSON request using Volley library:
JsonObjectRequest jsonRequest = new JsonObjectRequest (Request.Method.POST, url,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
// I should receive the success value 1 here
int success = response.getInt("success");
//and should receive the workers array here
Log.d("response",response.getJSONArray("workers").toString());
Log.d("success",""+success);
} catch (JSONException e) {
e.printStackTrace();
}
Toast.makeText(getApplicationContext(), response.toString(), Toast.LENGTH_LONG).show();
recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
recyclerView.setHasFixedSize(true);
layoutManager = new LinearLayoutManager(getApplicationContext());
recyclerView.setLayoutManager(layoutManager);
//Finally initializing our adapter
adapter = new WorkerAdapter(listWorkers);
recyclerView.setAdapter(adapter);
//adapter is working fine
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("error",error.toString());
Toast.makeText(getApplicationContext(),error.toString(),Toast.LENGTH_LONG).show();
}
}){
#Override
protected Map<String,String> getParams(){
Map<String,String> params = new HashMap<String, String>();
params.put("tag", "get_list");
params.put("service", service);
return params;
}
Running the above code it goes to the error listener and gives the output as org.json.JSONException: End of input at character 0 of.
But if I use StringRequest in place of JsonObjectRequest and receive the JSON response as a string then I am able to receive the output as a String but I can't use it further. So, please let me know where I am going wrong in receiving the JSONdata and suggest me the changes in the code that I must do.
EDIT- I am adding the php file which is returning the JSON object. Please let me know if there is some error over here:
<?php
error_reporting(0);
include("config.php");
if($_SERVER['REQUEST_METHOD']=='POST'){
$tag = $_POST['tag'];
// array for JSON response
$response = array();
if ($tag == 'get_list') {
// Request type is check Login
$service = $_POST['service'];
//echo json_encode($service);
// get all items from myorder table
$result = mysql_query("SELECT * FROM Workers WHERE Occupation = '$service'") or die(mysql_error());
if (mysql_num_rows($result) > 0) {
$response["workers"] = array();
while ($row = mysql_fetch_array($result)) {
// temp user array
$item = array();
$item["id"] = $row["wID"];
$item["pic"] = $row["Pic"];
$item["name"] = $row["Name"];
$item["phonenumber"] = $row["Phone Number"];
$item["occupation"] = $row["Occupation"];
$item["location"] = $row["Location"];
$item["rating"] = $row["Rating"];
$item["Review"] = $row["Review"];
$item["price"] = $row["Price"];
// push ordered items into response array
array_push($response["workers"], $item);
}
// success
$response["success"] = 1;
}
else {
// order is empty
$response["success"] = 0;
$response["message"] = "No Items Found";
}
}
echo json_encode($response);
}
?>
When I ran the api end point I have got the following result instead of the one that you have been telling so. So stop giving irrelevant data.
"Plumber"{"workers":[{"id":"1","pic":"ttp:\/\/vorkal.com\/images\/vorkal_cover.PNG","name":"Raja","phonenumber":"66589952","occupation":"Plumber","location":"Salunke Vihar","rating":"4","Review":"Hard Worker. Very Professional.","price":"80"},{"id":"2","pic":"http:\/\/vorkal.com\/images\/vorkal_cover.PNG","name":"Aman","phonenumber":"789456","occupation":"Plumber","location":"Wakad","rating":"4","Review":"Good","price":"80"}],"success":1}
Where Plumber is not the tag at all, hence throws error as the same is not valid json string. There's error in your server side scripting. I request you to send the complete script without modification.
If you are not getting the JSONObject that means the following is a malformed json. Thus you can try the following code in server side
function utf8ize($d) {
if (is_array($d)) {
foreach ($d as $k => $v) {
$d[$k] = $this->utf8ize($v);
}
} else if (is_string ($d)) {
return utf8_encode($d);
}
return $d;
}
where$d is the string/response. use it as echo json_encode($this->utf8ize($detail));
Also try the following in client side code
Gson gson = new Gson();
JsonReader reader = new JsonReader(new StringReader(result1));
reader.setLenient(true);
You may refer the solution to this question here click here
you can use Gson to convert json string to object
Gson gson = new Gson();
GetWorkersResponse getWorkersResponse =gson.fromJson(response,GetWorkersResponse.class);
class GetWorkersResponse {
public boolean success;
public List<Worker> workers = new ArryList<>();
}
It's work for me.
Can you check that server is returning you a JSONObject and not the string? In Volley if the type of response is different then it will return the error.
Related
I'm trying to get some data from the Binance API for an Android APP.
However, it seems that my JsonArrayRequest is simply ignored when I run my code.
Does anyone have any idea as to why this is happening?
private void getData(){
String url = "https://api.binance.com/api/v1/klines?symbol=ETHUSDT&interval=1h";//+rateSymbol+"&interval="+interval;
RequestQueue requestQueue = Volley.newRequestQueue(this);
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Request.Method.GET, url, null, response -> {
System.out.println("KKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKK");
System.out.println(response.length());
try{
for(int i = 0; i<response.length(); ++i){
JSONArray array = response.getJSONArray(i);
System.out.println("MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM");
System.out.println(array);
openTimes.add((Integer)array.get(0));
openValues.add((Double)array.get(1));
highValues.add((Double)array.get(2));
lowValues.add((Double)array.get(3));
closeValues.add((Double)array.get(4));
volumeValues.add((Double)array.get(5));
closeTimes.add((Integer)array.get(6));
}
} catch(Exception e){
System.out.println("ERRORERRORERRORERRORERRORERRORERRORERRORERRORERRORERRORERRORERRORERRORERRORERRORERRORERRORERRORERRORERRORERRORERRORERRORERRORERRORERRORERROR");
e.printStackTrace();
Toast.makeText(CryptoGraphActivity.this, "Couldn't extract JSON data... Please try again later.", Toast.LENGTH_SHORT).show();
}
}, error -> {
System.out.println("NORESPONSENORESPONSENORESPONSENORESPONSENORESPONSENORESPONSENORESPONSENORESPONSENORESPONSENORESPONSENORESPONSENORESPONSE");
Toast.makeText(CryptoGraphActivity.this, "Couldn't retrieve data... Please try again later.", Toast.LENGTH_SHORT).show();
});
requestQueue.add(jsonArrayRequest);
}
All of these prints are never actually shown on the terminal, but when I added a print right before requestQueue.add(jsonArrayRequest), this one showed (indicating that the request is indeed added to the request queue.
i am using gofile link but when i call it i get this error
E/Volley: [4463] NetworkUtility.shouldRetryException: Unexpected response code 404 for https://api.gofile.io/getFolder?folderId=XuxRGg
i also attach the code part
public class GoFile {
public interface goFileCallback {
void onSuccess(String result);
void onError(VolleyError error);
}
public static void getStreamLink(Context context, String url, final goFileCallback callback) {
String[] parts = url.split("/");
String id = parts[4];
RequestQueue queue = Volley.newRequestQueue(context);
StringRequest sr = new StringRequest(com.android.volley.Request.Method.GET, "https://api.gofile.io/getFolder?folderId="+id, response -> {
JsonObject jsonObject = new Gson().fromJson(response, JsonObject.class);
JsonObject data = jsonObject.get("data").getAsJsonObject();
JsonObject contents = data.get("contents").getAsJsonObject();
for (String keyStr : contents.keySet()) {
JsonObject md5 = contents.get(keyStr).getAsJsonObject();
String link = md5.get("link").getAsString();
callback.onSuccess(link);
}
}, error -> callback.onError(error));
queue.add(sr);
}
}
i would be glad if some one help me to solve this
You should double check the link "https://api.gofile.io/getFolder?folderId=XuxRGg". Typing it in chrome also return 404.
say 404_Not Found response code -
check api link and find http_response_code(404)(in php) - probably there isn't response in database
I am trying to fetch all videos of a channel using youtube data api, but my code is giving error and doesn't respond to PAGE token
displayVideos();
}
private void displayVideos ()
{
RequestQueue requestQueue= Volley.newRequestQueue(this);
StringRequest stringRequest=new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
System.out.println(jsonObject.get("nextPageToken"));
JSONArray jsonArray = jsonObject.getJSONArray("items");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject1 = jsonArray.getJSONObject(i);
if (jsonObject1.has("id")){
JSONObject jsonVideoId=jsonObject1.getJSONObject("id");
if (jsonVideoId.has("kind")){
if(jsonVideoId.getString("kind").equals("youtube#video")){
JSONObject jsonObjectSnippet = jsonObject1.getJSONObject("snippet");
JSONObject jsonObjectDefault=jsonObjectSnippet.getJSONObject("thumbnails").getJSONObject("medium");
String video_id=jsonVideoId.getString("videoId");
VideoDetails vd=new VideoDetails();
vd.setVideoId(video_id);
vd.setTitle(jsonObjectSnippet.getString("title"));
vd.setDescription(jsonObjectSnippet.getString("description"));
vd.setUrl(jsonObjectDefault.getString("url"));
videoDetailsoArrayList.add(vd);
}
// recyclerView.setAdapter(adapter);
// adapter.notifyDataSetChanged();
}
}
}
}catch (JSONException e) {
e.printStackTrace();
}
the url I am trying to parse is
String url="https://www.googleapis.com/youtube/v3/search?part=snippet&channelId=UCVMWWQ985A_-SESZUy_SsVQ&maxResults=50&pageToken="+nextPageToken+"&order=date&pageToken=CAUQAA&key=API_KEY";
I have been searchingb to apply nextpage token or page token in android studio but couldnt get specific tutorial. there are many examples but being naive in android studio I cant implement it into my code.
Please note that your URL does contain two instances of the parameter pageToken:
"https://www.googleapis.com/youtube/v3/search?part=snippet&channelId=UCVMWWQ985A_-SESZUy_SsVQ&maxResults=50&pageToken="+nextPageToken+"&order=date&pageToken=CAUQAA&key=API_KEY".
It should have only one for that to work OK; to be more precise, your URL should contain only this instance: pageToken="+nextPageToken+".
On the other hand, your code above does not show the loop implementing pagination. That is that you haven't shown the piece of code where you actually assign a valid value to the variable nextPageToken.
Therefore I cannot tell if your program will work or not.
The pagination loop would look like this:
// initially no pageToken
nextPageToken = null;
// URL as above, without the parameter pageToken
url = ...
do {
invoke the API on the URL: url + (nextPageToken != null ? "&pageToken=" + nextPageToken : "")
nextPageToken = jsonObject.get("nextPageToken");
} while (nextPageToken != null)
I am trying to convert a PHP-array into a Java ArrayList.
I have this PHP-Code which seems to have no syntax errors:
$password = "xxxx";
$host = "localhost";
$db_name = "xxxx";
$output = array();
$con = mysqli_connect("$host", "$user", "$password");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
if (!mysqli_select_db($con, $db_name)) {
die('Could not select database: ');
}
$result = mysqli_query($con, "SELECT name FROM shopping_items"); //change to "name"
if (!$result) {
printf("Error: %s\n", mysqli_error($con));
exit();
}
while($row = mysqli_fetch_array($result, MYSQLI_BOTH))
{
$output[]=$row;
}
return $output;
mysqli_close($con);
?>
It takes one row from the table, so I should get back a PHP-array.
Now comes the hard part. In Java, I wrote the following code using the Volley library:
public void getShopping(String url) {
//init queue or get from somewhere
RequestQueue queue = Volley.newRequestQueue(this);
StringRequest stringRequest;
stringRequest = new StringRequest(Request.Method.GET, url, //URL leads to PHP-File
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
shoppingItems.add(response); //shopping Items is an ArrayList
adapter.notifyDataSetChanged();
Toast.makeText(ShoppingListActivity.this, response, Toast.LENGTH_SHORT);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
//got error
}
});
queue.add(stringRequest);
}
I want to have each item added to shoppingItems. But when printing the array out I get an empty string. I think that StringRequest is the wrong way to go but I don't know any other way. I read that using json_encode is possible but that seems unnecessarily complicated to me. Is there an easier way to do that?
I could not find an answer in previous SO questions. If at all possible, please provide help that involves Volley because it is pretty integrated in my code.
Expected JSON to be send to server
{"syncsts":
[
{"status":"1","Id":"9"},
{"status":"1","Id":"8"}
]
}
Expected way of retrieval of JSON Object on the server
$arr = $_POST['syncsts']
(I think )
$arr should have [{"status":"1","Id":"9"},{"status":"1","Id":"8"}]
Volley JsonObjectRequest Function along with JSON style parameter
public void updateMySQLSyncSts(final ArrayList<HashMap<String, String>> lt){
JSONArray arr = new JSONArray(lt);
JSONObject js = new JSONObject();
try {
js.put("syncsts",arr);
} catch (JSONException e) {
e.printStackTrace();
}
Log.i("MainActivity",js.toString());
String url = "http://10.0.3.2/insight/mysqlsqlitesync/updatesyncsts.php";
JsonObjectRequest req = new JsonObjectRequest(Request.Method.POST, url, js,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Toast.makeText(getApplicationContext(), "MySQL DB has been informed about Sync activity", Toast.LENGTH_LONG).show();
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.i("MainActivity",error.getMessage());
Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_LONG).show();
}
});
MySingleton.getInstance(this).addToRequestQueue(req);
}
PHP script
/**
* Updates Sync status of Users
*/
include_once './db_functions.php';
//Create Object for DB_Functions clas
$db = new DB_Functions();
//Get JSON posted by Android Application
$json = $_POST["syncsts"];
//Remove Slashes
if (get_magic_quotes_gpc()){
$json = stripslashes($json);
}
//Decode JSON into an Array
$data = json_decode($json);
//Util arrays to create response JSON
$a=array();
$b=array();
//Loop through an Array and insert data read from JSON into MySQL DB
for($i=0; $i<count($data) ; $i++)
{
//Store User into MySQL DB
$res = $db->updateSyncSts($data[$i]->Id,$data[$i]->status);
//Based on inserttion, create JSON response
if($res){
$b["id"] = $data[$i]->Id;
$b["status"] = 'yes';
array_push($a,$b);
}else{
$b["id"] = $data[$i]->Id;
$b["status"] = 'no';
array_push($a,$b);
}
}
//Post JSON response back to Android Application
echo json_encode($a);
I am using the above function to send JSON formatted parameter along with my post request. when $_POST["syncsts"] line in PHP script executed the following error is thrown.
JSONObject toString() and the Error as shown in the logcat
10-04 21:59:23.523 2062-2062/? I/MainActivity: {"syncsts":[{"status":"1","Id":"9"},{"status":"1","Id":"8"}]}
10-04 21:59:23.767 2062-2062/? I/MainActivity: org.json.JSONException: Value <br of type java.lang.String cannot be converted to JSONObject
PHP script to show what is received on server (Debugging)
file_put_contents('test.txt', file_get_contents('php://input'));
$arr = $_POST['syncsts'];
echo $arr;
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
echo json_encode($age);
test.txt
{"syncsts":[{"status":"1","Id":"9"},{"status":"1","Id":"8"}]}
Please tell me what is wrong in the JSON format which I am trying to send to our server which was generated in Java.
it looks like the error is at the responce from server. the onResponse(JSONObject response) expects the results to be proper jsonobject. check if there is any other elements being displayed after echoing the result(such as an error message). you can check it from browser using a chrome extension called postman using which you can try sending POST and GET requests manually to server