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.
Related
I wrote android app to read json using volley.
If i use example URL from internet - i don't have problem, the data is read. But when i try to read data from local host, I am getting an error.
The same data i can see in web browser in my emulator.
my URL: "http://10.0.2.2/volley_sample/get_data.php"
my code:
private void sendGetRequest() {
RequestQueue queue = Volley.newRequestQueue(MainActivity.this);
String url = "http://10.0.2.2/volley_sample/get_data.php"; //it doesn't work
//String url ="https://reqres.in/api/users/2"; //it works
// Request a string response from the provided URL.
StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
// Display the first 10 characters of the response string.
get_response_text.setText("Response is: " + response.substring(0, 10));
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
get_response_text.setText("That didn't work!");
}
});
// Add the request to the RequestQueue.
queue.add(stringRequest);
}
adres "http://10.0.2.2/volley_sample/get_data.php" works in web browser in my emulator.
I tried also "http://192.168....", "127.0.0.1....", "localhost/volley_sample...." etc., and neither works.
adres "https://reqres.in/api/users/2" (example from internet) work without problem.
ofc. i added "<uses-permission android:name="android.permission.INTERNET"/>"
I have no idea what I am doing wrong :(
I can get very strange issue in my project. I can get the response from volley over the internet and after reposne I want to store it in sharedpref, but issue is that when I get the response and showed up within resonse function then it shows correct data, but when I used to save it outside the response function sharedpref it gives 0. I declared the string public and top of the class but got no luck. Am very strange whats the issue.
SharedPreferences savelogin = getSharedPreferences("login",MODE_PRIVATE);
final SharedPreferences.Editor slogin = savelogin.edit();
String url = "https://datafinderdatabase.xyz/dfapi/FetchId.php?username="+fuser;
StringRequest stringRequest = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
userid = response.toString();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toasty.error(getApplicationContext(), "Network Issue", Toast.LENGTH_SHORT).show();
}
});
RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());
requestQueue.add(stringRequest);
slogin.putString("username",fuser);
slogin.putString("password",fpass);
slogin.putString("userid",userid);
slogin.commit();
This is because your call to the API is asynchronous. Therefore, the result you get back may be processed after that function finishes. To solve this, you can take a Interface approach, explained here for a similar issue:
wait until firebase retrieves data
OR: you need to save the variable to the shared preferences inside the onResponse function.
These:
slogin.putString("username",fuser);
slogin.putString("password",fpass);
slogin.putString("userid",userid);
slogin.commit();
must be inside this:
#Override
public void onResponse(String response) {
userid = response.toString();
//here
}
I have a mysql data base and a table in it, I encode it to json, when I run php file in browser i got something like this :
[
{
"product":"\u0645\u0627\u0633\u062a \u067e\u0631 \u0686\u0631\u0628 \u0633\u0648\u0646 \u06a9\u0627\u0644\u0647",
"info":"\u0645\u0627\u0633\u062a \u0633\u0648\u0646 \u06f5 \u062f\u0631\u0635\u062f \u0686\u0631\u0628\u06cc \u06f1\u060c\u06f5 \u06a9\u06cc\u0644\u0648\u06cc\u06cc \u06a9\u0627\u0644\u0647",
"price":"7\u060c800 \u062a\u0648\u0645\u0627\u0646",
"date":null,
"sale":"no sale",
"image":"Image source",
"buy":"Store"
}
]
that i think its ok , but when I get it in my android code its like the picture linked below:
this is the code i used in android
StringRequest stringRequest = new StringRequest(Request.Method.GET, server_url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONArray array = new JSONArray(response);
for (int i = 0; i < array.length(); i++) {
JSONObject product = array.getJSONObject(i);
productList.add(new Product(
product.getString("product"),
product.getString("info"),
product.getString("price"),
product.getString("date"),
product.getString("sale"),
product.getString("image"),
product.getString("buy")
));
}
ProductAdapter adapter = new ProductAdapter(MainActivity.this, productList);
recyclerView.setAdapter(adapter);
}
catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}
);
Volley.newRequestQueue(this).add(stringRequest);
So what can I do?
Thank you for your time.
I think you need to add an Accept header in your android request. The server is returning HTML because that is the default content-type. You should add a HTTP header "Accept: application/json".
I am setting up a sign in page for Android.
Android request code:
RequestQueue queue = Volley.newRequestQueue(getApplicationContext());
StringRequest sr = new StringRequest(Request.Method.POST,"http://www.MY-URL.ir/signup.php", new Response.Listener<String>() {
#Override
public void onResponse(String response) {
System.out.println("--------------> res : " + response + " <------------------- res");
Toast.makeText(Main2Activity.this, "res", Toast.LENGTH_SHORT).show();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(Main2Activity.this, "-----------------> err", Toast.LENGTH_SHORT).show();
}
}){
#Override
protected Map<String,String> getParams(){
Map<String,String> params = new HashMap<String, String>();
params.put("name","David Lee");
return params;
}
};
queue.add(sr);
PHP auntification code:
<?php
if(isset($_POST['name']))
{
$name=$_POST['name'];
$response = array();
$response['name'] = $name;
echo json_encode($response);
} else {
$no_data=array();
$no_data['none']= 'no data received';
echo json_encode($no_data);
}
?>
I am sending David Lee as a name and I want to insert it in a database (MySQL)
params.put("name","David Lee");
But I can't recognize the result of the request in my Php MySql table.
Is my code right?
Authentication request returns the following response:
System.out: --------------> res : <html><body><script type="text/javascript" src="/aes.js" ></script><script>function toNumbers(d){var e=[];d.replace(/(..)/g,function(d){e.push(parseInt(d,16))});return e}function toHex(){for(var d=[],d=1==arguments.length&&arguments[0].constructor==Array?arguments[0]:arguments,e="",f=0;f<d.length;f++)e+=(16>d[f]?"0":"")+d[f].toString(16);return e.toLowerCase()}var a=toNumbers("f655ba9d09a112d4968c63579db590b4"),b=toNumbers("98344c2eee86c3994890592585b49f80"),c=toNumbers("1ab6d8dc093d812e09e8e3d3ffcb99d5");document.cookie="__test="+toHex(slowAES.decrypt(c,2,a,b))+"; expires=Thu, 31-Dec-37 23:55:55 GMT; path=/"; location.href="http://www.papyrusmarket.ir/signup.php?i=1";</script><noscript>This site requires Javascript to work, please enable Javascript in your browser or use a browser with Javascript support</noscript></body></html> <------------------- res
How should back-end send the response to android? And how can I get it?
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.