[英]Getting ClassCastException when trying to create an array of an inner class type
[英]Classcastexception: when trying to create object of class
我有兩個java類:
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);
}
}
我正在嘗試在下面創建此類的對象:
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();
}
}
}
執行后,我在PrefManager prefManager = new PrefManager((WelcomeActivity) getApplicationContext());
行中不斷收到此錯誤。 :
原因:java.lang.ClassCastException: android.app.Application 無法轉換為 com.example.electric_viewing.WelcomeActivity
如何修復此錯誤?
使用通用的代碼
public PrefManager(Context context) {
this._context = context;
pref = _context.getSharedPreferences(PREF_NAME, PRIVATE_MODE);
editor = pref.edit();
}
現在可以像這樣創建對象
PrefManager prefManager = new PrefManager(this); // no need to call getApplicationContext
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.