Я использую Retrofit для входа в приложение и сделал это успешно (как я могу успешно войти в устройство, ответ в порядке), но не смог показать диалог Toast или Alert для неправильных учетных данных. Как, если любой из них дает неправильный пароль или имя пользователя Я хочу показать ответ от API, что «Пароль или имя пользователя не верны». Я пробовал почти все, но каждый раз получал сообщение «Тайм-аут». Также Toast работает хорошо в любом другом месте в этой деятельности, но не смог применить его, чтобы получить ответ для неправильных учетных данных.
Вот мой логин активности Код:
package com.vshine.neuron.riseshine.activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.Toast;
import com.vshine.neuron.riseshine.R;
import com.vshine.neuron.riseshine.util.SessionManager;
import com.vshine.neuron.riseshine.webservice.ApiClient;
import com.vshine.neuron.riseshine.webservice.ApiInterface;
import com.vshine.neuron.riseshine.webservice.apimodel.login.LoginResponse;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
public class LoginActivity extends AppCompatActivity {
Button login_button;
ImageButton GetRegistered;
EditText userName_edt, password_edt;
String user_name, password;
SessionManager sessionManager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
sessionManager = new SessionManager(LoginActivity.this);
if (sessionManager.isLoggedIn()) {
startActivity(new Intent(getApplicationContext(), MainActivity.class));
this.finish();
} else {
initBasic();
initLogin();
}
}
private void initBasic() {
login_button = findViewById(R.id.login_button);
GetRegistered = findViewById(R.id.register);
userName_edt = findViewById(R.id.user_name);
password_edt = findViewById(R.id.password);
}
private void initLogin() {
GetRegistered.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(LoginActivity.this, RegisteredActivity.class);
startActivity(intent);
}
});
login_button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
user_name = userName_edt.getText().toString();
password = password_edt.getText().toString();
if (validateLogin(user_name, password)) {
//do login
doLogin(user_name, password);
}
}
});
}
private boolean validateLogin(String user_name, String password) {
if (user_name == null || user_name.trim().length() == 0) {
Toast.makeText(this, "Username is required", Toast.LENGTH_SHORT).show();
return false;
}
if (password == null || password.trim().length() == 0) {
Toast.makeText(this, "Password is required", Toast.LENGTH_SHORT).show();
return false;
}
return true;
}
private void doLogin(final String username, final String password) {
ApiInterface apiService =
ApiClient.getClient().create(ApiInterface.class);
Call<LoginResponse> call = apiService.Login(username, password);
call.enqueue(new Callback<LoginResponse>() {
@Override
public void onResponse(Call<LoginResponse> call, Response<LoginResponse> response) {
LoginResponse loginresponse = response.body();
if (!loginresponse.getStatus()) {
/* AlertDialog alertDialog = new AlertDialog.Builder(LoginActivity.this).create();
alertDialog.setTitle("Alert");
alertDialog.setMessage("message");
alertDialog.setButton(AlertDialog.BUTTON_NEUTRAL, "OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
alertDialog.show();*/
Toast.makeText(LoginActivity.this, response.code() + "response", Toast.LENGTH_SHORT).show();
} else {
String id = loginresponse.getResponse().getId();
String userName = loginresponse.getResponse().getUsername();
String firstName = loginresponse.getResponse().getFirstName();
String lastName = loginresponse.getResponse().getLastName();
String email = loginresponse.getResponse().getEmail();
sessionManager.createLoginSession(id, userName, email, firstName, lastName);
startActivity(new Intent(getApplicationContext(), MainActivity.class));
finish();
}
}
@Override
public void onFailure(Call<LoginResponse> call, Throwable t) {
// Log error here since request failed
Log.e("", t.toString());
}
});
}
}
Вот код для ApiClient:
package com.vshine.neuron.riseshine.webservice;
import java.util.concurrent.TimeUnit;
import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
public class ApiClient {
public static final String BASE_URL = "http://........../vshine/API/";
private static Retrofit retrofit = null;
public static Retrofit getClient() {
OkHttpClient okHttpClient = new OkHttpClient().newBuilder()
.connectTimeout(10, TimeUnit.SECONDS)
.readTimeout(10, TimeUnit.SECONDS)
.writeTimeout(10, TimeUnit.SECONDS)
.build();
if (retrofit == null) {
retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.client(okHttpClient)
.addConverterFactory(GsonConverterFactory.create())
.build();
}
return retrofit;
}
}
Код для ApiInteface:
package com.vshine.neuron.riseshine.webservice;
import com.google.gson.JsonObject;
import com.vshine.neuron.riseshine.webservice.apimodel.login.LoginResponse;
import retrofit2.Call;
import retrofit2.http.Field;
import retrofit2.http.FormUrlEncoded;
import retrofit2.http.POST;
public interface ApiInterface {
@FormUrlEncoded
@POST("api.php?action=Login")
Call<LoginResponse> Login(@Field("user_name") String username, @Field("password") String password);
}
Изображение Logcat:
