Related
I'm using MVVM Design Pattern to build this app, but when I load data user using the searching method I get issue like this:
2020-05-04 11:34:55.839 11187-11187/com.planetmars23.im.movie_catalogue D/imam_log: null
2020-05-04 11:34:55.839 11187-11187/com.planetmars23.im.movie_catalogue I/imam_log: setSearchUserGithub - Response success
public void setSearchUserGithub(String accessToken, String user) {
Call<UserDataObject> githubSearchObjectCall = service.userSearchResult(user);
githubSearchObjectCall.enqueue(new Callback<UserDataObject>() {
#Override
public void onResponse(Call<UserDataObject> call, Response<UserDataObject> response) {
assert response.body() != null;
listGithub.setValue(response.body().getResults());
Log.d(Base.LOG, String.valueOf(response.body().getResults()));
Log.i(Base.LOG, "setSearchUserGithub - Response success");
}
#Override
public void onFailure(Call<UserDataObject> call, Throwable t) {
Log.w(Base.LOG, "setSearchUserGithub - Response failed :" + t.getMessage());
}
});
}
I'm using this for GitHub service
#GET("/search/users?")
#Headers("Authorization:"+ Base.KEY)
Call<UserDataObject> userSearchResult(#Query("q") String username);
I have a problem in my android studio project. when i try to do some retrieve API using retrofit from my web services, i had some errors that said
"Cannot find local variable call"
here is my code :
private void RegisUserTampung(String token)
{
Call<ResponseRegister> call = client.regisAccount("bearer " +token, "N", new Gson().toJson(regisUser));
call.enqueue(new Callback<ResponseRegister>() {
#Override
public void onResponse(Call<ResponseRegister> call, Response<ResponseRegister> response) {
ResponseRegister responseRegister = response.body();
if (responseRegister != null) {
Toast.makeText(VerifActivity.this, responseRegister.getMessage(), Toast.LENGTH_SHORT).show();
}
}
#Override
public void onFailure(Call<ResponseRegister> call, Throwable t) {
Toast.makeText(VerifActivity.this, "Failed POST Token to server ", Toast.LENGTH_SHORT).show();
}
});
and this is error i had when i went into debug mode :
Cannot find local variable 'call'
any idea for this issue?
You Now Have 2 variable With Same Name
Call<ResponseRegister> **call** = client.regisAccount("bearer " +token, "N", new Gson().toJson(regisUser));
And
public void onResponse(Call<ResponseRegister> **call**, Response<ResponseRegister>
try to change Variable Name
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.
I know a similar question has been asked a few times now, but I can't seem to find a solution for a simple problem: PATCH verb.
So I ask anyone who as solved the PATCH issue in Android either by using OkHttp, Volley or Retrofit ( or if you used a different method or library, please share).
I have spent 3 days digging around and I can't find any solutions to this problem. All I am trying to do is to do a partial update to a table via RESTful API which is built and ran in .NET environment.
I am currently using Volley, but every time I run the app, I get the exception error that says something along the lines of PATCH is not an allowed...? and it then gives a array of other verbs that can be used such as "POST, PUT, GET...". So, not very helpful at all.
I have tried using OkHttp like this:
JSONObject infoRequestBody = new JSONObject();
try {
infoRequestBody.put("Salutation", "MRrr.");
infoRequestBody.put("FirstName", "Work Now!!");
infoRequestBody.put("LastName", "Test from my mobile again!! Okhttp");
infoRequestBody.put("MiddleName", "From the Mobile");
infoRequestBody.put("NickName", null);
infoRequestBody.put("BirthDate", "1978-11-23T00:00:00.000Z");
infoRequestBody.put("CompanyName", null);
// infoRequestBody.put("RegDate", "2015-01-18T23:39:13.873Z");
infoRequestBody.put("Gender", "Male");
infoRequestBody.put("IsPregnant", null);
infoRequestBody.put("IsNursing", null);
infoRequestBody.put("WorkPhone", null);
infoRequestBody.put("WorkPhoneExt", null);
infoRequestBody.put("PhoneNumber", null);
infoRequestBody.put("Address", "My android app working!!");
infoRequestBody.put("Address2", null);
infoRequestBody.put("City", null);
infoRequestBody.put("State", "CA");
infoRequestBody.put("ZipCode", null);
infoRequestBody.put("EmailAddress", "email#me.com");
infoRequestBody.put("Occupation", null);
infoRequestBody.put("CountryofResidence", "United States");
infoRequestBody.put("CountryCode", "US");
infoRequestBody.put("Ethnicity", "Asian");
infoRequestBody.put("ModifiedDate", "2015-01-18T23:39:13.873Z");
infoRequestBody.put("ModifiedBy", null);
infoRequestBody.put("AcceptedTerms", true);
infoRequestBody.put("AcceptedPrivacyPolicyCheckbox", false);
infoRequestBody.put("AcceptedUnder18ConsentCheckbox", false);
} catch (JSONException e1) {
e1.printStackTrace();
}
RequestBody body = com.squareup.okhttp.RequestBody.create(JSON, infoRequestBody.toString());
com.squareup.okhttp.Request.Builder request = new com.squareup.okhttp.Request.Builder()
.url("APIUrls.PATIENT_INFO_URL")
.addHeader("Content-Type", "application/json")
.addHeader("Accept", "application/json")
.addHeader("X-ZUMO-APPLICATION", APIUrls.ZUMO_KEY)
.patch(body);
client.newCall(request).enqueue(new Callback() {
#Override
public void onFailure(com.squareup.okhttp.Request request, IOException e) {
}
#Override
public void onResponse(com.squareup.okhttp.Response response) throws IOException {
if (!response.isSuccessful()) throw new IOException("Unexpected code" + response);
Headers responseHeaders = response.headers();
for (int i = 0; i < responseHeaders.size(); i++) {
System.out.println(responseHeaders.name(i) + ": " + responseHeaders.value(i));
}
System.out.println(response.body().string());
}
});
but client.newCall(request).enque(new Callback()... gives me an error saying that the request can not be applied to Request.Builder.
I am new to OkHttp, by the way.
Anyways, I have been struggling to get PATCH to work for far too long. Maybe I am shooting in the dark, but if anyone out there has any suggestions, thoughts on how to get 'PATCH` to work, I'd be forever grateful to you.
Thanks for your help.
As GreyBeardedGeek says, you can use Retrofit + OkHttp to implement this.
RestAdapter restAdapter = new RestAdapter.Builder()
.setClient(new OkClient())
.setEndpoint(ENDPOINT)
.build();
MyPatchService patchService = restAdapter.create(MyPatchService.class);
UserUpdate updatedUser = new UserUpdate();
updatedUser.Salutation = "Mr";
updatedUser.FirstName = "Adam";
patchService.update(updatedUser);
And MyPatchService looks something like this:
public interface MyPatchService {
#PATCH("/some/update/endpoint")
User update(UserUpdate updatedObject);
}
Your UserUpdate class could look like this:
public class UserUpdate {
public String Salutation;
public String FirstName;
public String LastName;
}
If you do this, the JSON that will be sent will look like this (note that LastName is not serialized since it was never set - this is configurable through supplying a custom Gson instance to Retrofit):
{
"Salutation": "Mr",
"FirstName": "Adam"
}
The request/response objects are plain Java representations of the objects you send/receive over the network. Being a patch request, you can make your member vars Integer, Boolean, etc and they won't get serialized if not set (i.e. if they're null).
I haven't tried this, but apparently, if you use Retrofit with the OkHTTP's OKClient, then Retrofit supports an #Patch annotation.
See http://square.github.io/retrofit/javadoc/retrofit/http/PATCH.html and Retrofit & HTTP Patch
Alright! Thanks #Adam and everyone who contributed to get me in the right direction. Really appreciate it. So, here's what I ended up doing (I barely customized what #Adam posted, which of course is the correct answer!):
Firstly,
I set up my UserUpdate class as follows:
public class UserUpdate {
public String Salutation;
public String FirstName;
public String LastName;
public String MiddleName;
public String NickName;
//Setters and Getters...
public String getSalutation() {
return Salutation;
}
public void setSalutation(String salutation) {
Salutation = salutation;
}
public String getFirstName() {
return FirstName;
}
public void setFirstName(String firstName) {
FirstName = firstName;
}
public String getLastName() {
return LastName;
}
public void setLastName(String lastName) {
LastName = lastName;
}
public String getMiddleName() {
return MiddleName;
}
public void setMiddleName(String middleName) {
MiddleName = middleName;
}
public String getNickName() {
return NickName;
}
public void setNickName(String nickName) {
NickName = nickName;
}
}
and then I set up the interface class called PatientInfoAPI:
public interface PatientInfoAPI{
#PATCH("/tables/PatientInformation/{id}")
public void update(#Body UserUpdate updatedDAta, #Path("id") String id,Callback<UserUpdate> response);
}
Notice I'm passing the table id to be "PATCH'd", and most importantly I have the #Body annotation which allows me to pass the data to the update without getting an error (I tried without it and was getting an error)
And finally inside my main Activity:
RestAdapter restAdapter = new RestAdapter.Builder()
.setClient(new OkClient()) //very important!!!
.setEndpoint(ENDPOINT)//base url
.setRequestInterceptor(new RequestInterceptor() {//You may not need to pass headers, but I do, so this is how it's done.
#Override
public void intercept(RequestFacade request) {
request.addHeader("Content-Type", "application/json");
request.addHeader("Accept", "application/json");
request.addHeader("X-ZUMO-APPLICATION", APIUrls.ZUMO_KEY);
}
})
.build();
PatientInfoAPI patchService = restAdapter.create(PatientInfoAPI.class);
UserUpdate updatedUser = new UserUpdate();
updatedUser.setSalutation("Sr.");
updatedUser.setFirstName("YesSirtItsWorking");
updatedUser.setLastName("Bays");
updatedUser.setMiddleName("ComeOn Now man!");
updatedUser.setNickName("");
//Passing the tableId along with the data to update
patchService.update(updatedUser, APIUrls.TABLE_ID, new retrofit.Callback<UserUpdate>() {
#Override
public void success(UserUpdate userUpdates, retrofit.client.Response response) {
Log.v("All is good", "Nickname:" + userUpdates.getNickName().toString() + " Email: " + userUpdates.getEmailAddress().toString());
}
#Override
public void failure(RetrofitError error) {
Log.v("All is good", error.getLocalizedMessage().toString());
}
});
I know that maybe some of the steps are not very sophisticated, but for those who are starting with Retrofit and OkHttp, and most importantly have been struggling to get PATCH to work with Android, this is the solution. Again, props to #Adam for pretty much guide me through the process. #Adam was the one who really answered this question - I'm just putting it all together for those who may need a to see the full picture. Thanks, #Adam!!! You are a rockstar!
I am trying to develop a Facebook application for Android. I am unable to integrate the "Add Comment" feature to photos in Facebook Albums. Using the Graph API, I can show the previously made comments on a photo. However, I just can't add new comments to a photo.
Can somebody provide me some helpful advice?
here is simple example on doing that..
// post comment to single photo
Bundle parameters = new Bundle();
String target = "";
target = "<PHOTO_ID>/comments";
parameters.putString("message", "post Comment testing");
mAsyncRunner.request(target, parameters, "POST", new FacebookRequestListener(target+" (post comment)"));
and here is a simple example for the listener (you can get this from examples of facebook-android-sdk too)
public class FacebookRequestListener extends BaseRequestListener {
String caller = "default";
public FacebookRequestListener() {
}
public FacebookRequestListener(String caller) {
this.caller = caller;
}
public void onComplete(final String response) {
try {
Log.d(TAG, "FacebookRequestListener|"+caller+":" + response);
} catch (Exception e) {
Log.w(TAG, "Error:"+e.getMessage());
}
}
}