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.
Related
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'm trying to convert a string array list to a JSONArray then send it to a remote server
I expect it to send my array in a JSONarray format
this is the error "'java.lang.String org.json.JSONObject.getString(java.lang.String)' on a null object reference"
My array got 2 elements,
when i try to fetch them in the log.d : list ja [null,null]
This is the code i'm using
public void sendCommande (){
bt_newCommande.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//----------------------------------
StringRequest stringRequest = new StringRequest(Request.Method.POST,url_ProdCommande, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d(TAG,"element envoie !");
//listProRest.clear();
//adapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
})
{
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String,String> params = new HashMap<String,String>();
JSONArray ja = new JSONArray(db.afficherTousProduit());
Log.d(TAG,"list ja "+ja.toString());
for(int i =0;i<ja.length();i++){
JSONObject j = ja.optJSONObject(i);
/*
try {
params.put("idProduit",j.getString(db.afficherTousProduit().get(i).getIdProduct()));
params.put("qte",j.getString(String.valueOf(db.afficherTousProduit().get(i).getQtePro())));
params.put("heure",j.getString(db.afficherTousProduit().get(i).gethCollete()));
params.put("date",j.getString(db.afficherTousProduit().get(i).getDateCollete()));
} catch (JSONException e) {
e.printStackTrace();
}
*/
}
//params.put("id",arrayList.get(position).getIdProduct());
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());
requestQueue.add(stringRequest);
}
});
}
It looks like something is going wrong with
db.afficherTousProduit().get(i).getIdProduct()
I would set a breakpoint and check that the db is returning what you expect it to return.
From looking at your code, it seems like you are doing extra work converting to and from JSON several times. I could be wrong, but I think this could be cleaned up like so:
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String,String> params = new HashMap<String,String>();
JSONArray ja = new JSONArray(db.afficherTousProduit());
Log.d(TAG,"list ja "+ja.toString());
// Begin iterating through the JSON Array
for (int i=0; i < arr.length(); i++) {
// Get current JSON Object at index i
JSONObject j = arr.getJSONObject(i)
try {
// Return the specified value associated with the String for the current object
params.put("key",j.getJsonString("key");
} catch (JSONException e) {
e.printStackTrace();
}
}
//params.put("id",arrayList.get(position).getIdProduct());
return params;
}
It shouldn't require more than one db access to get the json array, and then it's a simple matter of iterating through each object and grabbing what you need from it. Check out the Java docs for more info.
Attempting to load specific api through twitch headers. This Code has always worked in the past in fact still works but is pulling another user that i have replaced.
Tried to use android volley url to string, tried Variable
tried to clear cache in code, in app, and in device
this appears to be related to the volley's cache but i cant seem to clear it.
I dont feel it is api related otherwise wouldn't pull the old information either. or at least wouldn't work after cache was cleared.
// Instantiate the RequestQueue.
RequestQueue queue = Volley.newRequestQueue(this);
queue.getCache().clear();
String url = "https://api.twitch.tv/helix/users?login=Twitchuser";
// Request a string response from the provided URL.
final JsonObjectRequest jsonObjectRequest = new JsonObjectRequest
(com.android.volley.Request.Method.GET, url, null, new
Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONObject jsonObject = response;
JSONArray JA = jsonObject.getJSONArray("data");
for (int i = 0; i < response.length(); i++) {
JSONObject object = JA.getJSONObject(i);
String bio = object.getString("description");
mTextView2.append(bio);
}
JSONObject jsonObject2 = response;
JSONArray JA2 = jsonObject2.getJSONArray("data");
for (int i = 0; i < response.length(); i++) {
JSONObject object = JA2.getJSONObject(i);
String name =
object.getString("display_name");
mTextView.append(name);
}
JSONObject jsonObject3 = response;
JSONArray JA3 = jsonObject3.getJSONArray("data");
for (int i = 0; i < response.length(); i++) {
JSONObject object = JA3.getJSONObject(i);
String Image =
object.getString("profile_image_url");
new
DownLoadImageTask(mImageView).execute(Image);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
, new Response.ErrorListener()
{
#Override
public void onErrorResponse(VolleyError error) {
mTextView.append("Welcome Guest");
Log.e("VOLLEY", "ERROR");
}
})
{ //this is the part, that adds the header to the request
#Override
public Map<String, String> getHeaders() {
Map<String, String> params = new HashMap<String, String>();
params.put("Client-ID", "Client id");
params.put("content-type", "application/json");
return params;
}
};
MySingleton.getInstance(this).addToRequestQueue(jsonObjectRequest);
shoud get twitch user name, description and logo and display to card within the android app. it does, but for the old user entered.
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 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.