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;
}
Related
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);
?>
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);
}
I created the functions like the json file in the picture. When I send a post request, the response is "Unexpected response code 500" for. I think the problem is caused by json arrays, I don't understand exactly why this error is coming. Server url works fine, successfully post on swift. Thanks
json_array_requested_from_me
private void CreditCardParams(Map<String, String> requestParameters) {
JSONArray creditCardItems = new JSONArray();
JSONObject item_creditCardItems = new JSONObject();
try {
item_creditCardItems.put("CC_NUMBER", "1111");
item_creditCardItems.put("EXP_MONTH", “11”);
item_creditCardItems.put("EXP_YEAR", “1111");
item_creditCardItems.put("CC_CVV", “111”);
item_creditCardItems.put("CC_OWNER", “TEST USER”);
item_creditCardItems.put("INSTALLMENT_NUMBER", "1");
} catch (JSONException e) {
e.printStackTrace();
}
creditCardItems.put(item_creditCardItems);
requestParameters.put("CreditCard", (creditCardItems.toString()));
}
private void CustomerParams(Map<String, String> requestParameters) {
JSONArray CustomerItems = new JSONArray();
JSONObject item_Customer = new JSONObject();
try {
item_Customer.put("FIRST_NAME", "Firstname");
item_Customer.put("LAST_NAME", "Lastname");
item_Customer.put("MAIL", "test#test.com");
item_Customer.put("PHONE", "+11111111");
item_Customer.put("CITY", "Test");
item_Customer.put("STATE", "Test");
item_Customer.put("ADDRESS", "Test");
item_Customer.put("CLIENT_IP", "111.11.11.11”);
} catch (JSONException e) {
e.printStackTrace();
}
CustomerItems.put(item_Customer);
requestParameters.put("Customer", (CustomerItems.toString()));
}
private void ProductParams(Map<String, String> requestParameters) {
JSONArray ProductItems = new JSONArray();
JSONObject item_Product = new JSONObject();
try {
item_Product.put("PRODUCT_ID", "1");
item_Product.put("PRODUCT_NAME", “1”);
item_Product.put("PRODUCT_CATEGORY", “Elec.”);
item_Product.put("PRODUCT_DESCRIPTION", “Info”);
item_Product.put("PRODUCT_AMOUNT", 15.00);
} catch (JSONException e) {
e.printStackTrace();
}
ProductItems.put(item_Product);
requestParameters.put("Product", (ProductItems.toString()));
}
private void ConfigParams(Map<String, String> requestParameters) {
JSONArray configItems = new JSONArray();
JSONObject item = new JSONObject();
try {
item.put("MERCHANT", "TEST1234");
item.put("MERCHANT_KEY", “123”);
item.put("BACK_URL", "localhost");
item.put("PRICES_CURRENCY", "USD");
item.put("ORDER_REF_NUMBER", "RFN0001");
item.put("ORDER_AMOUNT", 15.00);
} catch (JSONException e) {
e.printStackTrace();
}
configItems.put(item);
requestParameters.put("Config", (configItems.toString()));
}
private void post_func(){
StringRequest stringRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
System.out.println(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
System.out.println(error);
}
}
){
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String,String>();
CreditCardParams(params);
CustomerParams(params);
ProductParams(params);
ConfigParams(params);
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
As you know, 500 server error is an error caused by an exception in the server. If you don't get an error when you send the JSON file you showed from an http request sender program like postman, the problem is in the JSON object you sent to the server.
I've tried with normal JSONArrayRequests and StringRequests and everything was fine untill now. I want to send an JSONArrayRequest with POST parameters to get some MySQL result in JSON format from the script. Unfortunately I get [] everytime in response. I have checked .php file and query with _GET method and the script worked perfectly returning desired rows in Json format.
I read here (https://stackoverflow.com/a/18052417/4959185) Volley Team have added JSONArrayRequest with _POST parameter to their class. However it does not work in my case. Could you please look what is wrong with that function:
private void getFavouriteRecipes(final String userUniqueId, final int offset) {
JsonArrayRequest favouriteRecipesReq = new JsonArrayRequest(Request.Method.POST,
AppConfig.URL_GETFAVOURITERECIPES, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d("odpowiedz", "Odpowiedź ulubionych: " + response);
for (int i = 0; i < response.length(); i++) {
try {
JSONObject jObj = response.getJSONObject(i);
RecipeItem recipeItem = new RecipeItem();
recipeItem.setRecipeUniqueID(jObj.getString("unique_id"));
recipeItem.setRecipeTitle(jObj.getString("title"));
recipeItem.setRecipeImgThumbnailLink(jObj.getString(
"img_tumbnail_link"));
recipeItem.setRecipeAddAte(jObj.getString("add_date"));
recipeItem.setRecipeKitchenType(jObj.getString("kitchen_type"));
recipeItem.setRecipeMealType(jObj.getString("meal_type"));
recipeItem.setRecipeName(jObj.getString("name"));
recipeItem.setRecipeSurname(jObj.getString("surname"));
recipeItem.setRecipeLikeCount(jObj.getString("like_count"));
recipeFavouriteItems.add(recipeItem);
} catch (JSONException e) {
e.printStackTrace();
showSnackbarInfo("Błąd Json: " + e.getMessage(),
R.color.snackbar_error_msg);
}
}
recipeFavouriteItemsAdapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("odpowiedz", "Błąd pobierania ulubionych: " +
Integer.toString(error.networkResponse.statusCode));
showSnackbarInfo(Integer.toString(error.networkResponse.statusCode),
R.color.snackbar_error_msg);
}
}) {
#Override
protected Map<String, String> getParams() {
// Posting Parameters to Login URL
Map<String, String> params = new HashMap<>();
params.put("user_unique_id", userUniqueId);
params.put("offset", Integer.toString(offset));
Log.d(TAG, "wysylam parametry: " + userUniqueId + ", " + Integer.toString(offset));
return params;
}
};
// Adding Request to Request Queue
AppController.getInstance().addToRequestQueue(favouriteRecipesReq);
}
My PHP Script:
https://ideone.com/ZxYzHr
I have found another way to get JSONArrayResponse with sending parameters. I think that will help somebody.
U just write standard JSONArrayRequest liek this:
JsonArrayRequest favouriteRecipesReq = new JsonArrayRequest(prepareGetMethodUrl(),
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d("odpowiedz", "Odpowiedź ulubionych: " + response.toString());
for (int i = 0; i < response.length(); i++) {
try {
JSONObject jObj = response.getJSONObject(i);
RecipeItem recipeItem = new RecipeItem();
recipeItem.setRecipeUniqueID(jObj.getString("unique_id"));
recipeItem.setRecipeTitle(jObj.getString("title"));
recipeItem.setRecipeImgThumbnailLink(jObj.getString(
"img_tumbnail_link"));
recipeItem.setRecipeAddAte(jObj.getString("add_date"));
recipeItem.setRecipeKitchenType(jObj.getString("kitchen_type"));
recipeItem.setRecipeMealType(jObj.getString("meal_type"));
recipeItem.setRecipeName(jObj.getString("name"));
recipeItem.setRecipeSurname(jObj.getString("surname"));
recipeItem.setRecipeLikeCount(jObj.getString("like_count"));
recipeFavouriteItems.add(recipeItem);
} catch (JSONException e) {
e.printStackTrace();
}
}
recipeFavouriteItemsAdapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("odpowiedz", "Błąd pobierania ulubionych: " +
Integer.toString(error.networkResponse.statusCode));
showSnackbarInfo(Integer.toString(error.networkResponse.statusCode),
R.color.snackbar_error_msg);
}
});
// Adding Request to Request Queue
AppController.getInstance().addToRequestQueue(favouriteRecipesReq);
Instead of standard URL to the PHP script I inserted function returning String called prepareGetMethodUrl().
Let's look inside it:
private String prepareGetMethodUrl() {
return AppConfig.URL_GETFAVOURITERECIPES + "?user_unique_id=" + userUniqueId + "&offset=" +
Integer.toString(offset);
}
As you can see it's very simple. I get standard AppConfig.URL_GETFAVOURITERECIPES which is static field in AppConfig class conatining direct link to my PHP script on my serwer f.e http://www.someserversite.com/my_api/gmy_php_script.php and combine it with parametres values I need to send to the script: user_unique_id and it's content userUniqueId and offset which content is offset parsed from int to String.
Inside my script I just call:
<?php
// some code
// Receiving The Post Params
$user_unique_id = $_GET['user_unique_id'];
$offset = $_GET['offset'];
echo $user_unique_id . "<br />";
echo $offset;
?>
I feel like this is a very basic concept missunderstanding. In my Android app I make HTTP requests using Volley lib. At first I made the requests through a JsonObjectRequest in the Activity code and worked right, but now I separated the request code in a class apart so I can call it from any Activity. The new class has a method that returns the requested JSONObject but any "json action" I do over the returned object ends in an error.
Here is the new class code, JSONRequests:
public class JSONRequests {
private JSONObject mResponse;
private String mURL = "https://myurl.com/";
public JSONObject getJSONObject(final String credentials, final String path) {
final JsonObjectRequest mRequest = new JsonObjectRequest(mURL.concat(path), null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
mResponse = response;
try {
Log.d("RESPONSE", mResponse.getString("id")); // It works here
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}
) {
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<String, String>();
headers.put("Authorization", "Basic " + credentials);
return headers;
}
};
MyApplication.getInstance().getRequestQueue().add(mRequest);
return mResponse;
}
}
And here is how I call getJSONObject from MyActivity:
JSONRequests mRequest = new JSONRequests();
JSONObject mInfo = mRequest.getJSONObject(mEncodedCredentials, mPath);
try {
Log.d("RESPONSE", mInfo.getString("id")); // This doesn't work
} catch (JSONException e) {
e.printStackTrace();
}
When in the Activity file, I used "response" as a JSONObject and it worked, but now separated it won't. I don't know if is a error with JSONObject or just that I'm not getting the returned object in the correct way. Thanks in advance.