0
我做了一個可以存放應用程序範圍變量的類。我把它擴大活動,甚至包括它在清單中,但我仍然收到此錯誤:無法從android.app.Application轉換爲自定義類型
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.blacksmith/com.example.blacksmith.MainActivity}: java.lang.ClassCastException: android.app.Application cannot be cast to com.example.blacksmith.GlobalVars
這裏是類:
package com.example.blacksmith;
import android.app.Application;
public class GlobalVars extends Application {
private Boolean DefaultEncrypt;
private String Password;
public GlobalVars(){
DefaultEncrypt = true;
}
public void setDefaultEncrypt(Boolean is){
DefaultEncrypt = is;
}
public Boolean getDefaultEncrypt(){
return DefaultEncrypt;
}
public void setPassword(String pass){
Password = pass;
}
public String getPassword(){
return Password;
}
}
下面是Android清單:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.blacksmith"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="17"
android:targetSdkVersion="19" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="Blacksmith"
android:theme="@android:style/Theme.NoTitleBar" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".PasswordCreatorActivity"
android:label="@string/title_activity_password_creator" >
</activity>
<activity
android:name=".LoginActivity"
android:label="@string/title_activity_login" >
</activity>
</application>
<application android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:name=".application.GlobalVars">
</application>
</manifest>
這是我如何對其進行訪問:
GlobalVars tmp = ((GlobalVars) getApplicationContext());
tmp.setDefaultEncrypt(sharedPref.getBoolean("Default", true));
tmp.setPassword(sharedPref.getString("password", "0x1234"));
注意:我試過this.getApplication()和getApplication(),但都沒有工作
我在做什麼錯,我該如何解決它。
提前致謝。
您的應用程序必須包含因此您需要從您的清單中刪除第二個應用程序節點並將第一個應用程序的名稱設置爲'GlobalVars' – 2014-09-26 01:21:48
如果您將此作爲答案,我會給它一個檢查 – user1721803 2014-09-26 01:25:58
您可以檢查nPn答案,它的正確的 – 2014-09-26 01:26:45