Android Volley Error Null using Stored Procedures in EF - android

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.

Related

REST request using Volley sends back a result that is different from Postman

I am using the GenericRequest (an extension of the built-in jsonrequest) to make a REST call to a server that takes in a json object and returns a string, which is "0" if the json object already exists and a nonzero string otherwise.
However, with the following code, I always get a "0" back no matter what I sent.
JSONObject userobj = new JSONObject();
try {
userobj.put("email",email);
userobj.put("password",password);
userobj.put("username",name);
} catch (JSONException e) {
e.printStackTrace();
}
Log.d(TAG, userobj.toString());
GenericRequest jsonObjReq = new GenericRequest(Request.Method.POST, REGISTER_URL, String.class, userobj,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
// Handle access token.
Log.d(TAG, "Register received: " + response);
long token = Long.parseLong(response);
if(token == 0) {
Log.d(TAG, "Received 0!");
Toast.makeText(MainActivity.this, R.string.registerfail_toast, Toast.LENGTH_LONG).show();
} else {
Log.d(TAG, "Register success!");
Toast.makeText(MainActivity.this, R.string.Welcome, Toast.LENGTH_LONG).show();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d(TAG, error.toString());
Toast.makeText(MainActivity.this, error.toString(), Toast.LENGTH_LONG).show();
}
}) {
#Override
public String getBodyContentType() {
return "application/json";
}
};
jsonObjReq.setRetryPolicy(new DefaultRetryPolicy(0, -1, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
helper.add(jsonObjReq);
When testing in Postman, given the input like:
{
"email": "dlee23122",
"password": "1234",
"username": "dlee23122"
},
it gives back a nonzero string. (Screenshot as follows.) But when given a slightly different input using the Volley, it keeps giving back a "0". What could be the reason?
Thanks in advance!
Even i faced the same problem, volley default connection timeout is set to 5 sec and it was posting two times, so check for time in postman on right side, if it is closer to 5000ms or greater this might be the problem.
My problem got solved by adding the following to Volley request:
DefaultRetryPolicy retryPolicy = new DefaultRetryPolicy(0, -1, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
jsonObjectRequest.setRetryPolicy(retryPolicy);
if you want set custom retry policy look at this post Change Volley timeout duration

Custom API in Azure APP Serivce examples searched for Android Client

I need a working example for a custom API for Microsoft Azure App Service.
I could not get any useful or working information/examples for that, or they just show each time different approaches which are outdated?!?!
For now I have a working table controller which gets information from database and returns it back to my Android client. Now I need to define a custom API Controller to get a string back. In the examples they are all sending an object to the service in order to get an object back. I do not want to send anything to the API, just retrieve some information back from a GET Request.
Regards
// EDIT - Added / edited client / server code to Post a String.
You can use the following code to do a GET request on the auto generated API controller Visual Studio creates (ValuesController).
private void getStringFromAzure() throws MalformedURLException {
// Create the MobileService Client object and set your backend URL
String yourURL = "https://yourApp.azurewebsites.net/";
MobileServiceClient mClient = new MobileServiceClient(yourURL, this);
// Your query pointing to yourURL/api/values
ListenableFuture<JsonElement> query = mClient.invokeApi("values", null, GetMethod, null);
// Callback method
Futures.addCallback(query, new FutureCallback<JsonElement>() {
#Override
public void onSuccess(JsonElement jsonElement) {
// You are expecting a String you can just output the result.
final String result = jsonElement.toString();
// Since you are on a async task, you need to show the result on the UI thread
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(mContext, result, Toast.LENGTH_LONG).show();
}
});
}
#Override
public void onFailure(Throwable throwable) {
Log.d(TAG, "onFailure: " + throwable.getMessage());
}
});
}
public void sendString(final String someString) throws MalformedURLException {
// Your query pointing to /api/values/{String}
ListenableFuture<JsonElement> query = mClient.invokeApi("values/" + someString, null, PostMethod, null);
// Callback method
Futures.addCallback(query, new FutureCallback<JsonElement>() {
#Override
public void onSuccess(JsonElement jsonElement) {
// You are expecting a String you can just output the result.
final String result = jsonElement.toString();
}
#Override
public void onFailure(Throwable throwable) { }
});
}
The backend API: (ValuesController)
{
// Use the MobileAppController attribute for each ApiController you want to use
// from your mobile clients
[MobileAppController]
public class ValuesController : ApiController
{
// GET api/values
public string Get()
{
return "Hello World!";
}
// POST api/values/inputString
public string Post(string inputString)
{
return inputString;
}
}
}
You can also send parameters along in the following way:
List<Pair<String, String>> parameters = new ArrayList<>();
parameters.add(new Pair<>("name", "John"));
parameters.add(new Pair<>("password", "fourwordsalluppercase"));
ListenableFuture<JsonElement> query = client.invokeApi("yourAPI", PostMethod, parameters);
Or as json in the body:
JsonObject body = new JsonObject();
body.addProperty("currentPassword", currentPassword);
body.addProperty("password", password);
body.addProperty("confirmPassword", confirmPassword);
ListenableFuture<JsonElement> query = mClient.invokeApi("yourAPI", body, PostMethod, null);
Based on my understanding, I think there are two parts in your question which include as below. And I think you can separately refer to two sections to get the answers and write your own example.
How to define a custom API on Azure Mobile App to retrieve data from database? Please refer to the section Custom APIs to know how to do with Azure Mobile App backend.
How to call a custom API from Android App? Please refer to the section How to: Call a custom API to know how to do with Android SDK.

Android volley - Unexpected response code 500

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.

NodeMCU server bad response, when sending GET request from Android app

I've made little server based on NodeMCU. All works good, when I'm conneting from browser, but problem starts, when I'm trying to connect from Android app uisng OkHttp or Volley, I'm receiving exceptions.
java.io.IOException: unexpected end of stream on Connection using OkHttp,
EOFException using Volley.
Problem is very similar for this
EOFException after server responds, but answer didn't found.
ESP server code
srv:listen(80, function(conn)
conn:on("receive", function(conn,payload)
print(payload)
conn:send("<h1> Hello, NodeMCU.</h1>")
end)
conn:on("sent", function(conn) conn:close() end)
end)
Android code
final RequestQueue queue = Volley.newRequestQueue(this);
final String url = "http://10.42.0.17:80";
final StringRequest request = new StringRequest(Request.Method.GET, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
mTemperatureTextView.setText(response.substring(0, 20));
System.out.println(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
System.out.println("Error + " + error.toString());
mTemperatureTextView.setText("That didn't work!");
}
}
);
mUpdateButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
queue.add(request);
}
});
What you're sending back is not HTTP. It's nothing but a protocol-agnostic HTML fragment. Furthermore, there's a memory leak lingering.
Try this instead:
srv:listen(80, function(conn)
conn:on("receive", function(sck,payload)
print(payload)
sck:send("HTTP/1.0 200 OK\r\nServer: NodeMCU on ESP8266\r\nContent-Type: text/html\r\n\r\n<h1> Hello, NodeMCU.</h1>")
end)
conn:on("sent", function(sck) sck:close() end)
end)
you need to send back some HTTP headers, HTTP/1.0 200 OK and the newlines are mandatory
each function needs to use it's own copy of the passed socket instance, see how I renamed conn to sck in the two callback functions, see https://stackoverflow.com/a/37379426/131929 for details
For a more complete send example look at net.socket:send() in the docs. That becomes relevant once you start sending more than just a couple of bytes.

How to stream real time data using Retrofit

I want to observer changes from server in my android app.
So I'm using this interface for open stream with server.
public interface Service {
#GET("/n/{id}/streaming")
void streamThreads(#Path("name_space_id") String Id, #QueryMap Map<String, String> options,#Query("exclude_types") String type, Callback<Object> callback);
}
and this is my method where I can get response in my activity
server.streamThreads(accountInfo.getId(), map, "thread", new Callback<Object>() {
#Override
public void success(Object o, Response response) {
String json = (String) o;
Log.i(TAG,json);
}
#Override
public void failure(RetrofitError error) {
Response r = error.getResponse();
if (r != null)
Log.e(TAG, "error: " + r.getReason());
}
});
So I tested method in web browser and life stream works.
But response comes in my mobile app every 30 minutes. I'm using one activity and call method onCreate().
Thanks
Retrofit provides an #Streaming annotation.
The unread byteStream can then be obtained from the raw OkHttp ResponseBody.

Categories

Resources