How can I pass parameters to PHP files correctly - java

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'];

Related

How to fetch sum of column in MySQL using PHP based on id and display it in Android using Volley

I have a table called hotel_review in this I have hotel_stars column and I want to display the sum of all the hotel stars in Android using Volley. I want to display the average of the hotel rating, to do this I need the sum of the column. I think I'm close but not getting the values. I'm not getting any error but I can not fetch the values as well.
my php code:
<?php
require "init.php";
header('Content-Type: application/json;charset:UTF-8');
$hotel_id = $_POST['hotel_id'];
$query = mysqli_query($con, "SELECT SUM(hotel_stars) AS 'Total' FROM hotel_review WHERE hotel_id = '".$hotel_id."';");
$row = mysqli_fetch_assoc($query);
$sum = $row['Total'];
if($query)
{
$code = "getvalue";
$data[]['Total'] = $sum;
$result = array("code"=>$code,"stars" => $data);
echo json_encode($result);
}else {
$code = "not_get";
$msg = "Try Again....";
array_push($response, array("code"=>$code,"msg"=>$msg));
//echo("Error description: " . mysqli_error($con));
header('Content-Type: application/json;charset:UTF-8');
echo json_encode($response);
// echo("Error description: " . mysqli_error($con));
}
mysqli_close($con);
?>
my android code:
public void getHotelStars()
{
StringRequest stringRequest = new StringRequest(Request.Method.POST, getStars,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d("response", response);
JSONArray jsonArray = null;
try {
jsonArray = new JSONArray(response);
JSONObject jsonObject = jsonArray.getJSONObject(0);
String code = jsonObject.getString("code");
if (code.equals("not_get")) {
Toast.makeText(hotel_reviews.this, "error", Toast.LENGTH_SHORT).show();
} else {
String totalStars = jsonObject.getString("stars");
// String totalCount = jsonObject.getString("total_stars");
Toast.makeText(hotel_reviews.this, ""+totalStars, Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(hotel_reviews.this, "error", Toast.LENGTH_SHORT).show();
}
}){
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("hotel_id",HotelId);
//params.put("division",EmployeeDivision);
return params;
}
};MySingleton.getInstance(hotel_reviews.this).addToRequestque(stringRequest);
}
Im getting the proper hotel_id in params.put so no error is there in fetching id.
use it like this after you fire your query:
while ($row = mysqli_fetch_assoc($query)) {
$sum=$row["Total"];
echo $sum;
}
after your query and see if your total is there in $sum. Thereafter you can start using that anywhere.

org.json.JSONException: No value for status

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());
}
}

volley.parsererror:org.json.JSONException: value br of type java.lang.string cannot be converted to JSONObject

volley.parsererror:org.json
value br of type java.lang.string cannot be converted to JSONObject
Android Code
public void performSearch() {
String url= "http://192.168.0.136/fyp/stitle.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.i("Response", response.toString());
try {
//converting the string to json array object
JSONObject array = new JSONObject();
Log.i("test", " value : " + array.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 Code file to send json to android java file
<?php
include"connection.php";
if (isset($title = $_POST["Title"]){
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$query =$conn->prepare('SELECT isbn, title, authors, accession, publisher, pubyear, pages, rak, hr, vr, barcode FROM books where title like "%'.$title.'%" ');
$query->execute();
$query->bind_result($isbn, $title, $authors, $accession, $publisher, $pubyear, $pages, $rak, $hr, $vr, $barcode);
$books = array();
$data =array();
//traversing through all the result
while($query->fetch()){
$temp = array();
$temp['isbn'] = $isbn;
$temp['title'] = $title;
$temp['authors'] = $authors;
$temp['accession'] = $accession;
$temp['publisher'] = $publisher;
$temp['pubyear'] = $pubyear;
$temp['pages'] = $pages;
$temp['rak'] = $rak;
$temp['hr'] = $hr;
$temp['vr'] = $vr;
$temp['barcode'] = $barcode;
array_push($data, $temp);
}
$books['status'] = true;
$books['search'] = $data;
//displaying the result in json format
echo json_encode($books);
}}
?>
When run applicaion this error toast on screen [volley.parsererror:org.json.JSONException: value br of type java.lang.string cannot be converted to JSONArray]
There are several issues with your code. Let us deal with your PHP, first. Your PHP code should be designed to return some useful information whether it is successful or it fails--and why it fails.
I can't tell which class you are using to access your MySQL data, but in any case it is not PDO. I will show you an example using PDO because you can use prepared statements, which will help protect you from SQL injections attacks.
your PHP code is poorly designed and in addition to that it is open to a SQL injection attack!
Begin your PHP code with a isset check of your parameters. This code will return a JSONObject regardless of whether your query fails or not. This makes it easier to see what is going wrong--when it goes wrong.
<?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 __DIR__ . '/db_config.php';
// ...these variables
$host = DB_SERVER;
$db = DB_DATABASE;
$user = DB_USER;
$pass = DB_PASSWORD;
$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);
?>

Parsing JSON Array and Objects

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 :)

Cant get strings from db throught php and java in android app

I have mysql db and php script to get data from db.
I cant get array of strings in my android app, textview is empty no matter what I do. I checked my php and it is actually working so i guess i have some error in java code in android:
bShow.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST,
showUrl, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
System.out.println(response.toString());
try {
JSONArray students = response.getJSONArray("demo");
for (int i = 0; i < students.length(); i++) {
JSONObject student = students.getJSONObject(i);
String name = student.getString("name");
String lastname = student.getString("lastname");
String age = student.getString("age");
tvResult.append(name + " " + lastname + " " + age + " \n");
}
tvResult.setText("===\n");
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
System.out.append(error.getMessage());
}
});
requestQueue.add(jsonObjectRequest);
}
});
}
}
and my php file:
<?php
if($_SERVER["REQUEST_METHOD"]=="POST"){
include 'connection.php';
showStudent();
}
function showStudent()
{
global $connect;
$query = " Select * FROM demo; ";
$result = mysqli_query($connect, $query);
$number_of_rows = mysqli_num_rows($result);
$temp_array = array();
if($number_of_rows > 0) {
while ($row = mysqli_fetch_assoc($result)) {
$temp_array[] = $row;
}
}
header('Content-Type: application/json');
echo json_encode(array("students"=>$temp_array));
mysqli_close($connect);
}
?>
I tried php an mysql with postman and my guess is that im missing the obvious in java.
Any help is welcomed.
Query:
$query = " Select * FROM demo ";
your php is generating an array called: students
echo json_encode(array("students"=>$temp_array));
and you are trying to get an array called demo
JSONArray students = response.getJSONArray("demo");
change to:
JSONArray students = response.getJSONArray("students");

Categories