Get JSON response from PHP file with OkHttp - java

I need to make simple JSON request from PHP file which is on my localhost server. PHP code executes smoothly and it looks like:
<?php
header('Content-type: application/json');
$db = new PDO('mysql:host=localhost;dbname=nadjiprijevoz;charset=utf8', 'root', '');
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$query = "Select * FROM rute";
try {
$stmt = $db->prepare($query);
$result = $stmt->execute();
} catch(PDOException $ex) {
// Greska kod izvodjenja querija
$response["success"] = 0;
$response["message"] = "Database Error!";
die(json_encode($response));
}
$rows = $stmt->fetchAll();
if($rows) {
$response["success"] = 1;
$response["message"] = "Rute dohvacene";
$response["rute"] = array();
foreach($rows as $row) {
$ruta = array();
$ruta["id"] = $row["id"];
$ruta["naziv"] = $row["naziv"];
$ruta["polaziste"] = $row["polaziste"];
$ruta["odrediste"] = $row["odrediste"];
array_push($response["rute"] , $ruta);
}
echo json_encode($response);
} else {
$response["success"] = 0;
$response["message"] = "Nema ruta";
die(json_encode($response));
}
?>
When i try to fetch JSON data with my android application i dont get any response from the PHP file. Im using OkHttp library for fetching response and until now it worked smoothly (i havent been using php files before, only pure json) but when i try to get php response it doesnt work. Main activity code looks like:
public class activityMain extends ActionBarActivity {
private final static String TAG = activityMain.class.getSimpleName();
Ruta[] mRute;
#InjectView(R.id.textView) TextView text1;
#InjectView(R.id.textView2) TextView text2;
#InjectView(R.id.textView3) TextView text3;
String redditUrl = "http://localhost/nadjiprijevoz/connect.php";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout_mainmenu);
ButterKnife.inject(this);
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url(redditUrl)
.build();
Call call = client.newCall(request);
call.enqueue(new Callback() {
#Override
public void onFailure(Request request, IOException e) {
}
#Override
public void onResponse(Response response) throws IOException {
try {
String jsonData = response.body().string();
Log.i(TAG, response.body().string());
if (response.isSuccessful()) {
mRute = parsePostDetails(jsonData);
text1.setText(mRute[0].getNaziv());
text2.setText(mRute[0].getPolaziste());
text3.setText(mRute[0].getOdrediste());
}
} catch (IOException e) {
Log.e(TAG, "Excepiton caught: " , e);
} catch (JSONException e) {
Log.e(TAG, "Excepiton caught: " , e);
}
}
});
}
private Ruta[] parsePostDetails(String jsonData) throws JSONException {
JSONObject rutaObjectJSON = new JSONObject(jsonData);
JSONArray rutaArrayJSON = rutaObjectJSON.getJSONArray("rute");
Ruta[] ruteTemp = new Ruta[rutaArrayJSON.length()];
for (int i = 0; i < ruteTemp.length; i++) {
JSONObject rutaDetailJSON = rutaArrayJSON.getJSONObject(i);
Ruta tempRuta = new Ruta();
tempRuta.setNaziv(rutaDetailJSON.getString("naziv"));
tempRuta.setOdrediste(rutaDetailJSON.getString("odrediste"));
tempRuta.setPolaziste(rutaDetailJSON.getString("polaziste"));
ruteTemp[i] = tempRuta;
}
return ruteTemp;
}
}
Does anyone know where am i making mistake, if you do i would be very thankful.

Related

Synchronize SQLite With MySql by sending array of available quotes and receive the missing Android Java

Synchronize SQLite With MySql by sending array of ids for the quotes available in the SQLite to php script that will compare it with the available in the database and receive the missing quotes
this method will work in every moment when the app started
btw i know i have mistakes in the php script for that i'm asking now
im facing this error !
D/error: org.json.JSONException: Value Arraynull of type java.lang.String cannot be converted to JSONArray
thank you !
DatabaseHelper.java
public Map<String,String> readIds(){
SQLiteDatabase db=this.getReadableDatabase();
Cursor cursor=db.rawQuery("SELECT * FROM "+TABLE_NAME_QUOTES,null);
Map<String,String> QuotesModuleArray = new HashMap<String, String>();
if (cursor.moveToFirst()){
do {
QuotesModuleArray.put("quote_id"+"["+cursor.getString(0)+"]", cursor.getString(0));
}while (cursor.moveToNext());
}
cursor.close();
return QuotesModuleArray;
}
MainActivity.java
public void Quotes_SQLITE() throws UnsupportedEncodingException {
String url=".../android/checkquotes.php";
Map<String,String> arrayListQuotes;
dbHandler = new DataBaseHelper(MainActivity.this);
arrayListQuotes = dbHandler.readIds();
System.out.println(Arrays.toString(new Map[]{arrayListQuotes}));
quotesListSQLite.clear();
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Request.Method.GET, url, null,
response -> {
Log.e("Quotesqlite : ",response.toString());
progressBar.setVisibility(View.GONE);
swipeRefreshLayout.setRefreshing(false);
for (int i = 0 ; i < response.length() ; i++){
try {
JSONObject jsonObject = response.getJSONObject(i);
int quote_id = jsonObject.getInt("quote_id");
String quote_name = jsonObject.getString("quote_name");
String quote_details = jsonObject.getString("quote_details");
String status = jsonObject.getString("status");
String parent_id = jsonObject.getString("parent_id");
int language_id = jsonObject.getInt("language_id");
QuoteSQLite quote = new QuoteSQLite(quote_id , quote_name , quote_details , status,parent_id, language_id);
dbHandler.Add_Quote(quote_id,quote_name,quote_details, status,parent_id, language_id);
quotesListSQLite.add(quote);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(context, error.getMessage()+"", Toast.LENGTH_SHORT).show();
Log.d("error",error.getMessage()+"");
if((error.getMessage()+"").equals("null")) {
try {
Quotes_SQLITE();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
}
})
{
#Override
protected Map<String, String> getParams() {
Map<String, String> params;
params=arrayListQuotes;
return params;
}
};
requestQueue.add(jsonArrayRequest);
}
PHP Script
<?php
header('Content-Type: application/json; charset=utf-8');
define('DB_HOST', 'localhost');
define('DB_USER', 'ibnabita_alihaydar');
define('DB_PASS', '81336874');
define('DB_NAME', 'ibnabita_secure_imam');
$conn = mysqli_connect(DB_HOST, DB_USER, DB_PASS, DB_NAME);
mysqli_query($conn,"SET NAMES 'utf8'");
mysqli_query($conn,'SET CHARACTER SET utf8');
$allarray = array();
$toaddarray = array();
$flag = [];
$i = 0 ;
if(mysqli_connect_error($conn))
{
echo "Failed to connect to database ".mysqli_connect_error();
}
$sql="select quote_id from quotes";
$result2=mysqli_query($conn,$sql);
if($result2)
{
while($row=mysqli_fetch_array($result2,MYSQLI_BOTH))
{
array_push($allarray,$row["quote_id"]);
}
}
$ids = array();
foreach($_POST as $key=>$value){
$ids[] = $_POST[$key];
}
$data = json_decode($ids,true);
foreach($data as $item) { //foreach element in $arr
echo $item."\n" ;
}
foreach($allarray as $item) { //foreach element in $arr
//echo $item."\n" ;
if(in_array( $item ,$data))
{
}
else
{
$sql23="select * from quotes where quote_id=".$item;
$result23=mysqli_query($conn,$sql23);
$row23=mysqli_fetch_array($result23,MYSQLI_BOTH);
$flag[]=$row23;
}
}
print(json_encode($flag,JSON_UNESCAPED_UNICODE));
mysqli_close($conn);
?>

How to send JSONArray to PHP server using Volley?

I'm fairly inexperienced with Android programming and am having issues sending a JSONArray to my PHP server. I am using the following code to generate the JSONArray from my cursor:
public JSONArray matrixJSON(){
Cursor cursor = db.rawQuery("SELECT columnID,rowID,value FROM Matrix WHERE PolicyID=" + curPolicy,null);
JSONArray resultSet = new JSONArray();
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
int totalColumn = cursor.getColumnCount();
JSONObject rowObject = new JSONObject();
for (int i = 0; i < totalColumn; i++) {
if (cursor.getColumnName(i) != null) {
try {
rowObject.put(cursor.getColumnName(i),
cursor.getString(i));
} catch (Exception e) {
Log.d(TAG, e.getMessage());
}
}
}
resultSet.put(rowObject);
cursor.moveToNext();
}
cursor.close();
return resultSet;
}
I believe I am misunderstanding how to properly send data via JsonARrayRequest. Here is the following code that I am using to send the data.
public void sendData(JSONArray data) {
RequestQueue queue = Volley.newRequestQueue(this);
String url = "http://10.123.20.180:8080/insertmatrix.php";
JsonArrayRequest dataReq = new JsonArrayRequest(Request.Method.POST, url, data,
response -> Toast.makeText(MainActivity.this, "Success", Toast.LENGTH_LONG).show(),
error -> Toast.makeText(MainActivity.this, "Error", Toast.LENGTH_LONG).show()){
#Override
protected Response<JSONArray> parseNetworkResponse(NetworkResponse response) {
if (response.data == null || response.data.length == 0) {
return Response.success(null, HttpHeaderParser.parseCacheHeaders(response));
} else {
return super.parseNetworkResponse(response);
}
}
};
queue.add(dataReq);
}
Instead of sending the data, I am left with a blank array. The cursor to JSONarray function is working properly as I can see in debug, but the php server is receiving a blank array. I assume there is some essential functions I am missing.
Fixed it by switching my array into a string and then using a StringRequest to send the data.
Updated function:
public void sendData(JSONArray data) {
RequestQueue queue = Volley.newRequestQueue(this);
String url = "http://10.123.20.180:8080/insertmatrix.php";
String json = data.toString();
StringRequest dataReq = new StringRequest(Request.Method.POST,url,response -> Toast.makeText(MainActivity.this, "Success", Toast.LENGTH_LONG).show(),
error -> Toast.makeText(MainActivity.this, "Error", Toast.LENGTH_LONG).show()){
#Override
protected Map<String,String> getParams(){
Map<String,String> params = new HashMap<String,String>();
params.put("data",json);
return params;
}
};
queue.add(dataReq);
}

Android Volley - POST-Parameter not reaching PHP-Script

I want to get Infos from a Database. When i use a Query without parameters (e.g. "Select * from users;" my script works fine.
Now i have the following script which returns an empty Array. When i replace the $groupId in script with a string value (e.g. "Group1") it returns the expected Items.
<?php
$sql = "";
if($_SERVER['REQUEST_METHOD']== 'POST') {
$flag = array();
$groupId = $_POST['groupId'];
require_once('dbConnect.php');
$sql = "SELECT * FROM users where groupId = '$groupId'";
if($out = mysqli_query($con,$sql)){
//echo "Successfully Registered";
while($row = mysqli_fetch_array($out))
{
$flag[] = $row;
}
print(json_encode($flag));
}else{
echo "Could not register";
}
}else{
echo 'error';
}
//mysqli_close($con);
?>
When i call the following function with the hashmap hashMapGetNames.put("groupId", "Group#1");
then i get an empty array and the info: "No, Group ID is not set"
public ArrayList<String> get(String url, final HashMap<String, String> hashMap, final Context context) {
//Download the items from DB
final ArrayList<String> items = new ArrayList<>();
RequestQueue queue = Volley.newRequestQueue(context);
JSONObject parameters = new JSONObject(hashMap);
final JsonRequest<JSONArray> jsonArrayRequest = new
JsonRequest<JSONArray>(Request.Method.GET, url, parameters.toString(),
new com.android.volley.Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray jsonArray) {
if(jsonArray == null){
Log.d("Downloader", "FAIL: NO NAMES FOUND");
}
else {
for (int zähler = 0; zähler < jsonArray.length(); zähler++){
try {
Log.d("Downloader", "sind bei zähler " + zähler);
JSONObject object = jsonArray.getJSONObject(zähler);
String name = object.getString("name");
Log.d("Name", name);
items.add(name);
}
catch (JSONException e) {
Log.d("Downloader", "Catching exception");
e.printStackTrace();
}
}
}
}
}, new com.android.volley.Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("Downloader", "Error: " + error.toString());
}
})
{
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Log.d("Downloader", "gettingParams");
return hashMap;
}
#Override
protected Response<JSONArray> parseNetworkResponse(NetworkResponse response) {
Log.d("Downloader", "parsing Network response");
try {
String jsonString = new String(response.data,
HttpHeaderParser
.parseCharset(response.headers));
Log.d("Downloader", "Parsing success");
return Response.success(new JSONArray(jsonString),
HttpHeaderParser
.parseCacheHeaders(response));
} catch (UnsupportedEncodingException e) {
Log.d("Downloader", e.toString());
return Response.error(new ParseError(e));
} catch (JSONException je) {
Log.d("Downloader", je.toString());
return Response.error(new ParseError(je));
}
}
};
queue.add(jsonArrayRequest);
return items;
}
So the Script seems right but the parameter does not reach the Script. Any Ideas where the error could hide?
EDIT: I edited the code like shown in the tutorial commented below and use the same dbConnect.php file. but it prints out error - so the problem still exist. That means that the Request Method is not "Post".
Android Monitor prints out:
parsing Network response
Downloader: Parsing success
Error: com.android.volley.ParseError: org.json.JSONException: End of input at character 0
try this code...
#Override
protected Map<String, String> getParams() throws AuthFailureError {
//Creating parameters
Map<String,String> params = new Hashtable<String, String>();
//Adding parameters
params.put("groupId", "122");
//returning parameters
return params;
}

Value of type java.lang.String cannot be converted to JSONObject on Response.Listener

Hi i got this problem retrieving data, im using android volley and json to get data from web server.
heres my php file :
<?php
$con = mysqli_connect("***", "***", "***", "***");
// listing input entries for query
$city = $_POST["city"];
$term = $_POST["term"];
$p_type = $_POST["property_type"];
$min = $_POST["price_min"];
$max = $_POST["price_max"];
$bedrooms = $_POST["bedrooms"];
$bathrooms = $_POST["bathrooms"];
$query = "SELECT * FROM listing WHERE city = ? AND term = ? AND property_type = ? AND bedrooms = ? AND bathrooms = ?
AND price BETWEEN ? AND ?";
$statement = mysqli_prepare($con, $query);
mysqli_bind_param($statement, "sssiiii", $city, $term, $p_type, $bedrooms, $bathrooms, $min, $max);
mysqli_stmt_execute($statement);
mysqli_stmt_store_result($statement);
mysqli_stmt_bind_result($statement, $p_id, $p_name, $p_type, $term, $city, $address, $lot_area, $floor_area, $price,
$bedrooms, $bathrooms, $host_name, $host_contact_no, $host_details, $date_listed, $user_id);
$count = mysqli_stmt_num_rows($statement);
mysqli_stmt_close($statement);
$response = array();
$response["hasData"] = false;
if($count > 0){
$response["hasData"] = true;
while(mysqli_stmt_fetch($statement)){
$response["property_name"]= $p_id;
$response["property_type"] = $p_type;
$response["term"] = $term;
$response["city"] = $city;
$response["address"] = $address;
$response["lot_area"] = $lot_area;
$response["floor_area"] = $floor_area;
$response["price"] = $price;
$response["bedroom"] = $bedroom;
$response["bathroom"] = $bathroom;
$response["host_name"] = $host_name;
$response["host_contact_no"] = $host_contact_no;
$response["host_details"] = $host_details;
$response["date_listed"] = $date_listed;
}
}else{
$response["hasData"] = false;
}
echo json_encode($response);
?>
i have a java class name searchListingRequest.java
public class SearchListingRequest extends StringRequest {
private static final String SEARCH_REQUEST_URL = "http://homeseek.netau.net/searchLising.php";
private Map<String, String> params;
public SearchListingRequest(String city, String term, String p_type,
int price_min, int price_max, int bedrooms, int bathrooms, Response.Listener<String> listener){
super(Method.POST, SEARCH_REQUEST_URL, listener, null);
params = new HashMap<>();
params.put("city", city);
params.put("term", term);
params.put("property_type", p_type);
params.put("price_min", price_min + "");
params.put("price_max", price_max + "");
params.put("bedrooms", bedrooms + "");
params.put("bathrooms", bathrooms + "");
}
#Override
public Map<String, String> getParams() {
return params;
}
}
and in my other class ShowResults.java i call the class above to create instance and make a http request:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_show_results);
//unfocus on edittexts when starting
this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
//gets data from home fragment
Intent intent = getIntent();
//initialize listview
data_listing = (ListView) findViewById(R.id.lv_data_listing);
retrieveData(showResults, intent, data_listing);
}
public void retrieveData(Activity activity,Intent intent, final ListView lv){
final String inputCity = intent.getStringExtra("city");
final String inputTerm = intent.getStringExtra("term");
final String inputType = intent.getStringExtra("type");
final int inputPMin = Integer.parseInt(intent.getStringExtra("price_min"));
final int inputPMax = Integer.parseInt(intent.getStringExtra("price_max"));
final int inputBedrooms = Integer.parseInt(intent.getStringExtra("bedrooms"));
final int inputBathrooms = Integer.parseInt(intent.getStringExtra("bathrooms"));
test = (TextView) findViewById(R.id.tv_test);
Response.Listener<String> responseListener = new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonResponse = new JSONObject(response);
JSONArray responseArray = new JSONArray(response);
boolean hasData = jsonResponse.getBoolean("hasData");
// check if has data
if(hasData){
test.setText("have data");
}
else{// no data retrieved
showAlertDialog();
test.setText("no data");
}
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(), "Can't connect to server.", Toast.LENGTH_SHORT).show();
test.setText("error");
}
}
};
SearchListingRequest searchListingRequest =
new SearchListingRequest(inputCity,inputTerm,inputType,inputPMin,inputPMax,inputBedrooms,inputBathrooms,responseListener);
RequestQueue queue = Volley.newRequestQueue(getApplicationContext());
queue.add(searchListingRequest);
}
and when i run the application the text displays "error" which means it has a jsonexception.
here's the logcat :
Value <!DOCTYPE of type java.lang.String cannot be converted to JSONObject
I really have no idea what this means. thanks for helping!
This is because by default volley will not send the POST body in JSON format and I think server is expecting the POST body in JSON. Hence you need to override getBody() method and change the format from application/x-www-form-urlencoded to json.
Please refer the below code :
#Override
public bytes[] getBody() {
new JSONObject(params).toString().getBytes();
}
Also consider overriding getBodyContentType and setting it to JSON.

JSONArrayRequest and PHP pair not working

I am creating class which should send JSONArrayRequest using volley with specific params, then find mysql rows which equals these params and send it back. I wrote simple mysql function which receive POST params and Java method which send and receive JSONObjects. But it isn't working and I receive nothing.
This is my PHP file called details.php. It receive parameters from my Android App and send back an array.
require_once __DIR__ . '/db_connect.php'
$db = new DB_CONNECT();
$path= $_POST["path"];
$result = mysql_query("SELECT * FROM modx_ms2_product_files WHERE path = $path") or die(mysql_error());
// check for empty result
if (mysql_num_rows($result) > 0) {
// looping through all results
// products node
$json_response = array();
while ($row = mysql_fetch_array($result)) {
// temp user array
$product = array();
$product ["file"] = $row["file"];
// push single product into final response array
array_push($json_response, $product);
}
// echoing JSON response
echo json_encode($json_response);
$conn->close();
}
This is my method getArray(), which send request and receive response:
public void getarray() {
String path = "1578/";
final String URL = "http://myurl.io/details.php";
HashMap<String, String> params = new HashMap<String, String>();
params.put("path", path);
JsonArrayRequest customarray = new JsonArrayRequest(Request.Method.POST,URL,new JSONObject(params),new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
if (response.length() > 0) {
// Parsing json
for (int i = 0; i < response.length(); i++) {
try {
JSONObject Obj = response.getJSONObject(i);
pics pic = new pics();
pic.setFile(Obj.getString("file"));
Log.i("cmon", Obj.getString("file"));
pics.add(pic);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
AppController.getInstance().addToRequestQueue(customarray);
}
This is my modx_ms2_product_files table:
http://i.imgur.com/yl1f7Ze.png
http://i.imgur.com/9V6PrBU.png
Have you tried using StringRequest? For some reason when i used JsonArrayRequest i didn't get any response back from the server. If you decide to create a StringRequest you could convert your response to a JSONArray like this:
StringRequest get = new StringRequest(Method.POST, URL, new Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONArray myArray = new JSONArray(response);
for(int i = 0; i < myArray.length(); i++)
{
JSONObject jObj = myArray.getJSONObject(i);
// get your data here
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
Then of course add your request to the request queue.

Categories

Resources