我们可以根据某些条件进行两次发射器活动吗?

时间:2016-09-29 17:27:56

标签: java android android-intent

我的启动器活动是loginActivity,我希望当用户选择大学并第二次打开应用程序时,他应该转移到另一个活动TestYip(而不是登录活动)。这是启动器激活应该在用户登录后更改。为此我在select_Collage活动中创建了一个函数getCollege,该活动是从loginActivity调用的。 但它不起作用..代码给出:

  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>
    
  4. 请告诉我如何根据条件从一项活动转移到另一项活动。

4 个答案:

答案 0 :(得分:0)

尝试在共享首选项中保存boolean或int。 在Select_collage中设置int或boolean 在LoginAcitivity中获取其值,并按照您的方式检查条件。

我猜您的代码问题是在LoginAcitivity中检查条件时,Select_collage活动中的值未设置,因为它未创建。

https://developer.android.com/training/basics/data-storage/shared-preferences.html

答案 1 :(得分:0)

不要使用LoginActivity作为启动器活动。在您的LoginActivity中,将一些标志值保存到SharedPreferences以指示用户已登录,然后在您的其他活动的onCreate(将此设置为启动器)中,检查此值,如果它不存在,则转到LoginActivity。

答案 2 :(得分:0)

我会推荐最好的方法。每当你遇到这些事情时,Splash屏幕都会帮助你。

让我解释一下: -

只需将启动画面设为启动器活动即可。如果您不想让它显示更长时间,只需让处理程序运行1-2秒。现在看下面的代码。

  

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();

    }
}

这就是你如何解决这个问题。保持编码:)

答案 3 :(得分:0)

你必须开始一个闪屏活动..在那个活动你需要检查条件(oncreate功能) 哪个活动应该发布到下一个..