Search code examples
androidstart-activity

Not able to start activity within if statement?


There is a normal flow of activities in my application. If there is an instance where the app crashes / the user force closes the app, I make sure the app goes to the previous activity where the user last was. I record that in a preferences file, when my activity first starts up I make sure that the user is not logged in, if he is, I lok into the file to see where he last was and go directly there.

The problem is that it doesnt seem to work I tried the following variations

Intent i = new Intent(MainActivity.this, com.example.ramapriyasridharan.trialapp04.MainQuestionsActivity.class);
            startActivity(i);

Intent i = new Intent(this, MainQuestionsActivity.class);
                startActivity(i);

Here is the full code:

 boolean meow = instance_user.mKinveyClient.user().isUserLoggedIn();
        Log.i("main activity", "meow = " + meow);

        // if already logged
        if(meow){
            Log.i(TAG, "(not first time): " + instance_user.mKinveyClient.user().getId());
            user_text.setText("user id is " + instance_user.mKinveyClient.user().getId());
            int a = s_logged.getInt("activity", 2);
            Log.d(TAG, "activity going to :" + a);
            Intent i = new Intent(MainActivity.this, com.example.ramapriyasridharan.trialapp04.MainQuestionsActivity.class);
            i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_MULTIPLE_TASK);
//            switch(a){
//                case 1: i = new Intent(this, MainActivity.class);break;
//                case 2: i = new Intent(this, ProfilingFeaturesActivity.class);break;
//                case 4: i = new Intent(this, ProfilingSensorsActivity.class);break;
//                case 5: i = new Intent(this, ProfilingDataCollectorsActivity.class);break;
//                case 6: i = new Intent(this, ProfilingContextsActivity.class);break;
//                case 7: i = new Intent(this, QuestionsActivity.class);break;
//                case 8: i = new Intent(this, PauseActivity.class);break;
//                case 9: i = new Intent(this, MainQuestionsActivity.class);break;
//            }
            startActivity(i);
        }

This is how i go to the next activity with the normal flow :

Intent intent = new Intent(this, GetUserInformation.class);
        e.putInt("activity", 2);
        e.commit();
        intent.putExtra("user_id",user_string);
        startActivity(intent);

The first one is always ignored, and the second intent is called, the if condition is fine, logging statement proove that the activity state(ie where the user is) is correctly recorded.The only problem is that the intent is not called, I do not know why.

Any help is welcome. Thanks

Extra code : MainActivity.java

public class MainActivity extends AppCompatActivity {

    StoreDbHelper db = null;

    private static String TAG = MainActivity.class.getName();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        DatabaseInstance d = new DatabaseInstance(this);
        db = DatabaseInstance.db;
        // do not let screen switch off
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        final SharedPreferences s_logged = getSharedPreferences("logged", Context.MODE_PRIVATE);
        final SharedPreferences.Editor e = s_logged.edit();
        int temp = s_logged.getInt("activity", 0);
        Log.d("main activity", " s_logged activity ="+temp );

        UserInstanceClass instance_user = new UserInstanceClass();
        //final Client mKinveyClient = new Client.Builder("kid_W1EFbeKyy-", "1b6f09e812114210ae4447f310b38a0a"
         //       , this.getApplicationContext()).build();

        instance_user.setmKinveyClient(new Client.Builder(this.getApplicationContext()).build());
        //final Client mKinveyClient = new Client.Builder(this.getApplicationContext()).build();
        // get app properties from kinvey.properties
        final TextView user_text;
        user_text = (TextView) findViewById(R.id.user_id);

        // check if new to app
        boolean meow = instance_user.mKinveyClient.user().isUserLoggedIn();
        Log.i("main activity", "meow = " + meow);
        int is_logged = s_logged.getInt("logged",0);
        Log.d("main activity", " s_logged logged ="+is_logged);

        // if already logged
        if(meow){
            Log.i(TAG, "(not first time): " + instance_user.mKinveyClient.user().getId());
            user_text.setText("user id is " + instance_user.mKinveyClient.user().getId());
            int a = s_logged.getInt("activity", 2);
            Log.d(TAG, "activity going to :" + a);
            Intent i = new Intent(MainActivity.this, com.example.ramapriyasridharan.trialapp04.MainQuestionsActivity.class);
            i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_MULTIPLE_TASK);
//            switch(a){
//                case 1: i = new Intent(this, MainActivity.class);break;
//                case 2: i = new Intent(this, ProfilingFeaturesActivity.class);break;
//                case 4: i = new Intent(this, ProfilingSensorsActivity.class);break;
//                case 5: i = new Intent(this, ProfilingDataCollectorsActivity.class);break;
//                case 6: i = new Intent(this, ProfilingContextsActivity.class);break;
//                case 7: i = new Intent(this, QuestionsActivity.class);break;
//                case 8: i = new Intent(this, PauseActivity.class);break;
//                case 9: i = new Intent(this, MainQuestionsActivity.class);break;
//            }
            startActivity(i);
        }

        // if user is logged in meow = True dont log him in again!

        if (!meow) {
            instance_user.mKinveyClient.user().login(new KinveyUserCallback() {
                    @Override
                    public void onFailure(Throwable error) {
                        Log.i(TAG, "Fail");
                        user_text.setText("User not identified !!");
                        Log.i(TAG, "" + error);
                    }

                    @Override
                    public void onSuccess(User result) {
                        user_text.setText("user id is " + result.getId());
                        e.putInt("logged",1); // means it is logged in
                        e.commit();
                        Log.i(TAG, "Logged in a new implicit user with id(first time): " + result.getId());
                    }
            });

        }


        String user_string = instance_user.mKinveyClient.user().getId();
        Log.i(TAG, "running for first time");

        // Reset preferences file when installing application for the first time
        // remove only debugging!
        SharedPreferences s = getSharedPreferences("bid_window_values", Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = s.edit();
        editor.putInt("current_question_number",0);
        editor.putInt("current_day",1);
        editor = AddDouble.putDouble(editor,"current_credit",0);
        editor = AddDouble.putDouble(editor,"current_privacy",100);
        editor.commit();

        // clear content to simulate first time user
        db.removeAll();
        Intent intent = new Intent(this, GetUserInformation.class);
        e.putInt("activity", 2);
        e.commit();
        intent.putExtra("user_id",user_string);
        startActivity(intent);
    }

This is the first activity called once app is opened,it ususally goes to the next activity getUserInformation, but if the user has already logged in and used the app, it should instead see where the user last was and go there.

The way I save the state using number refering to each activity as you can see in the switch case(saved in a preferences file), unfortunately calling any activity from inside the if doesnt seems to work for me.


Solution

  • As suggested, here is my answer. Firstly, I felt that your code is really disorganized - and that you should take some time to clean it up - most importantly, you should move most of the code out to some helper functions. Also, please just get rid of all the code where you use SharedPreferences - I don't really see why you have this code.

    Please see below my suggested changes which I hope can help you in resolving the problem:

    public class MainActivity extends AppCompatActivity {
    
        StoreDbHelper db = null;
        SharedPreferences.Editor s_loggedEditor = null;
    
        private static String TAG = MainActivity.class.getName();
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
    
            DatabaseInstance d = new DatabaseInstance(this);
            db = DatabaseInstance.db;
            // do not let screen switch off
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
            setContentView(R.layout.activity_main);
            Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
            setSupportActionBar(toolbar);
    
            UserInstanceClass instance_user = new UserInstanceClass();
    
            instance_user.setmKinveyClient(new Client.Builder(this.getApplicationContext()).build());
    
            final TextView user_text;
            user_text = (TextView) findViewById(R.id.user_id);
    
            // check if new to app
            boolean meow = instance_user.mKinveyClient.user().isUserLoggedIn();
            Log.i("main activity", "meow = " + meow);
    
            // if already logged
            if(meow){
                Log.i(TAG, "(not first time): " + instance_user.mKinveyClient.user().getId());
                user_text.setText("user id is " + instance_user.mKinveyClient.user().getId());
    
                Intent i = new Intent(MainActivity.this, com.example.ramapriyasridharan.trialapp04.MainQuestionsActivity.class);
                i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_MULTIPLE_TASK);
                startActivity(i);
            }
           else{
            //instead of  if (!meow){}...just use ELSE
                instance_user.mKinveyClient.user().login(new KinveyUserCallback() {
                        @Override
                        public void onFailure(Throwable error) {
                            Log.i(TAG, "Fail");
                            user_text.setText("User not identified !!");
                            Log.i(TAG, "" + error);
                        }
    
                        @Override
                        public void onSuccess(User result) {
                            user_text.setText("user id is " + result.getId());
    
                            Log.i(TAG, "Logged in a new implicit user with id(first time): " + result.getId());
                            //now you can do whatever you wanted to do when the user logs in for the first time
                            processFirstTimeLogin();
                            //Here I am just assuming you wanted to show the GetUserInformation Activity
                            String user_string = result.getId();
                            Log.i(TAG, "running for first time");
                            showGetUserInformationIntent(user_string);
                        }
                });
    
            }
    
        }
        //I just moved some of the code here 
        private void processFirstTimeLogin(){
             //THE REST OF YOUR CODE
            // Reset preferences file when installing application for the first time
            // remove only debugging!
    
            SharedPreferences s = getSharedPreferences("bid_window_values", Context.MODE_PRIVATE);
            SharedPreferences.Editor editor = s.edit();
            editor.putInt("current_question_number",0);
            editor.putInt("current_day",1);
            editor = AddDouble.putDouble(editor,"current_credit",0);
            editor = AddDouble.putDouble(editor,"current_privacy",100);
            editor.commit();
    
            // clear content to simulate first time user
            db.removeAll();
        }
        //Here you show the other Intent
        private void showGetUserInformationIntent(String userString){
            Intent intent = new Intent(this, GetUserInformation.class);
            s_loggedEditor.putInt("activity", 2);
            s_loggedEditor.commit();
            intent.putExtra("user_id",userString);
            startActivity(intent);
        }