user3519023 user3519023 - 6 days ago 6
Android Question

Android Studio: App skips MainActivity and land on SecondaryActivity on launch

My app isn't behaving as intended by skipping the main activity (AuthenticationActivity) and landing on the secondary activity (HomeActivity). If my code is correct, it's supposed to start AuthenticationActivity and land the user on WelcomeFragment if not logged in, or on HomeActivity if user is logged in. This is the code for the AuthenticationActivity:

package com.android.MyApp.main;

import com.android.MyApp.R;
import com.android.MyApp.authentication.fragments.WelcomeFragment;

import android.app.Fragment;
import android.app.FragmentTransaction;
import android.content.SharedPreferences;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.content.Intent;
import android.app.FragmentManager;

import com.android.MyApp.authentication.Constants;

public class AuthenticationActivity extends AppCompatActivity{



private SharedPreferences pref;

@Override
//Applying layout to activity
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_authentication);
pref = getPreferences(0);
initFragment();
initActivity();
}

private void initFragment(){
Fragment mFragment;
if(pref.getBoolean(Constants.IS_LOGGED_IN,false)){
initActivity();
}else {
mFragment = new WelcomeFragment();
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.replace(R.id.fragment_frame,mFragment);
ft.commit();
}
}


private void initActivity(){
//Starting HomeActivity from Authentication Activity if user is logged in.
Intent intent = new Intent(this, HomeActivity.class);
startActivity(intent);
}
}


And the xml file:

<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_authentication"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:context="com.android.MyApp.main.AuthenticationActivity">

<android.support.constraint.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="0dp"
android:layout_marginLeft="0dp"
android:layout_marginRight="0dp"
android:layout_marginBottom="0dp">

<FrameLayout
android:id="@+id/fragment_frame"
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_marginTop="1dp"
android:layout_marginLeft="1dp"
android:layout_marginRight="1dp"
android:layout_marginBottom="1dp"/>

</android.support.constraint.ConstraintLayout>

</android.support.design.widget.CoordinatorLayout>


Authentication Activity has 3 fragments. Here's is the WelcomeFragment:

package com.android.MyApp.authentication.fragments;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.android.MyApp.R;
import android.content.Intent;
import android.app.Fragment;
import android.app.FragmentTransaction;
import android.support.v7.widget.AppCompatButton;
//import android.view.LayoutInflater;


import com.android.MyApp.main.HomeActivity;


public class WelcomeFragment extends Fragment implements View.OnClickListener {

private AppCompatButton login_button;
private AppCompatButton skip_button;
private AppCompatButton register_button_welcome;

//Defining the layout for this fragment
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

//Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_welcome, container, false);
initViews(view);
return view;
}

private void initViews(View view) {

login_button = (AppCompatButton) view.findViewById(R.id.signin_button);
register_button_welcome = (AppCompatButton) view.findViewById(R.id.register_button_welcome);
skip_button = (AppCompatButton) view.findViewById(R.id.skip_button);

login_button.setOnClickListener(this);
register_button_welcome.setOnClickListener(this);
skip_button.setOnClickListener(this);
}

@Override
public void onClick(View v) {

switch (v.getId()) {

case R.id.login_button:
goToLogin();
break;

case R.id.skip_button:
goToHome();
break;

case R.id.register_button_welcome:
goToRegister();
break;
}
}

private void goToLogin() {

Fragment login = new LoginFragment();
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.replace(R.id.fragment_frame, login);
//ft.addToBackStack(null);
ft.commit();
}

private void goToRegister() {

Fragment register = new RegisterFragment();
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.replace(R.id.fragment_frame, register);
//ft.addToBackStack(null);
ft.commit();
}

private void goToHome() {
Intent intent = new Intent(getActivity(), HomeActivity.class);
startActivity(intent);
}
}


And the LoginFragment:

package com.MyApp.main.authentication.fragments;

/**
* If login operation is successful, the values are stored in SharedPreferences
* Boolean variable is stored in SharedPreferences to check whether the user is logged in or not.
*/

//import android.support.v4.app.Fragment;
import android.app.Fragment;
import android.app.FragmentTransaction;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.design.widget.Snackbar;
import android.support.v7.widget.AppCompatButton;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.MyApp.main.main.HomeActivity;
import com.MyApp.main.R;
import com.MyApp.main.authentication.models.ServerRequest;
import com.MyApp.main.authentication.models.ServerResponse;
import com.MyApp.main.authentication.models.User;
import com.MyApp.main.authentication.Constants;
import com.MyApp.main.authentication.RequestInterface;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

import android.content.Intent;
//import android.content.Context;
//import android.support.v7.app.AppCompatActivity;

public class LoginFragment extends Fragment implements View.OnClickListener{

private AppCompatButton login_button;
private EditText email_field,password_field;
private TextView textlink_register;
private ProgressBar progress;
private SharedPreferences pref;


//Defining the layout for this fragment
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

//Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_login,container,false);
initViews(view);
return view;
}

private void initViews(View view){

pref = getActivity().getPreferences(0);

login_button = (AppCompatButton)view.findViewById(R.id.login_button);
textlink_register = (TextView)view.findViewById(R.id.textlink_register);
email_field = (EditText)view.findViewById(R.id.email_field);
password_field = (EditText)view.findViewById(R.id.password_field);

progress = (ProgressBar)view.findViewById(R.id.progress);

login_button.setOnClickListener(this);
textlink_register.setOnClickListener(this);
}

@Override
public void onClick(View v) {

switch (v.getId()){

case R.id.textlink_register:
goToRegister();
break;

case R.id.login_button:
String email = email_field.getText().toString();
String password = password_field.getText().toString();

if(!email.isEmpty() && !password.isEmpty()) {

progress.setVisibility(View.VISIBLE);
loginProcess(email,password);

} else {

Snackbar.make(getView(), "Fields are empty !", Snackbar.LENGTH_LONG).show();
}
break;

}
}
private void loginProcess(String email,String password){

Retrofit retrofit = new Retrofit.Builder()
.baseUrl(Constants.BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();

RequestInterface requestInterface = retrofit.create(RequestInterface.class);

User user = new User();
user.setEmail(email);
user.setPassword(password);
ServerRequest request = new ServerRequest();
request.setOperation(Constants.LOGIN_OPERATION);
request.setUser(user);
Call<ServerResponse> response = requestInterface.operation(request);

response.enqueue(new Callback<ServerResponse>() {
@Override
public void onResponse(Call<ServerResponse> call, retrofit2.Response<ServerResponse> response) {

ServerResponse resp = response.body();
Snackbar.make(getView(), resp.getMessage(), Snackbar.LENGTH_LONG).show();

if(resp.getResult().equals(Constants.SUCCESS)){
SharedPreferences.Editor editor = pref.edit();
editor.putBoolean(Constants.IS_LOGGED_IN,true);
editor.putString(Constants.EMAIL,resp.getUser().getEmail());
editor.putString(Constants.NAME,resp.getUser().getName());
editor.putString(Constants.UNIQUE_ID,resp.getUser().getUnique_id());
editor.apply();
goToHome();

}
progress.setVisibility(View.INVISIBLE);
}

@Override
public void onFailure(Call<ServerResponse> call, Throwable t) {

progress.setVisibility(View.INVISIBLE);
Log.d(Constants.TAG,"failed");
Snackbar.make(getView(), t.getLocalizedMessage(), Snackbar.LENGTH_LONG).show();

}
});
}

private void goToRegister(){

Fragment register = new RegisterFragment();
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.replace(R.id.fragment_frame,register);
ft.addToBackStack(null);
ft.commit();
}

private void goToHome(){
Intent intent = new Intent(getActivity(), HomeActivity.class);
startActivity(intent);
}


And the last fragment, RegisterFragment:

package com.android.MyApp.authentication.fragments;

/**
* Snackbar is used to display messages instead of Toast.
*/

import android.app.Fragment;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.support.design.widget.Snackbar;
import android.support.v7.widget.AppCompatButton;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.android.MyApp.R;
import com.android.MyApp.authentication.models.ServerRequest;
import com.android.MyApp.authentication.models.ServerResponse;
import com.android.MyApp.authentication.models.User;
import com.android.MyApp.authentication.Constants;
import com.android.MyApp.authentication.RequestInterface;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;



public class RegisterFragment extends Fragment implements View.OnClickListener{

private AppCompatButton register_button;
private EditText email_field,password_field,name_field;
private TextView textlink_login;
private ProgressBar progress;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

View view = inflater.inflate(R.layout.fragment_register,container,false);
initViews(view);
return view;
}

private void initViews(View view){

register_button = (AppCompatButton)view.findViewById(R.id.register_button);
textlink_login = (TextView)view.findViewById(R.id.textlink_login);
name_field = (EditText)view.findViewById(R.id.name_field);
email_field = (EditText)view.findViewById(R.id.email_field);
password_field = (EditText)view.findViewById(R.id.password_field);

progress = (ProgressBar)view.findViewById(R.id.progress);

register_button.setOnClickListener(this);
textlink_login.setOnClickListener(this);
}

@Override
public void onClick(View v) {

//Input text fields validation on click

switch (v.getId()){
case R.id.textlink_login:
goToLogin();
break;

case R.id.register_button:

String name = name_field.getText().toString();
String email = email_field.getText().toString();
String password = password_field.getText().toString();

if(!name.isEmpty() && !email.isEmpty() && !password.isEmpty()) {

progress.setVisibility(View.VISIBLE);
registerProcess(name,email,password);

} else {

Snackbar.make(getView(), "Fields are empty !", Snackbar.LENGTH_LONG).show();
}
break;

}

}

private void registerProcess(String name, String email,String password){

//registerProcess method is called when the Register button is pressed (after input validation).


//Retrofit is defined here. This performs network operations and returns response

Retrofit retrofit = new Retrofit.Builder()
.baseUrl(Constants.BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();

//The input data is stored to ServerRequest model class using setters.

RequestInterface requestInterface = retrofit.create(RequestInterface.class);

User user = new User();
user.setName(name);
user.setEmail(email);
user.setPassword(password);
ServerRequest request = new ServerRequest();

request.setOperation(Constants.REGISTER_OPERATION); //Registration operation is set
request.setUser(user);
Call<ServerResponse> response = requestInterface.operation(request); //request is ServerRequest object (defined here)

//request is executed using enqueue method below

response.enqueue(new Callback<ServerResponse>() {
@Override

//onResponse callback method is called when the request is successful and response is received

public void onResponse(Call<ServerResponse> call, retrofit2.Response<ServerResponse> response) {

ServerResponse resp = response.body();
Snackbar.make(getView(), resp.getMessage(), Snackbar.LENGTH_LONG).show();
progress.setVisibility(View.INVISIBLE);
}

@Override

//The onFailure method is called if there is a failed request or network error
//All response messages are displayed in Snackbar

public void onFailure(Call<ServerResponse> call, Throwable t) {

progress.setVisibility(View.INVISIBLE);
Log.d(Constants.TAG,"failed");
Snackbar.make(getView(), t.getLocalizedMessage(), Snackbar.LENGTH_LONG).show();

}
});
}

private void goToLogin(){

Fragment login = new LoginFragment();
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.replace(R.id.fragment_frame,login);
ft.addToBackStack(null);
ft.commit();
}
}


And the Manifest file:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.android.MyApp">


<uses-permission android:name="android.permission.GET_ACCOUNTS"/>
<uses-permission android:name="android.permission.READ_PROFILE"/>
<uses-permission android:name="android.permission.READ_CONTACTS"/>
<uses-permission android:name="android.permission.INTERNET"/>

<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/Theme.AppCompat">
<activity android:name=".main.AuthenticationActivity"
android:label="@string/app_name"
android:screenOrientation="sensorPortrait">
<intent-filter>
<action android:name="android.intent.action.MAIN"/>

<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
<activity android:name=".main.HomeActivity">
</activity>
</application>

</manifest>


I've been stuck on this for a while, so really could use some help.

Answer

This is happening because in Authentication activity's onCreate method you have(i guess mistakenly) called "initActivity()" method.

In Which you have started HomeActivity.

See your initActivity code:

 private void initActivity(){
          //Starting HomeActivity from Authentication Activity if user is logged in.
          Intent intent = new Intent(this, HomeActivity.class);
          startActivity(intent);
    }

Remove this method calling from onCreate() or put some condition here if user is loggedIn already then move to HomeActivity.

Comments