Home > Net >  Classcastexception: when trying to create object of class
Classcastexception: when trying to create object of class

Time:07-11

I have two java classes:

PrefManager.java :

public class PrefManager {
    SharedPreferences pref;
    SharedPreferences.Editor editor;
    Context _context;
    // shared pref mode
    int PRIVATE_MODE = 0;

    // Shared preferences file name
    private static final String PREF_NAME = "welcome";
    private static final String IS_FIRST_TIME_LAUNCH = "IsFirstTimeLaunch";

    public PrefManager(WelcomeActivity context) {
        this._context = context;
        pref = _context.getSharedPreferences(PREF_NAME, PRIVATE_MODE);
        editor = pref.edit();
    }

    public void setFirstTimeLaunch(boolean isFirstTime) {
        editor.putBoolean(IS_FIRST_TIME_LAUNCH, isFirstTime);
        editor.commit();
    }

    public boolean isFirstTimeLaunch() {
        return pref.getBoolean(IS_FIRST_TIME_LAUNCH, true);
    }
}

I am trying to create an object of this class below:

MainActivity.java :

public class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {

        PrefManager prefManager = new PrefManager((WelcomeActivity) getApplicationContext());
        if(prefManager.isFirstTimeLaunch()){
            prefManager.setFirstTimeLaunch(false);
            startActivity(new Intent(MainActivity.this, WelcomeActivity.class));
            finish();
        }
    }
}

Upon execution, I keep getting this error in the line PrefManager prefManager = new PrefManager((WelcomeActivity) getApplicationContext()); :

Caused by: java.lang.ClassCastException: android.app.Application cannot be cast to com.example.electric_viewing.WelcomeActivity

How do I fix this error?

CodePudding user response:

use code that can be generic

public PrefManager(Context context) {
        this._context = context;
        pref = _context.getSharedPreferences(PREF_NAME, PRIVATE_MODE);
        editor = pref.edit();
    }

now object can be created like this

PrefManager prefManager = new PrefManager(this); // no need to call getApplicationContext
  • Related