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
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);
want to start development with AWS IOT using Android app
I am seeking for example for IOT in android. need to start basic configuration on AWS console and android app. i already tested temperature demo but didn't get any clue from that! need a basic steps on shadow, policy , role. how to configure them step by step and use of cognito.
below getshadow() method is called onCreate , need to update value on real time basis not ony onCreate.
public void getShadows() {
GetShadowTask getControlShadowTask = new GetShadowTask("TemperatureControl");
getControlShadowTask.execute();
}
private class GetShadowTask extends AsyncTask<Void, Void, AsyncTaskResult<String>> {
private final String thingName;
public GetShadowTask(String name) {
thingName = name;
}
#Override
protected AsyncTaskResult<String> doInBackground(Void... voids) {
try {
GetThingShadowRequest getThingShadowRequest = new GetThingShadowRequest()
.withThingName(thingName);
GetThingShadowResult result = iotDataClient.getThingShadow(getThingShadowRequest);
// Toast.makeText(getApplication(),result.getPayload().remaining(),Toast.LENGTH_LONG).show();
byte[] bytes = new byte[result.getPayload().remaining()];
result.getPayload().get(bytes);
String resultString = new String(bytes);
return new AsyncTaskResult<String>(resultString);
} catch (Exception e) {
Log.e("E", "getShadowTask", e);
return new AsyncTaskResult<String>(e);
}
}
#Override
protected void onPostExecute(AsyncTaskResult<String> result) {
if (result.getError() == null) {
JsonParser parser=new JsonParser();
JsonObject jsonObject= (JsonObject) parser.parse(result.getResult());
response=result.getResult();
setPoint=jsonObject.getAsJsonObject("state").getAsJsonObject("reported")
.get("current_date").getAsString();
textView.setText(setPoint);
// Toast.makeText(getApplication(),setPoint,Toast.LENGTH_LONG).show();
Log.i(GetShadowTask.class.getCanonicalName(), result.getResult());
} else {
Log.e(GetShadowTask.class.getCanonicalName(), "getShadowTask", result.getError());
Toast.makeText(getApplication(),result.getError().toString(),Toast.LENGTH_LONG).show();
}
}
}
UPDATE
Thing Shadow
{
"desired": {
"welcome": "aws-iot"
},
"reported": {
"welcome": "aws-iot",
"current_date": "06-Sep-2017 1:26:40 PM"
}
}
AWS has provided a complete Github repo of Android samples. In the samples do the PubSubWebSocket to connect, subscribe and publish the data to the shadow.
If you have a closer look into the PubSubWebSocket example you will find a detailed information on how to to make a thing policy and role. It cannot be more concise and clear than that.
For understanding and using Cognito follow AmazonCognitoAuthDemo example to make the identity pool and use it in the PubSubWebSocket example.
To get a better understanding of roles and Cognito. Please read the AWS documentation.
Update:
In the IoT thing policy did you give appropriate permissions to connect, subscribe and publish. The option can be found in AWS IoT->Security->Policy->Create Policy.
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": "iot:*",
"Resource": "arn:aws:iot:us-east-2:293751794947:topic/replaceWithATopic"
}
]
}
The above policy gives all access to the user. Also, make sure your pool which you created is for unauthenticated users.
To get the changes to the shadow type the following in the sample android(WebSocketAwsPubSub) edit box $aws/things/thing_name/shadow/update/accepted
And to publish the data to the shadow type $aws/things/thing_name/shadow/update
Update 2:
Android Code where you will receive the reported messaged. Its suscribing to the device. Its the copy of the snippet from PubSubWebSocketSample.
public void AwsSubscribe(){
final String topic = "$aws/things/D1/shadow/update/accepted";
Log.d(LOG_TAG, "topic = " + topic);
try {
mqttManager.subscribeToTopic(topic, AWSIotMqttQos.QOS0,
new AWSIotMqttNewMessageCallback() {
#Override
public void onMessageArrived(final String topic, final byte[] data) {
runOnUiThread(new Runnable() {
#Override
public void run() {
try {
String message = new String(data, "UTF-8");
Log.d(LOG_TAG, "Message arrived:");
Log.d(LOG_TAG, " Topic: " + topic);
Log.d(LOG_TAG, " Message: " + message);
tvLastMessage.setText(message);
} catch (UnsupportedEncodingException e) {
Log.e(LOG_TAG, "Message encoding error.", e);
}
}
});
}
});
} catch (Exception e) {
Log.e(LOG_TAG, "Subscription error.", e);
}
}
If you want to create a topic, just change the value of this variable final String topic = "YOUR TOPIC" then subscribe to it by using the sample code.
get request endpoint method defined in api interface
#GET("youtube/v3/search")
Callback<YoutubeResponse> getYouTubeVideos(#Query("key") String apiKey,
#Query("channelId") String channelId,
#Query("part") String videoPart,
#Query("order") String videoOrder,
#Query("maxResults") int maxResults,
Callback<ChannelListResponse> callback);
Method call to get the results :
Callback <YoutubeResponse> call = apiService.getYouTubeVideos(API_KEY,
"UCjXfkj5iapKHJrhYfAF9ZGg", "snippet", "date", 20, new Callback<ChannelListResponse>() {
#Override
public void onResponse(Call<ChannelListResponse> call, Response<ChannelListResponse> response) {
Log.v("check", response.body().getEtag() + "check");
}
#Override
public void onFailure(Call<ChannelListResponse> call, Throwable t) {
}
}) ;
I am not getting results via this implementaion giving illegal stat exception .
There is some structual mistake because the log says Unable to create call adapter for retrofit2.Callbackfor method ApiInterface.getYouTubeVideos
using these additional links to implement the same . Using this reference link for help : YouTube Data API v3 search JSON response retrofit parsing error
But If keep the return type of getYouTubeVideos() as void. Then it says service method can not have void return type .
A help in this regards will be appreciated
Please correct the retofit syntax like this.
api interface,
#GET("youtube/v3/search")
Call<ChannelListResponse> getYouTubeVideos(#Query("key") String apiKey,
#Query("channelId") String channelId,
#Query("part") String videoPart,
#Query("order") String videoOrder,
#Query("maxResults") int maxResults);
Method call,
Call<ChannelListResponse> call = apiService.getYouTubeVideos(API_KEY,
"UCjXfkj5iapKHJrhYfAF9ZGg", "snippet", "date", 20);
call.enqueue(new Callback<ChannelListResponse>() {
#Override
public void onResponse(Call<ChannelListResponse>call,
Response<ChannelListResponse> response) {
Log.d(TAG, "onResponse");
}
#Override
public void onFailure(Call<ChannelListResponse>call, Throwable t) {
// Log error here since request failed
Log.e(TAG, t.toString());
}
});
We're moving from Apache's http client to Retrofit and we've found some edge cases where param values can be null.
Apache used to intercept these and turn them into empty strings, but Retrofit throws an IllegalArgumentException.
We want to replicate the old behavior so that it doesn't cause any unexpected issues out in production. Is there a way for me to swap these null values with empty strings before ParameterHandler throws an exception?
You can try the following:
My web service (Asp.Net WebAPI):
[Route("api/values/getoptional")]
public IHttpActionResult GetOptional(string id = null)
{
var response = new
{
Code = 200,
Message = id != null ? id : "Response Message"
};
return Ok(response);
}
Android client:
public interface WebAPIService {
...
#GET("/api/values/getoptional")
Call<JsonObject> getOptional(#Query("id") String id);
}
MainActivity.java:
...
Call<JsonObject> jsonObjectCall1 = service.getOptional("240780"); // or service.getOptional(null);
jsonObjectCall1.enqueue(new Callback<JsonObject>() {
#Override
public void onResponse(Call<JsonObject> call, Response<JsonObject> response) {
Log.i(LOG_TAG, response.body().toString());
}
#Override
public void onFailure(Call<JsonObject> call, Throwable t) {
Log.e(LOG_TAG, t.toString());
}
});
...
Logcat output:
If using service.getOptional(null);
04-15 13:56:56.173 13484-13484/com.example.asyncretrofit I/AsyncRetrofit: {"Code":200,"Message":"Response Message"}
If using service.getOptional("240780");
04-15 13:57:56.378 13484-13484/com.example.asyncretrofit I/AsyncRetrofit: {"Code":200,"Message":"240780"}
I'm using the latest Android SDK for VK, and trying to get posts from my wall:
VKParameters vkParameters = VKParameters.from(VKApiConst.USER_ID, SettingsManager.getInstance().getVkId());
VKRequest vkRequest = VKApi.wall().get(vkParameters);
vkRequest.executeWithListener(new VKRequest.VKRequestListener() {
#Override
public void onComplete(VKResponse response) {
super.onComplete(response);
VKList<VKApiPost> posts = (VKList<VKApiPost>) response.parsedModel;
for (VKApiPost post : posts) {
Logger.i(GuestsActivity.class, "Post: " + post.getId());
}
}
#Override
public void onError(VKError error) {
super.onError(error);
}
});
I see the JSON and string in response, but parsedModel is null:
Why and how to fix it?
You need add request param extended (and yes, i know its strangely ):
VKApiConst.EXTENDED, 1