I am struggling with one situation. I am returning some json data from PHP server my code is as follows,
PHP API code:
if ($user != false) {
$result = mysql_query("SELECT stock_name,stock_location FROM btrack_stock WHERE user_id= '$user_id'") or die(mysql_error());
$rows = array();
$count = mysql_num_rows($result);
if($count > 0){
while ($r = mysql_fetch_assoc($result)) {
$rows[] = $r;
}
echo json_encode(array('usertransaction' => $rows));
}else{
$response["error"] = 1;
$response["error_msg"] = "You do not have any transaction so far. ";
echo json_encode($response);
}
}
On android side, I use a class that extends AsyncTask and on my onPostExecute I use:
protected void onPostExecute(JSONObject json) {
try {
if(json.getString("error_msg") != null){
String err = json.getString("error_msg");
stock_error.setText(err);
stock_error.setVisibility(View.VISIBLE);
pDialog.dismiss();
}else{
pDialog.dismiss();
Toast.makeText(getApplicationContext(), "Success", Toast.LENGTH_LONG).show();
}
}catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Well actually, I wanted to display error message that is returned from PHP server and display all the data if I got success message (here I am showing a Toast).
My question is how can we display error message if json returns error message and display success if json does not return error message.
* My code works fine if I get error_msg as json response but if I return other data the app stuck in process dialog with a warning in LogCat as " There is no value for error_msg".
Thanks in Advance.
Try this:
if json.isNull("error_msg") {
do_something()
}
else {
json.getString("error_msg");
do_something_else()
}
Related
I am getting some info from the server and the for used in onPostExecute was supposed to store the data into 2 different arrays. The server's response it's alright, it gets to the app, it is recognized as a JSON object, but when it comes to transforming it to a JSONArray to get the elements it just gets over that part of the code, as it wouldn't be written. So, after the JSONArray departamenteArray = obj.getJSONArray("departamente"); line, it just goes over the rest of it without making any changes.
.java code:
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
//hiding the progressbar after completion
try {
//converting response to json object
JSONObject obj = new JSONObject(s);
//if no error in response
if (!obj.getBoolean("error")) {
JSONArray departamenteArray = obj.getJSONArray("departamente");
for (int i = 0; i < departamenteArray.length(); i++) {
JSONObject dep = departamenteArray.getJSONObject(i);
// Verificare daca s-au primit probleme trimise de server
if (!dep.isNull("Departament")) {
String departament = SchimbareDiactritice(dep.getString("Departament")).replace("&","");
String id_departament= dep.getString("id_departament");
id_departamente.add(id_departament);
departamente.add(departament);
}
}
} else {
Toast.makeText(getApplicationContext(), "Some error occurred", Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
layout_validare.setVisibility(GONE);
linearLayout_obs_redirectionare.setVisibility(View.VISIBLE);
}
JSON response from the server :
{
"error": false,
"message": "Alerte reimprospatate",
"departamente": [{
"Departament": "Parcări",
"id_departament": 2
}, {
"Departament": "Trafic rutier și iluminat public",
"id_departament": 3
}, {
"Departament": "Salubritate și vandalism",
"id_departament": 4
}, {
"Departament": "Altele",
"id_departament": 5
}]
}
.php code on the server side:
if($stmt->num_rows > 0){
$stmt->bind_result($departament, $id_departament);
while($stmt->fetch()) {
$departamente[] = array (
"Departament"=>$departament,
"id_departament"=>$id_departament
);
$response['error'] = false;
$response['message'] = 'Alerte reimprospatate';
$response['departamente']= $departamente;
It seems that after a restart of the Android Studio it works. It must have been only a bug. The code shown above it's working properly.
I have a problem when attempting to use Fuel to send image to my server.
I am trying to use the Fuel.upload method.
Fuel.upload(urlfile).source { request, url ->
File(photopath)
}.responseString { request, response, result ->
}
the image is like : /storage/emulated/0/Android/data/fr.tais.riodi/files/Pictures/MyPicture4945313277123614993.jpg
$target_dir = "images/";
$target_file_name = $target_dir .basename($_FILES["file"]["name"]);
$response = array();
// Check if image file is a actual image or fake image
if (isset($_FILES["file"]))
{
if (move_uploaded_file($_FILES["file"]["tmp_name"], $target_file_name))
{
$success = true;
$message = "Successfully Uploaded";
}
else
{
$success = false;
$message = "Error while uploading";
}
}
else
{
$success = false;
$message = "Required Field Missing";
}
$response["success"] = $success;
$response["message"] = $message;
echo json_encode($response);
I tried to find an example of this operation. Have you an examples or an idea?
Thanks all
I am working on an app in Android Studio that downloads a json file from a php query, however when I have managed to read the contents of the json file from android, this contents does not behave as text, because when comparing a text entered from the app against the read from the json file, it never matches despite being the same text. (Example: password text from app and the password from the json file).
Php Code:
<?php
ini_set('display_errors', 'On');
error_reporting(E_ALL);
include('functions.php');
$col=$_GET["col"];
$colbus=$_GET["colbus"];
$tabla=$_GET["nomtable"];
$todfilas=$_GET["todasf"];
$dbuser =$_GET["username"];
$dbpass=$_GET["password"];
$dbbase=$_GET["dbname"];
//echo "$todfilas <br>";
if($todfilas == 1){
$sqlt="SELECT * FROM $tabla";
}else{
$sqlt="SELECT * FROM $tabla WHERE $col='$colbus'";
}
//echo "$sqlt <br>";
if($resultset=getSQLResultSet($sqlt,$dbuser,$dbpass,$dbbase)){
while ($row = $resultset->mysqli_fetch_array(MYSQLI_NUM)){
echo json_encode($row);
}
}
?>
Code from Android Studio:
private class ConsultData extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
// params comes from the execute() call: params[0] is the url.
try {
return downloadUrl(urls[0]);
} catch (IOException e) {
return "No es posible cargar pagina web o la direccion es invalida!";
}
}
// onPostExecute displays the results of the AsyncTask.
#Override
protected void onPostExecute(String result) {
JSONArray ja = null;
try {
ja = new JSONArray(result);
Log.d("Password:",ja.getString(7)+"="+logPass.getText().toString().trim());
logPass2.setText(ja.getString(7).trim());
String pass1 =logPass2.toString();
String pass0 = logPass.toString().trim();
if(pass0==pass1){
showAlertDialog("Session:","login is valid!");
} else{
showAlertDialog("Session:","password does not match!");
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
I'm not sure if the way to create the json file in the php query is the problem? because I can see the contents of the json array in Android Studio, but when I compare text from json array, they do not match even if they are the same ("123" = "123").
As seeing your code you doing so many mistakes like you are getting textview value thats not right way
change code like this
String pass1 =logPass2.getText().toString();
String pass0 = logPass.getText().toString().trim();
Also comparsion of string
if(pass0.equals(pass1)){
showAlertDialog("Session:","login is valid!");
} else{
showAlertDialog("Session:","password does not match!");
}
instead of this
if(pass0==pass1){
showAlertDialog("Session:","login is valid!");
} else{
showAlertDialog("Session:","password does not match!");
}
Can anyone help me? I debugg app many more time but I can not found what exact issue going in my android app. In my android app, My cases are describe below.
cases 1: Insert data into database It is perfectly worked fine.
case 2: That data display in to recycler view ok. It will display fine.
It will work with only single user login. When another user will login in to app and try to add data then It will get this exception. Or when I will refresh first user login view at that time it have same exception.
Or when I remove second user from database then I refresh first login user view at that time it will work perfectly . Now what to do? Please any one help me out of this issue. I attached screen shot of my error log please refer it.
Retrive data.java
private void makeJsonArrayRequest(final String email) {
String cancel_req_tag = "list";
JsonArrayRequest req = new JsonArrayRequest(URL_FOR_SELECT,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d("OnResponse", response.toString());
try {
// Parsing json array response
// loop through each json object
for (int i = 0; i < response.length(); i++) {
JSONObject jsonObject = response.getJSONObject(i);
ListMobileModal objMobileModal = new ListMobileModal();
if (jsonObject.getString("email").equals(email)) {
objMobileModal.email = jsonObject.getString("email");
if (!jsonObject.isNull("name")) {
objMobileModal.lname = jsonObject.getString("name"); //here we can fetch webservice field
}
if (!jsonObject.isNull("title")) {
objMobileModal.title = jsonObject.getString("title"); //here we can fetch webservice field
}
if (!jsonObject.isNull("eimage")) {
objMobileModal.eimage = jsonObject.getString("eimage");
}
if (!jsonObject.isNull("eid")) {
objMobileModal.eid = jsonObject.getString("eid");
}
if (!jsonObject.isNull("ename")) {
objMobileModal.ename = jsonObject.getString("ename");
}
if (!jsonObject.isNull("edescription")) {
objMobileModal.edescription = jsonObject.getString("edescription");
}
if (!jsonObject.isNull("evlocation")) {
objMobileModal.elocation = jsonObject.getString("elocation");
}
lstListMobile.add(i, objMobileModal);
}
}
objMobileAdapter = new ListMobileAdapter(SavedPhoneBottomActivity.this, lstListMobile);
objEmptyRecyclerViewAdapter = new EmptyRecyclerViewAdapter("No selected list!");
if (lstListMobile == null || lstListMobile.size() == 0) {
rvDisplay.setAdapter(objEmptyRecyclerViewAdapter);
rvDisplay.setVisibility(View.VISIBLE);
} else {
rvDisplay.setAdapter(objMobileAdapter);
rvDisplay.setVisibility(View.VISIBLE);
}
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(SavedPhoneBottomActivity.this,
"Error: " + e.getMessage(),
Toast.LENGTH_LONG).show();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d("VolleyError", "Error: " + error.getMessage());
Toast.makeText(SavedPhoneBottomActivity.this,
error.getMessage(), Toast.LENGTH_SHORT).show();
}
});
AppSingleton.getInstance(getApplicationContext()).addToRequestQueue(req, cancel_req_tag);
}
List exception error
try to replace lstListMobile.add(i, objMobileModal); with lstListMobile.add(objMobileModal);
when if (jsonObject.getString("email").equals(email)) condition fails 0 index is not added for that user.
you will get ArrayIndexOutOfBound error on lstListMobile.add(1, objMobileModal); if 0 index is not present
You're inserting lstListMobile.add(i, objMobileModal); maybe you can just add lstListMobile.add(objMobileModal);? Probably whats happening is that when i==0 is does not pass the test if (jsonObject.getString("email").equals(email)) {. So it does not add and the size remains 0. When i==1 it breaks when inserting.
Please check first array is not null
if (response.length > 0) {
// do something
}
else{
//empty array
}
Hi guys i have already made login and register using volley library and data gets saved successfully as shown in the snap 1 below. Now my question is how to retrieve particular or specific row data for the particular user when he/she logins?? For example if user admin gets logged in how to fetch her entire row alone
saved data in server side
<?php
$conn = mysql_connect("localhost", "root", "");
if(isset($conn))
{
mysql_select_db('your_db', $conn);
}
else
{
echo 'Sorry,can not connect to database' ;
}
$userid = isset($_GET['id']) ? mysql_real_escape_string($_GET['id']) : "";
$qur = mysql_query("select usename,other_fields from `your_tbl` where userid= $userid");
$result =array();
while($r = mysql_fetch_array($qur)){
extract($r);
$result[] = array("usename" => $usename,"other_fields" => $other_fields);
}
$json =array("data"=>$result);
mysql_close($conn);
/* Output header */
header('Content-type: application/json');
echo json_encode($json);
You will have to use server side scripting. Webservice that will fetch that particular row of data.
The script should take your input parameters and give you the out put in Json Array or Object.
You then hit this script using volley and the response you receive can then be utilized for the next step.
//call volley get method and get data in success method
public void onSuccess(string response)
{
try {
String s = new String(response);
JSONObject jsonObject = new JSONObject(s);
if (jsonObject.has("data")) {
JSONArray country =jsonObject.getJSONArray("data");
for (int i = 0; i < country.length(); i++) {
JSONObject cnt = country.getJSONObject(i);
String res=cnt.getString("username"));
//now you can use res as per your requirement
}
} catch (JSONException e) {
e.printStackTrace();
} catch (NullPointerException e) {
e.printStackTrace();
}
}