Android volley - Unexpected response code 500 - android

I am trying to edit an already registered addresses on my application, but I'm getting this error when I try to do that.
private void callServiceToEditAddress(String flatNo, String apartmentName, String landmark, String pincode) {
HashMap<String, String> hashMap = new HashMap<>();
hashMap.put("id", addressID);
hashMap.put("flat_no", flatNo);
hashMap.put("apartment_name", apartmentName);
hashMap.put("lanmark", landmark);
hashMap.put("pincode", pincode);
hashMap.put("state", selectedState);
hashMap.put("city", ID_city);
hashMap.put("location", ID_locality);
hashMap.put("country", "2");
new VolleyHelper(getActivity()).post("editAddress/", hashMap, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
String success = jsonObject.getString("success");
mAddresshasbeenAdded.newAddressHasbeenAdded();
CroutonUtil.showCroutonMessage(getActivity(), success, CroutonUtil.CROUTON_STYLE_CONFIRM);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
});
}
My Log cat:
E/Volley: [365] BasicNetwork.performRequest: Unexpected response code 500 for link I'm using

i solved this by changing the permission for included files in my server side

I was actually able to solve my problem eventually. What happened is that this web service that I am using "editAddress" also needed another field that I was not providing inside hashMap. I made the changes and it worked fine.

I just change my url from
http
to
https
Then it works fine for me.

The parameters put into Hashmap and get in server side was misspelled, When I have corrected the words of both side with same spelling , The problem was gone, Alhamdulillah.

Related

I cannot identify what is causing this unexpected upload error on my app

I am relatively new to android development and I have been squeezing my brain juice for hours on probably a very simple error. Look, the app's been working fine yesterday and after I made some changes on some XML files and ran the app on my emulator, I experience this error:
2019-09-10 14:13:19.533 6388-
6516/ E/Volley: [301]
BasicNetwork.performRequest: Unexpected response code 406 for
http://applybpojobs.com/widevalueappfiles/server/api/addvehicle.php
2019-09-10 14:13:21.573 1633-1656/system_process E/memtrack: Couldn't load
memtrack module
I have already tried numerous solutions on the web and it seems not to fix my problem. This is my code:
StringRequest stringRequest = new StringRequest(Request.Method.POST,
URL_ADD_VEHICLE,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.i(TAG, response.toString());
try {
JSONObject jsonObject = new JSONObject(response);
String Success = jsonObject.getString("success");
if (Success.equals("1")){
hideLoader();
Toast.makeText(Addvehicle.this,"Vehicle Added
Successfully",Toast.LENGTH_SHORT).show();
}else if (Success.equals("0")){
hideLoader();
Toast.makeText(Addvehicle.this,"Vehicle
Already Exist",Toast.LENGTH_SHORT).show();
}
}catch (JSONException e){
e.printStackTrace();
hideLoader();
Toast.makeText(Addvehicle.this,"Vehicle Added
Error"+e.toString(),Toast.LENGTH_SHORT).show();
}
}
},
new Response.ErrorListener(){
#Override
public void onErrorResponse(VolleyError error){
Toast.makeText(Addvehicle.this,"Vehicle Added
Error"+error.toString(),Toast.LENGTH_SHORT).show();
hideLoader();
}
})
I am receiving a blank response from this URL and I need guidance on how to fix this:
http://*********.php
For whatever reasons, this page on my app stopped working because of this error. Any help would be appreciated. Again, I'm basically new in android development so please understand that a simple error like this bleeds my nose.
Here are my server php codes:
<?php
require '../core/connect.php';
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$plate_number=$_POST['plate_number'];
$vin=$_POST['vin'];
$car_make=$_POST['car_make'];
$car_model=$_POST['car_model'];
$car_year=$_POST['car_year'];
$displacement=$_POST['displacement'];
$fuel_type=$_POST['fuel_type'];
$transmission=$_POST['transmission'];
$mileage=$_POST['mileage'];
$owner_name=$_POST['owner_name'];
$address=$_POST['address'];
$phone_number=$_POST['phone_number'];
$email_adress=$_POST['email_adress'];
$facebook=$_POST['facebook'];
$adddate = date("d/m/Y");
$photo = $_POST['photo'];
$id=uniqid();
$path = "vehicle_upload/$id.jpeg";
$finalpath = "*********.$path;
$sql1=mysqli_query($connect,"SELECT * FROM _addvehicle WHERE
PlateNumber='$plate_number'");
if (mysqli_num_rows($sql1) > 0) {
$result['success'] = "0";
$result['message'] = "error";
echo json_encode($result);
}else{
$sql = mysqli_query($connect, "INSERT IGNORE INTO
_addvehicle(PlateNumber, Vin, Make, Model, Year, Displacement, FuelType,
Transmission, Mileage, OwnerorCompany, HomeorCompanyAddress, ContactNumber,
EmailAddress, FacebookID, AddDate, vehicleImage)VALUES('$plate_number','$vin','$car_make','$car_model','$car_year','$displacement','$fuel_type','$transmission','$mileage','$owner_name','$address','$phone_number','$email_adress','$facebook','$adddate','$finalpath')");
if ($sql) {
if (file_put_contents($path, base64_decode($photo))) {
$result['success'] = "1";
$result['message'] = "success";
echo json_encode($result);
//mysqli_close($connect);
}
}
}
}
?>
In POST request you need to send parameters like an empty Hashmap i.e
{"":""} or you need to try https instead of http.

Retreiving data from MySQL database using Android Volley library is too slow

I tried to retrieve a list of form data stored in database in my Android application. Each row of database contains some personal information of a person in string format and also an image of that person. I have stored the images in database in MEDIUMBLOB format.
Whenever I try to retrieve data from my server using JSONObjectrequest of Volley Library in my Android app, the response is usually very slow. Sometimes it takes more than 1 minute to view only 10 to 12 rows retrieved from the database.
This is my logcat:
D/Volley: [337] BasicNetwork.logSlowRequests: HTTP response for request=<[ ] http://helpclick.ahsanaasim.me/v1/tasksall/johny 0xa3e020c1 NORMAL 1> [lifetime=14740],
I tried to search for a perfect solution but I couldn't find anything satisfactory. Here is my Java code:
mRequestStartTime = System.currentTimeMillis();
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET,
showUrl2, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
long totalRequestTime = System.currentTimeMillis() - mRequestStartTime;
System.out.println(totalRequestTime);
System.out.println(response.toString());
try { c1++;
System.out.println(c1);
JSONArray incidents = response.getJSONArray("incidents");
for (int i = 0; i < incidents.length(); i++) {
e=0;
JSONObject incident = incidents.getJSONObject(i);
c1++;
id= incident.getString("id");
age = incident.getString("age");
gender = incident.getString("gender");
location = incident.getString("location");
//det= incident.getString("det");
String image=new String();
image = incident.getString("bigimage");
if(image.length()!=0) {
myBitmap = ConvertToImage(image);
Bitmap bitmap= Bitmap.createScaledBitmap(myBitmap,500,500,true);
imgs.add(bitmap);
ages.add(age);
genders.add(gender);
locations.add(location);
ids.add(id);
}
}
if(c1>0) {
System.out.println(ages.size());
Intent intent1 = new Intent(search_buttons_page.this, All_Incidents.class);
startActivity(intent1);
}
}
catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
System.out.append(error.getMessage());
}
});
jsonObjectRequest.setRetryPolicy(new DefaultRetryPolicy(
20000,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
requestQueue.add(jsonObjectRequest);
It would be really helpful if someone can tell me the reason of this slow performance and how to solve it by making minimum modifications in my source code.
Don't keep the images in the db. Keep them in files, and keep the URL of the files in the db. Download the images separately as needed via URL. Then you aren't killing your database access times with what should be file IO.

Android Volley Error Null using Stored Procedures in EF

Im consuming a RESTful Api builded with ASP EF. I have a procedure in my DB, this is it:
ALTER PROCEDURE [Ventas].[CtasxCobxVendedor]
#AGE CHAR(1),
#VENDEDOR VARCHAR(10)
AS
BEGIN
SET NOCOUNT ON
SELECT
V.CLIENTE Codigo,
C.RazonSocialAnalitico Cliente,
C.DireccionAnalitico Direccion,
C.TelefonoAnalitico Telefono,
V.Gestion,
V.IdDos,
V.DCTO,
V.Factura,
V.Fecha,
V.Vencimiento,
SUM(B.DBB) Monto,
SUM(B.HBB) Pagos,
SUM(B.DBB-B.HBB) Saldo
FROM VENTAS.VMAESTRO V
JOIN VENTAS.CTASXCOBRAR B ON
(V.GESTION=B.GESTIONF
AND V.AGE =B.AGE
AND V.TIPO = B.TIPOF
AND V.IDDOS = B.IDDOSF
AND V.DCTO = B.DCTOF)
JOIN VENTAS.vwCLIENTES C ON
(V.CLIENTE = C.IdAnalitico)
WHERE
-- V.AGE =#AGE
V.STA = 'A'
AND V.VENDEDOR = #VENDEDOR
GROUP BY V.CLIENTE,C.RazonSocialAnalitico,C.DireccionAnalitico,C.TELEFONOAnalitico,V.Gestion,V.IdDos,V.DCTO,V.Factura,V.FECHA,V.VENCIMIENTO
HAVING SUM(B.DBB-B.HBB) > 0.001
ORDER BY C.RazonSocialAnalitico, V.FECHA, V.DCTO;
RETURN 0;
END
I created the import function, and the Complex Type on VS. So this is what I got:
public virtual ObjectResult<CtasxCobxVendedor_Result> CtasxCobrarV(string aGE, string vENDEDOR)
{
var aGEParameter = aGE != null ?
new ObjectParameter("AGE", aGE) :
new ObjectParameter("AGE", typeof(string));
var vENDEDORParameter = vENDEDOR != null ?
new ObjectParameter("VENDEDOR", vENDEDOR) :
new ObjectParameter("VENDEDOR", typeof(string));
return ((IObjectContextAdapter)this).ObjectContext.ExecuteFunction<CtasxCobxVendedor_Result>("CtasxCobrarV", aGEParameter, vENDEDORParameter);
}
Then I tried to call this SP in one of my controllers, in this case is my Personal controller, like this:
public IQueryable<CtasxCobxVendedor_Result1> GetCuenta(string id)
{
using (NemesisEntities ctx = new NemesisEntities()) {
return db.CtasxCobxVendedor("A", id).AsQueryable();
}
}
When I call this method on the browser (like this "localhost:45896/api/personals/3329672" where "3329672" is the Personal Id) works just fine, cause it gives me this result:
[{"Codigo":"1018389023","Cliente":"BAREMSA","Direccion":"Av. Cicunvalación - ITOS S/N","Telefono":"","Gestion":"15","IdDos":503,"DCTO":15001980,"Factura":1097,"Fecha":"2015-10-21T00:00:00","Vencimiento":"2015-11-20T00:00:00","Monto":1380.0000,"Pagos":0.0000,"Saldo":1380.0000},{"Codigo":"1018389023","Cliente":"BAREMSA","Direccion":"Av. Cicunvalación - ITOS S/N","Telefono":"","Gestion":"15","IdDos":509,"DCTO":15002329,"Factura":128,"Fecha":"2015-12-09T00:00:00","Vencimiento":"2016-01-08T00:00:00","Monto":1980.0000,"Pagos":0.0000,"Saldo":1980.0000},{"Codigo":"3095060012","Cliente":"BERTHA CONDORI ORURO","Direccion":"","Telefono":" 25288136","Gestion":"15","IdDos":509,"DCTO":15002349,"Factura":148,"Fecha":"2015-12-11T00:00:00","Vencimiento":"2016-01-10T00:00:00","Monto":1450.0000,"Pagos":0.0000,"Saldo":1450.0000},{"Codigo":"1015777022","Cliente":"CADEXNOR","Direccion":"","Telefono":"","Gestion":"16","IdDos":509,"DCTO":16000384,"Factura":661,"Fecha":"2016-03-09T00:00:00","Vencimiento":"2016-04-08T00:00:00","Monto":1440.0000,"Pagos":0.0000,"Saldo":1440.0000},{"Codigo":"1006965023","Cliente":"COMIBOL","Direccion":"Plaza 6 de Agosto","Telefono":" 68224768","Gestion":"14","IdDos":10,"DCTO":14000142,"Factura":314,"Fecha":"2012-08-03T00:00:00","Vencimiento":"2012-08-08T00:00:00","Monto":2770.0000,"Pagos":0.0000,"Saldo":2770.0000},{"Codigo":"1006965023","Cliente":"COMIBOL","Direccion":"Plaza 6 de Agosto","Telefono":" 68224768","Gestion":"14","IdDos":10,"DCTO":14000143,"Factura":776,"Fecha":"2013-10-03T00:00:00","Vencimiento":"2013-11-02T00:00:00","Monto":2900.0000,"Pagos":0.0000,"Saldo":2900.0000}]
Then when I try to connect it to my Android app using Volley framework:
JsonArrayRequest re= new JsonArrayRequest(Request.Method.GET, newURL, (String)null, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Toast.makeText(Cobrar.this,response.toString(),Toast.LENGTH_LONG).show();
procesarRespuesta(response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(Cobrar.this,"NOTHING",Toast.LENGTH_LONG).show();
Log.d(TAG, "Error Volley: " + error.getMessage());
}
});
Where "newURL" is like the one above. Just Give me "Error Volley:null" without any other explanation.
I really dont know what to fix, cause when I use simple GET calls for example calling this: "http://localhost:45896/api/clientes", it works fine, the problem is when I want to use the SP.
Any idea of what am I doind wrong? Since I dont get any information of where my problem actually is, Idk where to start
Please check this question posted here.
I have faced same issue.
Why this happens?
In volley, When timeout/socket timeout occurs it throws error. but
error object is null. You can override two methods in your Request
class to check if its timeout.
Solution :
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, "url", "request", new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}) {
#Override
protected void deliverResponse(JSONObject response) {
super.deliverResponse(response);
}
#Override
public void deliverError(VolleyError error) {
super.deliverError(error);
}
};
You can get error on deliverError method in above code.
TimeOut occurs when server takes more time to respond to app then defined in RetryPolicy.
request.setRetryPolicy(new DefaultRetryPolicy(DefaultRetryPolicy.DEFAULT_TIMEOUT_MS * 48,
0, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
default timeout is 2500 seconds for Volley.
You can avoid this issue using following improvements :
You need to improve your server performance
You can set retryCount to 1 if it suits your app requirements.
Thanks.

How to post data from android apps using android studio to the server

This Android app is using Android Studio. The function is to scan and display data from the beacon/eddystone. The app already functions and after the scanning stops, the data saves to the local file. But my problem is when I have to transfer the scanning data to the server, I have to ent it to the back-end server. But I really didn't know what is the best way as I'm a beginner.
Here is the code that the data will transfer to the local data:
private void stopScanning(Button scanButton) {
try {
beaconManager.stopRangingBeaconsInRegion(region);
} catch (RemoteException e) {
// TODO - OK, what now then?
}
String scanData = logString.toString();
if (scanData.length() > 0)
{
// Write file
fileHelper.createFile(scanData);
// Display file created message.
Toast.makeText(getBaseContext(),
"File saved to:" + getFilesDir().getAbsolutePath(),
Toast.LENGTH_SHORT).show();
scanButton.setText(MODE_STOPPED);
} else {
// We didn't get any data, so there's no point writing an empty file.
Toast.makeText(getBaseContext(),
"No data captured during scan, output file will not be created.",
Toast.LENGTH_SHORT).show();
scanButton.setText(MODE_STOPPED);
}
}
To send Data to a server there are many ways, BUT I PREFER you use Volley Library because it's faster and easier
You can use volley for fetching and sending data ,For example:
//Request serever for JsonObject
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
//Your code to proceed with fetched data
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}){
//This is the method used to put params into the body, this what you will have to use for sending post data
#Override
public Map<String, String> getParams() throws AuthFailureError {
HashMap<String, String> params = new HashMap<String, String>();
params.put("name","jois");
return params;
}
};
Volley.newRequestQueue(getApplicationContext()).add(request);
compile 'com.mcxiaoke.volley:library:1.0.19' This is the dependice you will have to add in build.gradle file to use volley library
I hope this was helpful, ThankYou

How to check a key is exist or not in gson parsing android

I am parsing a json response using gson. However in my case I am getting different response for success and failure.
So I am unable to parse the data, because in my utility class I have created some serilized field those are not present for both the scenario.
e.g. when registration is success I am using user key to get the user details while when registration is failed I am using error field to get error message.
I have knowledge about json parsing and in that we we do parsing step by step like if success is true then parse for user details otherwise parse for error. Again in json parsing we have method has which check a key is exist or not. And I am looking for something similar in gson also.
Below is my code snippet please check it
Get Register Data from Server
private void getRegisterData(String email, String password, String full_name,String phone) {
WdApplication= (WAdvantageApplication) this.getApplication();
RequestQueue queue = application.getRequestQueue();
HashMap<String, String> headerMap = new HashMap<String, String>();
headerMap.put(RequestHeaders.CONTENT_TYPE, RequestHeaders.CONTENT_TYPE_JSON);
HashMap<String, String> dataMap = new HashMap<String, String>();
dataMap.put("email", email);
dataMap.put("password", password);
dataMap.put("phone", phone);
dataMap.put("fullname", full_name);
GsonRequest<RegisterDetails> request = new GsonRequest<RegisterDetails>(GsonRequest.Method.POST, URLConstant.REGISTER_URL, RegisterDetails.class, headerMap, dataMap, successListener, failureListener);
queue.add(request);
}
private Response.Listener successListener = new Response.Listener<RegisterDetails>() {
#Override
public void onResponse(RegisterDetails registerDetails) {
Log.e("success", "Success");
finish();
}
};
private Response.ErrorListener failureListener = new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
Log.e("fail", "Registration failed");
}
};
my RegisterDetails class
#SerializedName("user")
private UserDetails userDetails;
#SerializedName("success")
private String success;
#SerializedName("error")
Information info;
So for success is true I want only user part and for success is false I want error part.
If I am doing anything wrong please rectify me , Thanks
I am not sure what you are asking about, but in gson if you are getting success key and user key (if it's success) and error (if something goes wrong)in single response, you can code something like this.
if(registerDetails.getSuccess().equalsIgnoreCase("true"))
{
// use registerDetails.getUserDetails();
}
else
{
// use registerDetails.getInfo();
}
Not sure about GSON but if you use Jackson, you can provide an annotation like this
#JsonIgnoreProperties(ignoreUnknown = true)
and then you can use the same model class for success or failure, if it is a success, the userDetails will be set, if it is a failure, the error part will be set.

Categories

Resources