On Response Code 400 I cant get data retrofit - android-studio

private void getotp(String name,String phone, String dob){
btnVerify.setClickable(false);
dialog.show();
//Toast.makeText(BookToken.this,blockname,Toast.LENGTH_LONG).show();
Retrofit retrofit = RetrofitClient.getRetrofitInstance();
apiInterface api = retrofit.create(apiInterface.class);
Call<otp> call = api.SendOtp("covishield",dose,age, blockname, location, phone);
call.enqueue(new Callback<otp>() {
#Override
public void onResponse(Call<otp> call, Response<otp> response) {
if (response.code() == 200) {
otp resp = response.body();
String Success = resp.getSuccess();
dialog.cancel();
if (response.code() == 200) {
otp resp = response.body();
String msg= resp.getMessage();
dialog.cancel();
btnVerify.setClickable(true);
}
}else {
dialog.cancel();
btnVerify.setClickable(true);
}
}
#Override
public void onFailure(Call<otp> call, Throwable t) {
Toasty.error(BookToken.this, "SomeThing Went Wrong", Toast.LENGTH_SHORT, true).show();
dialog.cancel();
}
});
}
here on response code 400 api echo json data on value message, but on my mnethod i can get the message if i try to get message it will we force close due to null object refer,
its retrofit or httpintercepter error? please let me know this

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) {
}
}); ```

to invoke interface method 'retrofit2.Call on a null object reference

how can i solve null object while sending post request
error says
to invoke interface method 'retrofit2.Call com.itgrepnet.foodbundle.remote.UserService.addUser(com.itgrepnet.foodbundle.model.User)' on a null object reference
in AddUserActivity
btnSubmit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
addNewUser();
}
private void addNewUser() {
User u = new User();
u.setFirstname(first_name.getText().toString());
u.setLastname(last_name.getText().toString());
u.setEmail(email.getText().toString());
u.setPassword(password.getText().toString());
Call<User> call = userService.addUser(u);
call.enqueue(new Callback<User>() {
#Override
public void onResponse(Call<User> call, Response<User> response) {
if (response.isSuccessful()) {
Toast.makeText(getApplicationContext(), "User Created Successfully!", Toast.LENGTH_LONG).show();
}
}
#Override
public void onFailure(Call<User> call, Throwable t) {
Log.e("Error: ", t.getMessage());
}
});
}
});
UserService.java
#POST("user/")
Call<User> addUser(#Body User user);
RetrofitClient.java
public class RetrofitClient {
private static Retrofit retrofit = null;
public static Retrofit getClient(String url) {
if (retrofit == null) {
retrofit = new Retrofit.Builder().baseUrl(url)
.addConverterFactory(GsonConverterFactory.create())
.build();
}
return retrofit;
}
}

When are we getting the exact message "timeout" in Retrofit onFailure()?

I got a SocketTimeoutException. In the onFailure method, when I call t.getMessage(), it returns exactly "timeout"
Here is my code:
private void getCouponsService() {
APIInterface mObjInterface = APIClient.getClient().create(APIInterface.class);
Call<CouponsResponseModel> call = mObjInterface.getCoupons();
call.enqueue(new Callback<CouponsResponseModel>() {
#Override
public void onResponse(Call<CouponsResponseModel> call, Response<CouponsResponseModel> response) {
if (response.code() == 200) {
// Handle success response
}
}
#Override
public void onFailure(Call<CouponsResponseModel> call, Throwable t) {
String message = t.getMessage();
}
});
}
The value of message is exactly "timeout". In which scenario are we supposed to get that message? I expected the output to be Unable to resolve host "abc.domainname.in": No address associated with hostname.

update instant message in conversation activity - Android

I am building an instant messaging feature in my app using retrofit 2.0,php and mysql. But i do not know how to show and update the messages received and send in the recyclerview.
conversation Activity
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_conversation);
dp=findViewById(R.id.conversationUser);
back=findViewById(R.id.goBackFromCoversation);
name=findViewById(R.id.conversationUserName);
activeStatus=findViewById(R.id.conversationUserSeen);
shareTitle=findViewById(R.id.conversationStatusTitle);
typeMessage=findViewById(R.id.typeMessage);
attach=findViewById(R.id.attachFiles);
send=findViewById(R.id.sendMessage);
recyclerView=findViewById(R.id.conversationRv);
toolbar=findViewById(R.id.converationToolbar);
setSupportActionBar(toolbar);
if (SharedPrefManager.getInstance(this).contains("keyid")) {
id = SharedPrefManager.getInstance(this).getUser().getId();
Toast.makeText(this, "user id is " + id, Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "no id found", Toast.LENGTH_SHORT).show();
}
getUserId= getIntent().getIntExtra("userId",0);
getUserName=getIntent().getStringExtra("userName");
getUserDp=getIntent().getStringExtra("dpUrl");
chatType=getIntent().getIntExtra("chatType",0);
if(getUserDp==null){
Toast.makeText(getApplicationContext(),"user dp is null, value is "+getUserDp,Toast.LENGTH_SHORT).show();
}else {
loadDp(getUserDp);
}
name.setText(getUserName);
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(this);
((LinearLayoutManager) mLayoutManager).setOrientation(LinearLayoutManager.VERTICAL);
recyclerView.setLayoutManager(mLayoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.setNestedScrollingEnabled(true);
fetchConversation(id,getUserId);
cla=new ConversationAdapter(this,conversation);
recyclerView.setAdapter(cla);
back.setOnClickListener(this);
name.setOnClickListener(this);
attach.setOnClickListener(this);
send.setOnClickListener(this);
}
#Override
public void onClick(View view) {
switch (view.getId()){
case R.id.goBackFromCoversation:
finish();
break;
case R.id.conversationUserName:
Intent intent= new Intent(ConversationActivity.this,ViewProfileActivity.class);
intent.putExtra("userId",getUserId);
startActivity(intent);
break;
case R.id.attachFiles:
break;
case R.id.sendMessage:
getTextMessage=typeMessage.getText().toString();
messageType=0;
sendMessage(chatType,id,getUserId,messageType,getTextMessage);
onCreate(null);
break;
}
}
private void fetchConversation(int id, int getUserId) {
Gson gson = new GsonBuilder()
.setLenient()
.create();
HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
OkHttpClient client = new OkHttpClient.Builder()
.addInterceptor(interceptor).build();
Retrofit retrofi = new Retrofit.Builder()
.baseUrl("http://192.168.56.110/app2/")
.addConverterFactory(GsonConverterFactory.create(gson))
.addConverterFactory(ScalarsConverterFactory.create())
.client(client)
.build();
RetrofitApi service = retrofi.create(RetrofitApi.class);
Call<Message> call = service.getMessages(id,getUserId);
/* Call<Message> call = RetrofitClient
.getmInstance()
.getApi()
.getMessages(id, Integer.parseInt(getUserId));*/
call.enqueue(new Callback<Message>() {
#Override
public void onResponse(Call<Message> call, Response<Message> response) {
if (response.isSuccessful()) {
if (response.body() != null) {
Message sr = response.body();
int count=sr.getConversation().toArray().length;
if(sr.getSuccess()==1){
for(int i=0;i<sr.getConversation().toArray().length;i++){
messageId=sr.getConversation().get(i).getMessageId();
fromId=sr.getConversation().get(i).getSenderId();
toId=sr.getConversation().get(i).getReceiverId();
type=sr.getConversation().get(i).getType();
timeSent=sr.getConversation().get(i).getTime_sent();
message=sr.getConversation().get(i).getMessage();
Conversation c=new Conversation(messageId,fromId,toId,type,message,timeSent);
conversation.add(c);
cla.notifyDataSetChanged();
}
}else{
Log.v(TAG,"success is not 1");
}
} else {
Log.v(TAG, "fetchConvo, response is null ");
Toast.makeText(getApplicationContext(), "resposne is null", Toast.LENGTH_SHORT).show();
}
} else {
Log.v(TAG, "fetchConvo, Something went wrong");
Toast.makeText(getApplicationContext(), "Something went wrong- ", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onFailure(Call<Message> call, Throwable t) {
Log.v(TAG, "fetchConvo, response is" + t.getMessage());
Toast.makeText(getApplicationContext(), "Failure, response is- " + t.getMessage(), Toast.LENGTH_LONG).show();
Log.v(TAG, "fetchConvo, Failed, cause is " + t.getCause());
Toast.makeText(getApplicationContext(), "Failed, cause is - " + t.getCause(), Toast.LENGTH_LONG).show();
}
});
}
private void loadDp(String getUserDp) {
String[] parts= getUserDp.split("htdocs");
String newString="http://192.168.56.110"+ parts[1];
Log.e(TAG, newString );
GlideApp.with(this).
load(newString)
.diskCacheStrategy( DiskCacheStrategy.ALL )
.into(dp);
}
private void sendMessage(int chat,int id, int getUserId, int messageType, String getTextMessage) {
Log.v(TAG,"id is"+ id);
Log.v(TAG,"userId is"+ getUserId);
Log.v(TAG,"type is"+ messageType);
Log.v(TAG,"message is"+getTextMessage);
Gson gson = new GsonBuilder()
.setLenient()
.create();
HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
OkHttpClient client = new OkHttpClient.Builder()
.addInterceptor(interceptor).build();
Retrofit retrofi = new Retrofit.Builder()
.baseUrl("http://192.168.56.110/app2/")
.addConverterFactory(GsonConverterFactory.create(gson))
.addConverterFactory(ScalarsConverterFactory.create())
.client(client)
.build();
RetrofitApi service = retrofi.create(RetrofitApi.class);
Call<com.example.user.myapplication.Model.Response> call = service.saveMessages(id,getUserId,getTextMessage,messageType);
/* Call<com.example.user.myapplication.Model.Response> call = RetrofitClient
.getmInstance()
.getApi()
.saveMessages(id,getUserId,getTextMessage,messageType);*/
call.enqueue(new Callback<com.example.user.myapplication.Model.Response>() {
#Override
public void onResponse(Call<com.example.user.myapplication.Model.Response> call, Response<com.example.user.myapplication.Model.Response> response) {
if (response.isSuccessful()) {
if (response.body() != null) {
com.example.user.myapplication.Model.Response sr = response.body();
if(sr.getSuccess()==1){
Log.v(TAG,"Response is successful");
}
} else {
Log.v(TAG, "saveMessage, response is null ");
Toast.makeText(getApplicationContext(), "resposne is null", Toast.LENGTH_SHORT).show();
}
} else {
Log.v(TAG, "saveMessage, Something went wrong");
Toast.makeText(getApplicationContext(), "Something went wrong- ", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onFailure(Call<com.example.user.myapplication.Model.Response> call, Throwable t) {
Log.v(TAG, "saveMessage, response is" + t.getMessage());
Toast.makeText(getApplicationContext(), "Failure, response is- " + t.getMessage(), Toast.LENGTH_LONG).show();
Log.v(TAG, "saveMessage, Failed, cause is " + t.getCause());
Toast.makeText(getApplicationContext(), "Failed, cause is - " + t.getCause(), Toast.LENGTH_LONG).show();
}
});
}
Conversation Adapter
public class ConversationAdapter extends RecyclerView.Adapter<ConversationAdapter.ViewHolder> {
private static final String TAG = "ChatListAdapter";
private Context context;
private ArrayList<Conversation> conversation= new ArrayList<>();
private int id;
public ConversationAdapter(Context context, ArrayList<Conversation> conversation) {
this.context = context;
this.conversation = conversation;
}
#NonNull
#Override
public ConversationAdapter.ViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.list_item_message, viewGroup, false);
ConversationAdapter.ViewHolder viewHolder = new ConversationAdapter.ViewHolder(view);
return viewHolder;
}
#Override
public void onBindViewHolder(#NonNull ViewHolder viewHolder, int i) {
if (SharedPrefManager.getInstance(context).contains("keyid")) {
id = SharedPrefManager.getInstance(context).getUser().getId();
Toast.makeText(context, "user id is " + id, Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(context, "no id found", Toast.LENGTH_SHORT).show();
}
if(Integer.parseInt(conversation.get(i).getSenderId())==id){
viewHolder.messageSent.setText(conversation.get(i).getMessage());
viewHolder.messaegReceievd.setVisibility(View.GONE);
}else{
viewHolder.messaegReceievd.setText(conversation.get(i).getMessage());
viewHolder.messageSent.setVisibility(View.GONE);
}
if(i==conversation.toArray().length-1) {
viewHolder.messageTime.setText(conversation.get(conversation.toArray().length- 1).getTime_sent());
}else{
viewHolder.messageTime.setVisibility(View.GONE);
}
}
#Override
public int getItemCount() {
return conversation.toArray().length;
}
public class ViewHolder extends RecyclerView.ViewHolder {
BubbleTextView messageSent,messaegReceievd;
TextView messageTime;
public ViewHolder(#NonNull View itemView) {
super(itemView);
Log.v(TAG, "ViewHolder, setting view in variables");
messageSent=itemView.findViewById(R.id.textMessageSent);
messaegReceievd=itemView.findViewById(R.id.textMessageReceived);
messageTime=itemView.findViewById(R.id.messageSentTime);
}
}
}
Whenever i send message and tries to reload the activity to show the messages received or send i start activity again and have to make network request once again which i think will take much time when real user will use it. So, therefore i want to implement something else to make it instant messaging activity.
Any help would be appreciated Thanks in advance

How update Room DB with API response if there is not data?

I am trying to update my database (room) with the response of my call api if my database table is empty and return to my recyclerview
API
#GET("user/patient/")
Flowable<ResponsePatient> getPatients(#Header("Authorization") String userToken);
FactoryData.class
public Flowable<List<Patient>> getPatientFromApi(){
String token = preferences.getValue(SDConstants.token);
return apiNetwork.getPatients(token).map(new Function<ResponsePatient, List<Patient>>() {
#Override
public List<Patient> apply(ResponsePatient responsePatient) throws Exception {
return PatientMapper.transform(responsePatient);
}
});
}
public Flowable<List<Patient>> listPatient(){
return appDataBase.patientDao().listPatient()
.switchIfEmpty(getPatientFromApi())
.doOnNext(s -> appDataBase.patientDao().saveAll(s));
}
I not sure how to do this. I appreciate any help.
Finally I can solve my problem.
public Flowable<List<Patient>> getPatient(){
return getPatientFromlocal()
.take(1)
.filter(list -> !list.isEmpty())
.switchIfEmpty(
Flowable.defer(() -> getPatientFromApi()));
}
public Flowable<List<Patient>> getPatientFromlocal(){
return appDataBase.patientDao().listPatient();
}
public Flowable<List<Patient>> getPatientFromApi(){
String token = preferences.getValue(SDConstants.token);
return apiNetwork.getPatients(token).map(new Function<ResponsePatient, List<Patient>>() {
#Override
public List<Patient> apply(ResponsePatient responsePatient) throws Exception {
return PatientMapper.transform(responsePatient);
}
}).doOnNext(new Consumer<List<Patient>>() {
#Override
public void accept(List<Patient> patients) throws Exception {
appDataBase.patientDao().saveAll(patients);
}
});
}

Resources