Shikha Gupta Shikha Gupta - 1 month ago 13
Android Question

can we make two launcher activities and launch one based on some condition?

my launcher activity is loginActivity and i want that when the user selects a college and opens the app for the second time he should be moved to another activity TestYip (and not login activity). that is the launcher activty should change once the user has logged in. for this i made a fuction getCollege in Select_Collage activity which is called from the loginActivity .
but its not working.. the code is given :


  1. Select_Collage

    package notes.test.firebase;

    import java.util.ArrayList;
    import java.util.HashMap;

    import android.content.Intent;
    import android.content.SharedPreferences;
    import android.os.Build;
    import android.os.Bundle;
    import android.preference.PreferenceManager;
    import android.support.v7.app.AppCompatActivity;
    import android.text.Editable;
    import android.text.TextWatcher;
    import android.view.View;
    import android.view.Window;
    import android.view.WindowManager;
    import android.widget.AdapterView;
    import android.widget.ArrayAdapter;
    import android.widget.EditText;
    import android.widget.ListView;
    import android.widget.TextView;


    public class Select_Collage extends AppCompatActivity {

    // List view
    public ListView lv;
    public TextView tv;
    public String str;


    // Listview Adapter
    ArrayAdapter<String> adapter;

    // Search EditText
    EditText inputSearch;

    final String products[] = {"Jaypee university Guna", "Delhi university", "Graphics era", "UPES",
    "Amity university", "Saradha university",
    "ITM gwalior", "RKDF university", "Indraprast university", "IIT delhi"};


    // ArrayList for Listview
    ArrayList<HashMap<String, String>> productList;

    @Override
    public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.collage);
    if (Build.VERSION.SDK_INT >= 21) {
    Window window = getWindow();
    window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
    window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
    window.setStatusBarColor(getResources().getColor(R.color.colorPrimaryDark));
    }
    // Listview Data
    /* final String products[] = {"Jaypee university Guna", "Delhi university", "Graphics era", "UPES",
    "Amity university", "Saradha university",
    "ITM gwalior", "RKDF university", "Indraprast university", "IIT delhi"};

    */
    lv = (ListView) findViewById(R.id.list_view);


    inputSearch = (EditText) findViewById(R.id.inputSearch);

    // Adding items to listview
    adapter = new ArrayAdapter<String>(this, R.layout.college_selection_text_view, R.id.product_name, products);
    lv.setAdapter(adapter);

    lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
    @Override
    public void onItemClick(AdapterView<?> arg0, View arg1, int position,
    long arg3){

    tv = (TextView) arg1.findViewById(R.id.product_name);

    str = tv.getText().toString().trim();

    if (str.equals(products[0]))

    {
    Intent int0 = new Intent(Select_Collage.this, TestYip.class);
    startActivity(int0);
    }

    else if(str.equals(products[1])) {
    Intent int1 = new Intent(Select_Collage.this, MainListDisplay.class);
    startActivity(int1);

    }
    }
    });
    /**
    * Enabling Search Filter
    * */
    inputSearch.addTextChangedListener(new TextWatcher() {

    @Override
    public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) {
    // When user changed the Text
    Select_Collage.this.adapter.getFilter().filter(cs);
    }

    @Override
    public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
    int arg3) {
    // TODO Auto-generated method stub

    }

    @Override
    public void afterTextChanged(Editable arg0) {
    // TODO Auto-generated method stub
    }


    });
    }

    public void getCollege () {
    SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
    SharedPreferences.Editor editor = preferences.edit();
    if (str.equals(products[0]))
    {
    editor.putInt("key", 1);
    editor.apply();
    //Intent int0 = new Intent(getAppl,TestYip.class);
    //Intent int0 = new Intent(getApplicationContext(),TestYip.class);
    //startActivity(int0);
    } else {
    editor.putInt("key", 0);
    editor.apply();
    }
    }
    }

  2. LoginActivity

    package notes.test.firebase;

    import android.content.Intent;
    import android.content.SharedPreferences;
    import android.os.Bundle;
    import android.preference.PreferenceManager;
    import android.support.annotation.NonNull;
    import android.support.v7.app.AppCompatActivity;
    import android.support.v7.widget.Toolbar;
    import android.text.TextUtils;
    import android.view.View;
    import android.widget.Button;
    import android.widget.EditText;
    import android.widget.ProgressBar;
    import android.widget.Toast;

    import com.google.android.gms.tasks.OnCompleteListener;
    import com.google.android.gms.tasks.Task;
    import com.google.firebase.auth.AuthResult;
    import com.google.firebase.auth.FirebaseAuth;

    public class LoginActivity extends AppCompatActivity {

    private EditText inputEmail, inputPassword;
    private FirebaseAuth auth;
    private ProgressBar progressBar;
    private Button btnSignup, btnLogin, btnReset;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    //Get Firebase auth instance
    auth = FirebaseAuth.getInstance();

    if (auth.getCurrentUser() != null ) {
    Select_Collage s = new Select_Collage();
    //s.getCollege();
    //startActivity(new Intent(LoginActivity.this, MainActivity.class));
    s.getCollege();
    SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
    int i = preferences.getInt("key",0);
    ///startActivity(new Intent(LoginActivity.this, MainActivity.class));
    if (i==1)
    {
    startActivity(new Intent(LoginActivity.this, TestYip.class));
    }
    else
    startActivity(new Intent(LoginActivity.this, MainActivity.class));


    }

    // set the view now
    setContentView(R.layout.activity_login);

    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    inputEmail = (EditText) findViewById(R.id.email);
    inputPassword = (EditText) findViewById(R.id.password);
    progressBar = (ProgressBar) findViewById(R.id.progressBar);
    btnSignup = (Button) findViewById(R.id.btn_signup);
    btnLogin = (Button) findViewById(R.id.btn_login);
    btnReset = (Button) findViewById(R.id.btn_reset_password);

    //Get Firebase auth instance
    auth = FirebaseAuth.getInstance();

    btnSignup.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
    startActivity(new Intent(LoginActivity.this, SignupActivity.class));
    }
    });

    btnReset.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
    startActivity(new Intent(LoginActivity.this, ResetPasswordActivity.class));
    }
    });

    btnLogin.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
    String email = inputEmail.getText().toString();
    final String password = inputPassword.getText().toString();

    if (TextUtils.isEmpty(email)) {
    Toast.makeText(getApplicationContext(), "Enter email address!", Toast.LENGTH_SHORT).show();
    return;
    }

    if (TextUtils.isEmpty(password)) {
    Toast.makeText(getApplicationContext(), "Enter password!", Toast.LENGTH_SHORT).show();
    return;
    }

    progressBar.setVisibility(View.VISIBLE);

    //authenticate user
    auth.signInWithEmailAndPassword(email, password)
    .addOnCompleteListener(LoginActivity.this, new OnCompleteListener<AuthResult>() {
    @Override
    public void onComplete(@NonNull Task<AuthResult> task) {
    // If sign in fails, display a message to the user. If sign in succeeds
    // the auth state listener will be notified and logic to handle the
    // signed in user can be handled in the listener.
    progressBar.setVisibility(View.GONE);
    if (!task.isSuccessful()) {
    // there was an error
    if (password.length() < 6) {
    inputPassword.setError(getString(R.string.minimum_password));
    } else {
    Toast.makeText(LoginActivity.this, getString(R.string.auth_failed), Toast.LENGTH_LONG).show();
    }
    } else {
    Intent intent = new Intent(LoginActivity.this, MainActivity.class);
    startActivity(intent);
    finish();
    }
    }
    });
    }
    });
    }
    }

  3. Android Manifest

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

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

    <!-- To auto-complete the email text field in the login form with the user's emails -->
    <uses-permission android:name="android.permission.GET_ACCOUNTS" />
    <uses-permission android:name="android.permission.READ_PROFILE" />
    <uses-permission android:name="android.permission.READ_CONTACTS" />

    <application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
    <activity
    android:name=".LoginActivity"
    android:theme="@style/AppTheme.NoActionBar">
    <intent-filter>
    <action android:name="android.intent.action.MAIN" />

    <category android:name="android.intent.category.LAUNCHER" />
    </intent-filter>
    </activity>
    <activity
    android:name=".MainActivity"
    android:label="@string/title_activity_profile"
    android:theme="@style/AppTheme.NoActionBar">




    </activity>
    <activity
    android:name=".SignupActivity"
    android:label="@string/title_activity_login"
    android:theme="@style/AppTheme.NoActionBar" />
    <activity
    android:name=".ResetPasswordActivity"
    android:label="@string/title_activity_reset_password"
    android:theme="@style/AppTheme.NoActionBar" />
    <activity
    android:name=".TestYip"
    android:label="@string/title_test"
    android:theme="@style/AppTheme.NoActionBar" />
    <activity android:name=".Computer_Notes" />
    <activity
    android:name=".MainListDisplay"
    android:label="@string/Select_Subject"
    android:theme="@style/AppTheme.NoActionBar" >
    <meta-data
    android:name="android.app.default_searchable"
    android:value=".SearchResulltsActivity" />
    </activity>
    <activity
    android:name=".Select_Collage"
    android:label="@string/Select_Collage"
    android:theme="@style/AppTheme.NoActionBar">
    <meta-data
    android:name="android.app.default_searchable"
    android:value=".SearchResulltsActivity" />
    </activity>

    <meta-data
    android:name="android.app.searchable"
    android:resource="@xml/searchable" />

    <activity android:name=".SearchResulltsActivity"
    android:theme="@style/AppTheme.NoActionBar">
    <meta-data android:name="android.support.PARENT_ACTIVITY"
    android:value=".MainActivity"/>
    <intent-filter>
    <action android:name="android.intent.action.SEARCH" />
    </intent-filter>
    <meta-data
    android:name="android.app.searchable"
    android:resource="@xml/searchable" />
    </activity>
    </application>

    </manifest>



please tell how i can move from one activity to another based on a condition.

Answer

I will recommend the best way around. Whenever you are stuck on such things, Splash screen will help you.

Let me explain how:-

Just make splash screen as Launcher activity. If you don't want that to display it for much longer, just have the handler run for 1-2 seconds. Now look at the code below.

SplashScreen.java

public class SplashScreen extends AppCompatActivity {

    private String email;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);

        setContentView(R.layout.activity_splash);

        //SharedPreference to Store API Result
        SharedPreferences pref = getApplicationContext().getSharedPreferences("CachedResponse", 0);
        SharedPreferences.Editor editor = pref.edit();
        editor.apply();

        email = pref.getString("login", null);

        int SPLASH_TIME_OUT = 3000;

        if (email != null) {

            //It means User is already Logged in so I will take the user to Select_College Screen

            new Handler().postDelayed(new Runnable() {

                @Override
                public void run() {

                    Intent intent = new Intent(SplashScreen.this, Select_College.class);
                    intent.putExtra("Email", email);
                    startActivity(intent);
                    finish();

                }

            }, SPLASH_TIME_OUT);

        } else {

            //It means User is not Logged in so I will take the user to Login Screen

            new Handler().postDelayed(new Runnable() {

                @Override
                public void run() {

                    Intent intent = new Intent(SplashScreen.this, Login.class);
                    startActivity(intent);
                    finish();

                }

            }, SPLASH_TIME_OUT);

        }

    }
}

Login.java

public class Login extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_doctor_login);

        //SharedPreference to Store API Result
        pref = getApplicationContext().getSharedPreferences("CachedResponse", 0);

        Login();

    }

    private void login() {

        //If login is successfull, before moving to next activity, store something in sharedpreference with name login. It can be email or just a string as "true"

        SharedPreferences.Editor editor = pref.edit();
                        editor.putString("login", email);
                        editor.apply();

                        Intent intent = new Intent(DoctorLogin.this, Select_Collage.class);
                        intent.putExtra("Email", email);
                        startActivity(intent);
                        finish();

    }
}

Select_Collage.java

public class Select_Collage extends AppCompatActivity {

    private SharedPreferences pref;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_doctor_message);

        //SharedPreference to Store API Result
        pref = getApplicationContext().getSharedPreferences("CachedResponse", 0);

        //Somewhere on Signout button click, delete the login sharedpreference
        signOut();

    }

    private void signOut() {

        SharedPreferences.Editor editor = pref.edit();
        editor.remove("login");
        editor.apply();

        Intent intent = new Intent(Select_Collage.this, Login.class);
        startActivity(intent);
        finish();

    }
}

So that's how you can solve this problem. Keep Coding :)

Comments