I am new to Android and have come across a problem while implementing it. I'm trying to navigate the user to the MainActivity.java activity if the user has already logged in and if the user hasn't logged in then it will have navigate to the LoginActivity.java.
This is the code inside onCreate() method of my MainActivity.java.
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
name = (TextView) findViewById(R.id.tvName);
prefs = PreferenceManager.getDefaultSharedPreferences(this);
Gson gson = new GsonBuilder().create();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create(gson))
.build();
sponsorApi = retrofit.create(SponsorInterface.class);
if (prefs.getBoolean(Constants.IS_LOGGED_IN, false)){
Intent intent = new Intent(MainActivity.this, MainActivity.class);
startActivity(intent);
user = prefs.getString(Constants.USER, "Username");
Call<Sponsor> sponsorRequest = sponsorApi.getSponsor(user);
sponsorRequest.enqueue(new Callback<Sponsor>() {
@Override
public void onResponse(Call<Sponsor> call, Response<Sponsor> response) {
int statusCode = response.code();
final Sponsor sponsor = response.body();
name.setText(sponsor.getName());
Log.d("SponsorDetails Activity", "onResponse: " + statusCode);
}
@Override
public void onFailure(Call<Sponsor> call, Throwable t) {
Log.d("LoginActivity", "onFailure: " + t.getLocalizedMessage());
}
});
}else {
Intent intent = new Intent(MainActivity.this, LoginActivity.class);
Toast.makeText(getBaseContext(), "Please login to proceed", Toast.LENGTH_SHORT).show();
startActivity(intent);
}
}
When I run the app, it works but the Activity runs into infinite loop and I don't know what is causing the loop.
Update1: Debugger
PS: SponsorDetails.java in image is MainActivity.java of the question.
Update2: Removing Intent of MainActivity As suggested in the comments I removed
Intent intent = new Intent(MainActivity.this, MainActivity.class);
startActivity(intent);
But still I am getting the infinite loop in onResponse() method. Yes, after removing the code, I uninstalled the app from emulator and re-ran the app from IDE.
Update 3: onStart() method
@Override
protected void onStart() {
super.onStart();
if (prefs.getBoolean(Constants.IS_LOGGED_IN, false)){
Intent intent = new Intent(MainActivity.this, MainActivity.class);
startActivity(intent);
}else{
Intent intent = new Intent(MainActivity.this, LoginActivity.class);
Toast.makeText(getBaseContext(), "Please login to proceed", Toast.LENGTH_SHORT).show();
startActivity(intent);
}
}