-1

So i got my firstScreen that i want to be shown just on the first app use. and i have my mainActivity which will follow the firstScreen. Im only starting with android and i don't want to use the solutions brought in here: How to launch activity only once when app is opened for first time? AND Can I have an android activity run only on the first time an application is opened? because i dont know SharedPreferrences yet.

So how can i achieve that using Boolean flags?

I have got:boolean firstTimeUse = false; In my firstScreenActivity

And when i start myMainActivity i set the flag to true;

firstTimeUse = true;
Intent intent = new Intent(FirstScreen.this,MainActivity.class);
startActivity(intent);

The problem is the MainActivity doesn't recognize the Boolean variable. Am i doing it wrong? Or i can still make some modifications and do it with flags?

EDIT FirstScreen.java:

package com.example.predesignedmails;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.method.ScrollingMovementMethod;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageButton;
import android.widget.TextView;

public class FirstScreen extends AppCompatActivity
{
    TextView welcomeTextTextView;

    String welcomeText;

    ImageButton goToMainImageButton;

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

        viewsInitialization();

        welcomeText = "Welcome to Pre Designed Mails.\n"
                + "In here you will have a tons of Emails templates for about every purpose you will need.\n"
                + "Just fill the small details and click Send.\n\n"
                + "Send E-mails fast and efficient!";

        welcomeTextTextView.setText(welcomeText);
        welcomeTextTextView.setMovementMethod(new ScrollingMovementMethod());

        goToMainImageButton.setOnClickListener(new View.OnClickListener()
        {   
            @Override
            public void onClick(View v) 
            {
                Intent intent = new Intent(FirstScreen.this,MainActivity.class);
                startActivity(intent);
            }
        });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) 
    {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.first_screen, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) 
    { 
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.action_settings)
        {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    protected void onResume()
    {
         super.onResume();

        if (SettingsManager.getBoolean(this, SettingsManager.FIRST_LAUNCH, true))
        {
            SettingsManager.saveBoolean(this, SettingsManager.FIRST_LAUNCH, false);

            // First launch code
            Log.d("FirstLaunchCheckUp","First Launch");
        }
    }

    private void viewsInitialization()
    {
        welcomeTextTextView = (TextView) findViewById(R.id.welcome_text_text_view_id);
        goToMainImageButton = (ImageButton) findViewById(R.id.go_to_main_button_id);
    }
}

The onResume() method i added manually. It wasn't added automatically when i crated a new activity in Eclipse.

MainActivity.java:

package com.example.predesignedmails;

import android.support.v7.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;

public class MainActivity extends AppCompatActivity 
{
Button hatefullMailButton;
Button loveMailsButton;
Button welcomeScreenButton;

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

    getWindow().getDecorView().setBackgroundColor(getResources().getColor(R.color.main_activity_background_color)); // Setting background color

    viewsInitialization();

    hatefullMailButton.setOnClickListener(new View.OnClickListener()
    {   
        @Override
        public void onClick(View v) 
        {
            Intent intent = new Intent(MainActivity.this,HatefulMailsActivity.class);
            startActivity(intent);
        }
    });
    loveMailsButton.setOnClickListener(new View.OnClickListener()
    {
        @Override
        public void onClick(View v)
        {
            Intent intent = new Intent(MainActivity.this,LoveMailsActivity.class);
            startActivity(intent);
        }
    });
    welcomeScreenButton.setOnClickListener(new View.OnClickListener()
    {
        @Override
        public void onClick(View v) 
        {
            Intent intent = new Intent(MainActivity.this,FirstScreen.class);
            startActivity(intent);
        }
    });
}

@Override
public boolean onCreateOptionsMenu(Menu menu) 
{
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) 
{
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();
    if (id == R.id.action_settings) 
    {
        return true;
    }
    return super.onOptionsItemSelected(item);
}

private void viewsInitialization()
{
    hatefullMailButton = (Button) findViewById(R.id.hateful_email_button_id);
    loveMailsButton = (Button) findViewById(R.id.love_email_button_id);
    welcomeScreenButton = (Button) findViewById(R.id.welcome_screen_button_id);
}

}

Community
  • 1
  • 1
God
  • 1,238
  • 2
  • 18
  • 45
  • 6
    Now will be a good time to get familiar with SharedPreferrences... – Roi Divon Sep 05 '15 at 14:51
  • @RoiDivon Please no :(. – God Sep 05 '15 at 14:52
  • Well then you can try using this library https://github.com/jonfinerty/Once (it hides the usage of shared preferences) – Roi Divon Sep 05 '15 at 14:55
  • Just learn shared preferences... it's not that hard. You will need to learn it eventually. – Nick H Sep 05 '15 at 14:57
  • @RoiDivon Or i would learn SharedPrefferences. But i still didn't get any answer. You can do that with flags? – God Sep 05 '15 at 14:58
  • No you can't use flags. Because the flag's value wont be kept or the next time you open the app – Roi Divon Sep 05 '15 at 14:58
  • yes boolean cant be used to do this. You have to store your somewhere either in memory or sharedPreferences. – RajSharma Sep 05 '15 at 15:09
  • @God, I am sorry, but... What? How Rob Meeuwisse answer can it the accepted answer? Its wrong answer, it doesnt change anything. After restarting of your application, 'firstTimeUse' flag will be 'true' again, because you didnt save flag value. There is only one way to do this - its **save** flag value in the **SharedPreference** or in the _SQLite database_. Just add onResume method in your 'MainActivity' and copy 'SettingsManager' class to your project - thats it. You dont need to pass information in MainActivity - its not solved your problem, its redundant, its nothing change. – kolombo Sep 05 '15 at 17:59
  • And when you make sure that Rob Meeuwisse answer doesnt work - return to this question, copy code from my answer to your project and mark my answer as accepted answer, because its only one rigth answer. You dont need write anithing else, I already write all you need - just copy my code and thats it. – kolombo Sep 05 '15 at 18:05

2 Answers2

2

In your Activity

@Override
protected void onResume() {
    super.onResume();
    if (SettingsManager.getBoolean(this, SettingsManager.FIRST_LAUNCH, true)){
        SettingsManager.saveBoolean(this, SettingsManager.FIRST_LAUNCH, false);
        //your first launch code
    }
}

SharedPreference helper class

public class SettingsManager
{
    public static final String FIRST_LAUNCH= "first_lauch";

    public static String getString(Context context, String key, String defValue) {
        return PreferenceManager.getDefaultSharedPreferences(context).getString(key, defValue);
    }

    public static int getInt(Context context, String key, int defValue) {
        return PreferenceManager.getDefaultSharedPreferences(context).getInt(key, defValue);
    }

    public static boolean getBoolean(Context context, String key, boolean defValue) {
        return PreferenceManager.getDefaultSharedPreferences(context).getBoolean(key, defValue);
    }

    public static void saveString(Context context, String key, String value) {
        PreferenceManager.getDefaultSharedPreferences(context).edit().putString(key, value).commit();
    }

    public static void saveInt(Context context, String key, int value) {
        PreferenceManager.getDefaultSharedPreferences(context).edit().putInt(key, value).commit();
    }

    public static void saveBoolean(Context context, String key, boolean value) {
        PreferenceManager.getDefaultSharedPreferences(context).edit().putBoolean(key, value).commit();
    }
}

For the future you can write more simple methods on this SettingsManager, like

public static int getFirstLaunch(Context context) {
    return getBoolean(context, FIRST_LAUNCH, true);
}

public static int saveFirstLaunch(Context context, boolean value) {
    return saveBoolean(context, FIRST_LAUNCH, value);
}

And use it like

@Override
protected void onResume() {
    super.onResume();
    if (SettingsManager.getFirstLaunch(this)){
        SettingsManager.saveFirstLaunch(this, false);
        //your first launch code
    }
}
kolombo
  • 1,091
  • 9
  • 14
  • Can you explain a little about that and how do i check if it works? Thank you. – God Sep 05 '15 at 15:07
  • @God you can read more about SharedPreference in [documentation](http://developer.android.com/training/basics/data-storage/shared-preferences.html) or you can find some tutorials in a google. If you want to check this - just copy onResume method in your activity. And create new class file with name SettingsManager in your package. SharedPreference is not so difficult. Its very simple and helpful tool. – kolombo Sep 05 '15 at 15:25
  • But i don't have onResume() method in my firstScreenActivity and i can only override `onPostResume()` method. – God Sep 06 '15 at 08:15
  • I copy paste the code. Now how do i check if it works? – God Sep 06 '15 at 08:21
  • @God All your activities has onResume method. Its part of activity [lifecycle](http://developer.android.com/reference/android/app/Activity.html#ActivityLifecycle). If you already copy paste the code, run the app and you will see, that your "first launch code" will execute. And after that, if you restart your app, your "first launch code" will never execute again, because at the first launch you save value `false` in the SharedPreference and your `if` statement now will always be `false`. – kolombo Sep 06 '15 at 10:36
  • I dont have `onResume()` I just have `onCreate()` `onCreateOptionsMenu()` and `onOptionsItemSelected()`. – God Sep 06 '15 at 10:40
  • @God copy all your activities code to me. In the post. Just add all activities code. – kolombo Sep 06 '15 at 10:43
  • @God [This](https://codeshare.io/Mu05S). If you already start your app - your welcome message will never be displayed, you wiil see MainActivity. – kolombo Sep 06 '15 at 11:10
  • Its not happening. First the `Log.d` is never shown. Second when i start the app It always starting at the last activity i was. If i was in Main and i close the app it will open in Main again etc... – God Sep 06 '15 at 11:16
  • @God yes, but its shown **not** the last activity, its shown MainActivity. Because you already start your app **before** and `false` value already saved in the SharedPreference. If you want to reset this value, just add `SettingsManager.saveBoolean(this, SettingsManager.FIRST_LAUNCH, false)` before `if` statement in `onResume` method. – kolombo Sep 06 '15 at 11:24
  • But how you explain the `Log,d()` is not displayed.? – God Sep 06 '15 at 11:29
  • @God Install app->Start app at the first time->Log.d and first activity displayed and `false` saved in the SharedPreference->Start the app again->MainActivity shown. – kolombo Sep 06 '15 at 11:34
  • I wish it would happen but it don't O: – God Sep 06 '15 at 11:36
  • @God It happend because you already say that it happend: `when i start the app It always starting at the last activity i was. If i was in Main and i close the app it will open in Main again` – kolombo Sep 06 '15 at 11:38
  • Yeah but if i was in FirstScreen it will go there again which we don't want to happen. – God Sep 06 '15 at 11:43
  • @God its because you do it wrong. You must use the Dialog as a Welcome Dialog, instead of Activity. But this is already another question, because the question was `launching Activity only once (First app use) Using Boolean flags`. Read more about AlertDialogs in the Google. – kolombo Sep 06 '15 at 13:34
0

The reason why firstScreen does not recognize boolean firstTimeUse in mainActivity is because it does not yet exist. Only after you have executed the line startActivity(intent) will there exist an object of class mainActivity. Basically, you cannot set a boolean on something that does not yet exist.

Instead, what you can do is pass extra information to an activity that is to be started. When the just-started-activity is initializing itself it can read the extra information and act on it.

So build your intent for the activity you want to start and also set extra information in the 'extras':

Intent intent = new Intent(FirstScreen.this,MainActivity.class);
intent.putExtra("firstTimeUse", true);
startActivity(intent);

Now for your MainActivity to know the value of firstTimeUse it must read the extras:

public class MainActivity {

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

        boolean firstTimeUse = getIntent().getBooleanExtra("firstTimeUse", false);
        // do processing dependent on whether it's the first time or not
    }
}

This should solve your problem of "the MainActivity doesn't recognize the Boolean variable".

Rob Meeuwisse
  • 2,847
  • 1
  • 17
  • 21