How to manage session between cakephp version 2.x and android for subsequent call using retrofit2 - retrofit2

#GET("product/allProduct.json;cakephp={session_key}")
Call<Product> getProductData(#Path("cakephp") String session_Key);
Call<Product> call=apiInterface.getAssetsData(session_key);
call.enqueue(new Callback<Product>() {
#Override
public void onResponse(Call<Product> call, Response<Product> response) {
Log.d("TAG","success"+new Gson().toJson(response.body()));
}
#Override
public void onFailure(Call<Product> call, Throwable t) {
Log.d(TAG, "onResponseFail ");
}
});
I am getting response null from above code,please provide some inputs if i am missing anything.

Related

How to wait for response in request inside other request async

I would like to know how to deal with my problem. I am trying to send request in android studio (using retrofit2), and in "onResponse" method send other request which assing List to object from the first request. Problem is that the first request finish before the second can download the data and assign empty list. Some spaghetti i know, but i hope that code will help to understand my problem.
First request method
private void getTrainingPlans()
{
INodeJS inter= RetrofitClient.getGsonInstance().create(INodeJS.class);
retrofit2.Call<List<PlanTreningowy>> call=inter.getTrainingPlans(User.getId());
call.enqueue(new Callback<List<PlanTreningowy>>() {
#Override
public void onResponse(Call<List<PlanTreningowy>> call, Response<List<PlanTreningowy>> response) {
if(!response.isSuccessful())
{
Toast.makeText(getContext(),"Cant download data",Toast.LENGTH_SHORT).show();
return;
}
if (response.body() != null)
{
plany_treningowe=response.body();
for(PlanTreningowy plan:plany_treningowe)
{
//second request method
getExercisesFromTrainingPlan(plan.id);
//trying assign data from request to object but its empty
plan.exercises= cwiczenia_plan_treningowy;
}
nazwa_planu.setText(plany_treningowe.get(0).getTytul());
opis_planu.setText(plany_treningowe.get(0).getOpis());
//getExercisesName(plany_treningowe.get(0).getExercises());
TreningAdapter treningAdapter=new TreningAdapter(getContext(),t_nazwa, t_nazwa.size(),PlanTreningowyFragment.this);
recyclerView.setAdapter(treningAdapter);
recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
}
else
{
nazwa_planu.setText("Brak planów");
opis_planu.setText("Brak");
}
}
#Override
public void onFailure(Call<List<PlanTreningowy>> call, Throwable t) {
}
});
}
Second request method (nested)
Call<List<Exercise>> call=inter.getExercisesFromTrainingPlan(id_planu);
call.enqueue(new Callback<List<Exercise>>() {
#Override
public void onResponse(Call<List<Exercise>> call, Response<List<Exercise>> response) {
if(!response.isSuccessful())
{
Toast.makeText(getContext(),"Nie udało się wczytać ćwiczeń",Toast.LENGTH_SHORT).show();
return;
}
if (response.body() != null)
{ //assign data to list
cwiczenia_plan_treningowy=response.body();
Log.e("dlugosc" , String.valueOf(cwiczenia_plan_treningowy.size()));
return;
}
}
#Override
public void onFailure(Call<List<Exercise>> call, Throwable t) {
}
}); ```

How to showing response string in a textview?

Result: {"Status":"OK","Message":"Report Genarated.","Result":"JVBERi0xLjUKJeLjz9MKMSAwIG9iago8PC9UeXBlL0ZvbnQvU3VidHlw"}
I am getting these response from the post api calling.Now How can i am get the Result string value.
Code:
holder.downloadBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
manager = new UtilityBillManager(context, AppBaseController.get().getUserSettings());
manager.UserTransactionReceiptReport(listener,billReceiptReport); //This the api calling
}
});
}
private final TransactionReportListener listener = new TransactionReportListener() {
#Override
public void didFetch(UserReportResponse response, String message) {
}
#Override
public void didError(String message) {
}
};
UserReponse is a Model which have String status,message, result.
Just use getResult() getter of Model class
See the below code
// add this condition to prevent app crashing.
if (response.body().getResult()!=null){
textView.setText(response.body().getResult()); // getResult() is your getters of the Model Class.
}
Hope it helps.

Problem opening BiometricPrompt android studio

I have a code where I call biometrics for password validation, and it ends up working normally, I always have the expected results when I request, but it ends up generating an error on my console that I would like you to solve, but I don't find it in place some.
Follow the code:
Error:
java.lang.IllegalStateException: Must be called from main thread of fragment host
at androidx.fragment.app.FragmentManagerImpl.ensureExecReady(FragmentManagerImpl.java:1668)
at androidx.fragment.app.FragmentManagerImpl.execPendingActions(FragmentManagerImpl.java:1721)
at androidx.fragment.app.FragmentManagerImpl.executePendingTransactions(FragmentManagerImpl.java:183)
at androidx.biometric.BiometricPrompt.authenticateInternal(BiometricPrompt.java:749)
at androidx.biometric.BiometricPrompt.authenticate(BiometricPrompt.java:658)
at com.app.EntryPoint.showBiometricPrompt(EntryPoint.java:832)
at ifractal.ManagingRequests$1.callback(ManagingRequests.java:156)
at ifractal.ManagingRequests.itAllStartsHere(ManagingRequests.java:1598)
at ifractal.JSBridge.query(JSBridge.java:35)
at android.os.MessageQueue.nativePollOnce(Native Method)
at android.os.MessageQueue.next(MessageQueue.java:326)
at android.os.Looper.loop(Looper.java:165)
at android.os.HandlerThread.run(HandlerThread.java:65)
public boolean showBiometricPrompt(String callback, String primeiro_acesso) {
BiometricPrompt.PromptInfo promptInfo =
new BiometricPrompt.PromptInfo.Builder()
.setTitle("Autenticação")
.setSubtitle("Realize o login usando sua biometria")
.setNegativeButtonText("Cancelar")
.build();
BiometricPrompt biometricPrompt = new BiometricPrompt(EntryPoint.this,
executor, new BiometricPrompt.AuthenticationCallback() {
#Override
public void onAuthenticationError(int errorCode, #NonNull CharSequence errString) {
super.onAuthenticationError(errorCode, errString);
asset.log("onAuthenticationError", "Error: " +errString);
}
}
#Override
public void onAuthenticationSucceeded(
#NonNull BiometricPrompt.AuthenticationResult result) {
super.onAuthenticationSucceeded(result);
BiometricPrompt.CryptoObject authenticatedCryptoObject =
result.getCryptoObject();
}
#SuppressLint("WrongConstant")
#Override
public void onAuthenticationFailed() {
super.onAuthenticationFailed();
asset.log("onAuthenticationError", "Failed");
}
});
biometricPrompt.authenticate(promptInfo);
return true;
}

RxJava subscribe onNext is not called when adding element asynchronously

I have a Observable like this
Observable<String> gitHubRepoModelObservable;
I have this code
repoNames = new ArrayList<String>();
gitHubRepoModelObservable = Observable.fromIterable(repoNames);
repoNames.add("Hello");
gitHubRepoModelObservable
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Observer<String>() {
#Override
public void onSubscribe(Disposable d) {
}
#Override
public void onNext(String s) {
System.out.println(s);
}
#Override
public void onError(Throwable e) {
}
#Override
public void onComplete() {
}
});
repoNames is just a list of string. When I am adding a string "hello" manually the onNext is getting called but when I am adding string from a API call like bellow
call.enqueue(new Callback<List<GitHubRepoModel>>() {
#Override
public void onResponse(Call<List<GitHubRepoModel>> call, Response<List<GitHubRepoModel>> response) {
for (GitHubRepoModel repo : response.body()) {
repoNames.add(repo.getName());
}
}
#Override
public void onFailure(Call<List<GitHubRepoModel>> call, Throwable t) {
}
});
I am adding strings from the API into the repoNames the "onNext" is not getting called.
I have seen
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
can be added while initializing retrofit but I want to better understand the rxjava so in this experiment it is not working.
Please help!
It can't not be work.
When you create you api request and try subscribe you list is emty, so Observable does not work.
You need to create Observable such, that your subcribe will run your request!
Observable<String> gitHubRepoModelObservable = Observable.create(
new Observable.OnSubscribe<String>() {
#Override
public void call(final Subscriber<? super String> sub) {
call.enqueue(new Callback<List<GitHubRepoModel>>() {
#Override
public void onResponse(Call<List<GitHubRepoModel>> call, Response<List<GitHubRepoModel>> response) {
for (GitHubRepoModel repo : response.body()) {
sub.onNext(repo.getName()); //send result to rx
}
sub.onCompleted();
}
#Override
public void onFailure(Call<List<GitHubRepoModel>> call, Throwable t) {
}
});
}
}
);
gitHubRepoModelObservable
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Observer<String>() {
#Override
public void onNext(String s) {
System.out.println(s);
}
#Override
public void onCompleted() {
}
#Override
public void onError(Throwable e) {
}
});
Why would onNext get called if you are just adding element to plain List?
In the first example you are seeing onNext being called because modified list is passed through the stream during subscribe.
Create Subject ex. PublishSubject and pass list to Subject.onNext in onResponse, subscribe to it and you will get what you want.
Second option is adding RxJava2CallAdapterFactory and return Observable<Response<List<GithubRepoModel>>>. This way you don't need to create stream yourself.

HazelCast max-idle-seconds :evict listener is not working

hazelcast configuration for the map is
<map name="test">
<max-idle-seconds>120</max-idle-seconds>
<entry-listeners>
<entry-listener include-value="true" local="false">com.test.listener.SessionListener</entry-listener>
</entry-listeners>
</map>
I have a listener configured for the evict action.
Listener is not able to catch the evict action consistently .
Hazelcast Version : 3.6.5
Listener Class Implemetation:
public class SessionListener implements EntryListener<String, Object> {
#Override
public void entryEvicted(EntryEvent<String, Object> evictData) {
try {
Session sessionObjValue = (Session) evictData.getOldValue();
String sessionId = sessionObjValue.getSessionId();
String userName = sessionObjValue.getUsername();
JSONObject inputJSON = new JSONObject();
inputJSON.put(Constants.SESSIONID, sessionId);
inputJSON.put(Constants.USER_NAME, userName);
//Operations to be performed based on the JSON Value
} catch (Exception exception) {
LOGGER.logDebug(Constants.ERROR, methodName, exception.toString());
}
}
Below are the recommendations:
Include Eviction policy configurations in your map config. Right now eviction is happening only based on max-idle-seconds.
Implement all the methods from EntryListener interface which inturn extends other interfaces.
Implement EntryExpiredListener listener also, to catch the expiry events explicitly though evict event also will be called during expiry.
Sample code:
public class MapEntryListernerTest implements EntryListener, EntryExpiredListener {
#Override
public void entryAdded(EntryEvent event) {
}
#Override
public void entryEvicted(EntryEvent event) {
}
#Override
public void entryRemoved(EntryEvent event) {
}
#Override
public void entryUpdated(EntryEvent event) {
}
#Override
public void mapCleared(MapEvent event) {
}
#Override
public void mapEvicted(MapEvent event) {
}
#Override
public void entryExpired(EntryEvent event) {
}
}

Resources