I want to retrieve the list of football players via API, I have made the Http handler and api call correctly. Now i have this JSON array
http://api.football-data.org/v1/teams/66/players
I want to parse it so that only the name of the players is shown. How can i parse through the first bit of the JSON array so that the array starts from [{name:Paul Pogba... please?
My code so far:
#Override
protected Void doInBackground(Void... arg0) {
//New instance of http
http sh = new http();
// Making a request to URL and getting response
final String jsonStr = sh.makeServiceCall(url);
Log.e(TAG, "Response from: " + jsonStr);
if (jsonStr != null) {
try {
// Getting JSON Array node
JSONArray jsonarray = new JSONArray(jsonStr);
for (int i = 0; i < jsonarray.length(); i++) {
JSONObject jo = jsonarray.getJSONObject(i);
String name = jo.getString("name");
HashMap<String, String> player = new HashMap<>();
player.put("name", name);
playerlist.add(player);
}
} catch (final JSONException e) { //In case an error regarding JSON parsing takes place
Log.e(TAG, "Json parsing error: " + e.getMessage());
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Json parsing error: " + e.getMessage(),
Toast.LENGTH_LONG)
.show();
}
});
}
} else {
Log.e(TAG, "Couldn't get json from server."); //In case the JSON can't be obtained from the 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;
}
thanks for the info guys. Fixed it with substring :)
Related
I send the /getsms GET request to an API and I get the expected results on postman. However, when I try to make the same request through volley in java on android studio, it just doesn't get a response, I keep waiting and nothing happens.
I'm sure the API does get the request since the expected changes occur when I send the data associated with the get request.
So I'm at a loss as to why exactly it doesn't get a response.
Java code:
final String url = "http://10.0.2.2:3000/myroute/getsms/"+frm;
JsonObjectRequest getRequest = new JsonObjectRequest(Request.Method.GET, url, null,
new Response.Listener<JSONObject>()
{
#Override
public void onResponse(JSONObject response) {
try {
String frm = response.getString("src_num");
String msg = response.getString("msg");
int id = response.getInt("id");
itemsAdapter.add(frm + ": " + msg);
Log.d("Response", response.toString());
}
catch (Exception err) {
Log.d("excpetion", err.toString());
}
}
},
new Response.ErrorListener()
{
#Override
public void onErrorResponse(VolleyError error) {
Log.d("Error.Response", error.toString());
}
}
);
API code:
router.get('/getsms/:dest_num', function (req, res) {
console.log("get oldest unsent sms from db");
let sql = "SELECT * FROM " + table + " WHERE " + "dest_num=" + req.params.dest_num + " AND sent=FALSE " + "ORDER BY id " + "LIMIT 1;";
console.log(sql);
db.mycon.query(sql, function (err, result) {
console.log("Result: " + JSON.stringify(result));
if(err){
res.send(err);
} else {
console.log("SENT!")
res.json(result);
}
});
});
Any help is appreciated.
UPDATE: So upon sifting through the logs I found this:
2020-01-15 22:07:23.481 11880-11880/com.example.sms D/Error.Response: com.android.volley.ParseError: org.json.JSONException: Value [{"id":4,"src_num":"321","dest_num":"1003435365","msg":"first message from server","time":100,"sent":0}] of type org.json.JSONArray cannot be converted to JSONObject
Apparently the response is received but Volley kicks when parsing. I cant see why this is happening. I don't see anything wrong with the JSON string. And is this really enough for it to not go into the onResponse function?
UPDATE2: So apparently that was indeed the problem and what was sent wasn't a JSONObject but a JSONArray. and just needed to change the datatypes accordingly.
So the code ended working with:
String url = "http://10.0.2.2:3000/myroute/getsms/" + frm;
JsonArrayRequest jsonObjectRequest = new JsonArrayRequest(Request.Method.GET, url, null, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response_arr) {
try {
JSONObject response = response_arr.getJSONObject(0);
String frm = response.getString("src_num");
String msg = response.getString("msg");
int id = response.getInt("id");
itemsAdapter.add(frm + ": " + msg);
} catch (Exception err) {
System.out.println(err.toString());
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("Error.Response", error.toString());
}
});
requestQueue.add(jsonObjectRequest);
Thanks to the comments for helping :)
You can try for The code given below and also add the request to the requestqueue of the new instance of RequestHandler.
StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONArray array = new JSONArray(response); //here is the mistake of parsing which will be removed after it is converted to the json object
JSONObject object = array.getJSONObject(0); //-----mistake
String frm = object.getString("src_num");
String msg = object.getString("msg");
int id = object.getInt("id");
itemsAdapter.add(frm + ": " + msg);
Log.d("Response", response.toString());
} catch (JSONException e) {
Log.d("excpetion", err.toString());
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("Error.response", err.toString());
}
});
new RequestHandler().addToRequestQueue(stringRequest);
Hope it helps !!
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.
org.json.JSONException: No value for status
Here is my java code method for json parse
java
public void performSearch() {
String url= "http://192.168.0.136/fyp/stitle1.php";
RequestQueue requestQueue = Volley.newRequestQueue(Stitle.this);
JsonObjectRequest jsObjRequest = new JsonObjectRequest(Request.Method.POST,url,null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d("Response", response.toString());
try {
//converting the string to json array object
JSONObject array = new JSONObject();
//Log.i("test", " value : " + array.getString("status"));
Log.i("test", " value : " + response.getString("status"));
if (array.getString("status").equals("true")) {
JSONArray jsonArray = array.getJSONArray("search");
Log.i("test", " value : " + array);
for (int i = 0; i < jsonArray.length(); i++) {
//getting product object from json array
JSONObject product = jsonArray.getJSONObject(i);
//adding the product to product list
boolean add = productList.add(new list(
product.getLong("isbn"),
product.getString("title"),
product.getString("authors"),
product.getInt("accession"),
product.getString("publisher"),
product.getInt("pubyear"),
product.getInt("pages"),
product.getInt("rak"),
product.getInt("hr"),
product.getInt("vr"),
product.getLong("barcode")
));
}
} else {
Log.i("test", "else error");
}
} catch (JSONException e) {
e.printStackTrace();
Log.i("test", e.toString());
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(), "error:" + error.toString(), Toast.LENGTH_LONG).show();
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("Title", searchtitle.getText().toString());
return params;
}
};
requestQueue = Volley.newRequestQueue(Stitle.this);
requestQueue.add(jsObjRequest);
}
Php file to pass parameter to android jsonobject
stitle1.php
php
<?php
// array for JSON response
$response = array();
//set values just in case any thing goes wrong
$response["status"] = 0;
$response["message"] = "Error before start";
// check for post data with isset
if (isset($_POST["Title"])) {
$title = $_POST["Title"];
// You were not using PDO so I dumped your connection and require you to provide...
//...a configuration file for ...
require_once 'connection.php';
// ...these variables
$host = 'localhost';
$db = 'fyp';
$user = 'root';
$pass = '';
$charset = 'utf8';
$dsn = "mysql:host=$host;dbname=$db;charset=$charset";
$opt = [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_EMULATE_PREPARES => false,
];
try{
// connecting to db with PDO
$pdo = new PDO($dsn, $user, $pass, $opt);
$sql = 'SELECT isbn, title, authors, accession, publisher, pubyear, pages, rak, hr, vr, barcode
FROM books
WHERE title LIKE :titleParam';
$titleParam = "%".$title."%";
$stmt = $pdo->prepare($sql);
// Bind the parameter
$stmt->bindParam(':titleParam', $titleParam, PDO::PARAM_STR);
$res = $stmt->execute();
if ($res) {
// success
$response["status"] = 1;
// connection node
$response["books"] = array();
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$data = array();
$data["isbn"] = $row["isbn"];
$data["title"] = $row["title"];
$data["authors"] = $row["authors"];
$data["accession"] = $row["accession"];
$data["publisher"] = $row["publisher"];
$data["pubyear"] = $row["pubyear"];
$data["pages"] = $row["pages"];
$data["rak"] = $row["rak"];
$data["hr"] = $row["hr"];
$data["vr"] = $row["vr"];
$data["barcode"] = $row["barcode"];
array_push($response["books"], $data);
}
}
else {
// required field is missing
$response["status"] = 2;
$response["message"] = "No data returned";
}
}
catch (Exception $e){
$response["status"] = 3;
$response["message"] = "Error occurred." . $e->getMessage();
}
}
else {
$response["status"] = 4;
$response["message"] = "Post parameters are not correct";
}
// echoing JSON response
echo json_encode($response);
?>
When I run my application these lines appear on logcat panel
I/test: value : 4
I/test: org.json.JSONException: No value for status
These are two lines appear on logcat which indicate error about that the parameter was not sent properly
We will take this step for step. Lets start with response.
Your PHP code is returning a status value =4 which indicates that you are not getting the parameters sent to the PHP code properly. It is possible that getParams() is not even being called.
Change the getParams() method to look like this:
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
try{
String s = searchtitle.getText().toString();
Log.e("Volley request", "getParams called : " + s);
params.put("Title", s);
}
catch(Exception ex){
Log.e("Volley request ERROR", ex.getMessage());
}
return params;
}
For the second part, lets try to deal with the parsing code. Change the code to look like this:
Now regardless of how your php code responds, you will be getting a well formed JSONObject as a response which you can parse and react to it appropriately.
Change the onResponse() part of the code to look like this:
#Override
public void onResponse(JSONObject response) {
// Log.d("Response", response.toString());
try {
//converting the string to json array object
if(response != null){
if(!response.has("status"){
Log.e(TAG, "Something went wrong -- no status key!");
return;
}
else{
int status = response.optInt("status", -1);
if(status == 1){
//There could be quite a few books in this response...
//...you might want to parse in an AsyncTask instead
parseJsonObject(response);
}
else{
String message = response.optString("message", "uups");
Log.e(TAG, "error message = " + message);
return;
}
}
}
}
catch(Exception ex){
Log.e(TAG, ex.getMessage());
}
}
And now to parse the JSONObject:
Map<String, String> booksMap = new HashMap<>();
private void parseJsonObject(JSONObject jsonObject){
try{
if(jsonObject == null) return;
//Not Available!
String na = "NA"
Log.i("test", " value : " + jsonObject.toString());
if(jsonObject.has("books")){
JSONArray array = jsonObject.getJSONArray("books");
for(int i = 0; array.length(); i++){
JSONObject book = array.getJSONObject(i);
Iterator<String> it = book.keys();
while(it.hasNext()){
String key = it.next();
String value = book.optString(key, na);
booksMap.put(key, value);
}
}
}
}
catch(Exception ex){
Log.e(TAG, ex.getMessage());
}
}
[{
"name":"George",
"id":"2222",
"lastname":"wist",
"date":"07/08/07"
},
{
"name":"aaron",
"id":"1111",
"lastname":"borris",
"date":"06/06/09"
}]
You can use Volley library. Android volley is a networking library was introduced to make networking calls much easier, faster without writing tons of code.
To use Volley, you have to add below dependencies in your build.gradle file:
dependencies {
.............
......................
compile 'com.mcxiaoke.volley:library-aar:1.0.0'
}
Here is your required HTTP request:
/**
* Method to make json array request where response starts with [
* */
private void makeJsonArrayRequest() {
String url = "YOUR_API_URL";
JsonArrayRequest req = new JsonArrayRequest(url,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d("onResponse", response.toString());
// Here response is:
// [{ "name":"George", "id":"2222", "lastname":"wist", "date":"07/08/07" }, { "name":"aaron", "id":"1111", "lastname":"borris", "date":"06/06/09" }]
try {
// Parsing json array response
// loop through each json object
jsonResponse = "";
for (int i = 0; i < response.length(); i++) {
JSONObject person = (JSONObject) response.get(i);
String name = person.getString("name");
String id = person.getString("id");
String lastname = phone.getString("lastname");
String date = phone.getString("date");
jsonResponse += "Name: " + name + "\n\n";
jsonResponse += "Id: " + id + "\n\n";
jsonResponse += "Lastname: " + lastname + "\n\n";
jsonResponse += "Date: " + date + "\n\n\n";
}
Log.d("onResponse", "JSON RESPONSE: " + jsonResponse);
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(),
"Error: " + e.getMessage(),
Toast.LENGTH_LONG).show();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d("onErrorResponse", "Error: " + error.getMessage());
Toast.makeText(getApplicationContext(),
error.getMessage(), Toast.LENGTH_SHORT).show();
hidepDialog();
}
});
// Adding request to request queue
AppController.getInstance().addToRequestQueue(req);
}
Here is a very nice tutorial about Android JSON parsing using Volley
Hope this will help~
I have problem sending a string parameter to a PHP file to download a song inserting the song's name from a edit text. I don't understand the error I'm receiving.
Thanks in advance for the help!
LOGCAT:
Response from url: {"error":false,"message":"Musics fetched successfully.","musics":[]}
i don't know why the array is empty.
The PHP file works if i use a rest client passing the song's name but not in the URL.
This is my code:
ANDROID SIDE:
class GetContacts extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
//Toast.makeText(MainActivity.this, "Json Data is downloading", Toast.LENGTH_LONG).show();
canzone = editText.getText().toString();
}
#Override
protected Void doInBackground(Void... arg0) {
HttpHandler sh = new HttpHandler();
// Making a request to url and getting response
String url = "http://blabla.org/AndroidMusicDownload/downloads/getMusic.php?canzone=" + canzone;
String jsonStr = sh.makeServiceCall(url);
Log.e(TAG, "Response from url: " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
/* title=jsonObj.getString("title");
link=jsonObj.getString("link");
HashMap<String, String> contact = new HashMap<>();
contact.put("title", title);
contact.put("link", link);
System.out.println("LINK: "+link);
contactList.add(contact);
*/
Toast.makeText(MainActivity.this, jsonObj.getString("message"), Toast.LENGTH_SHORT).show();
JSONArray jsonArray = jsonObj.getJSONArray("musics");
for (int i = 0; i < jsonArray.length(); i++) {
//Declaring a json object corresponding to every pdf object in our json Array
JSONObject jsonObject = jsonArray.getJSONObject(i);
//Declaring a Pdf object to add it to the ArrayList pdfList
// Pdf pdf = new Pdf();
// String pdfName = jsonObject.getString("name");
//String pdfUrl = jsonObject.getString("url");
//pdf.setName(pdfName);
//pdf.setUrl(pdfUrl);
//pdfList.add(pdf);
canzone_cantante = jsonObject.getString("canzone_cantante");
}
/* pdfAdapter=new PdfAdapter(MainActivity.this,R.layout.list_layout, pdfList);
listView.setAdapter(pdfAdapter);
pdfAdapter.notifyDataSetChanged();*/
HashMap<String, String> contact = new HashMap<>();
// adding each child node to HashMap key => value
contact.put("canzone_cantante", canzone_cantante);
//contact.put("email", email);
// contact.put("mobile", mobile);
/* Toast.makeText(getApplicationContext(),
"LINK: "+link ,
Toast.LENGTH_LONG).show();*/
// adding contact to contact list
System.out.println("LINK: " + canzone_cantante);
contactList.add(contact);
} catch (final JSONException e) {
Log.e(TAG, "Json parsing error: " + e.getMessage());
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Json parsing error: " + 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;
}
PHP CODE:
<?php
if($_SERVER['REQUEST_METHOD']=='POST'){
$canzone = $_POST['canzone'];
require_once 'dbDetails.php';
$con = mysqli_connect(DB_HOST,DB_USERNAME,DB_PASSWORD,DB_NAME) or die("Unable to connect");
$sql = "SELECT * FROM music where canzone = '$canzone'";
$result = mysqli_query($con,$sql);
//response array
$response = array();
$response['error'] = false;
$response['message'] = "Musics fetched successfully.";
$response['musics'] = array();
//traversing through all the rows
while($row =mysqli_fetch_array($result)){
$temp = array();
$temp['id'] = $row['id'];
$temp['canzone'] = $row['canzone'];
$temp['canzone_cantante'] = $row['canzone_cantante'];
$temp['url'] = $row['url'];
array_push($response['musics'],$temp);
}
echo json_encode($response);
}
You are sending your canzone parameter with get request( inAndroid) but trying to get it by POST global variable(in php)
so i suggest changing your php from $canzone= $_POST['canzone']; to $canzone= $_GET['canzone'];
EDIT
also change the if statement here
if($_SERVER['REQUEST_METHOD']=='POST'){
to
if($_SERVER['REQUEST_METHOD']=='GET'){
You send song name as GET not like post.
Also you need to urlencode name of a song, if it has more then one word in name.
Cheers :)
As I understood you post the request like this from Android App
String url = "http://blabla.org/AndroidMusicDownload/downloads/getMusic.php?canzone=" + canzone;
But there is a problem that you send 'canzone' in URL, so this is GET parameter, and in the PHP you grab this variable from $_POST, just change $_POST to $_GET, should work
Try with replacing this line
$canzone = $_POST['canzone'];
with
$canzone = $_REQUEST['canzone'];