[英]Need an explanation about Application class
我正在嘗試使用內置的android的Application.class ,但是每次我要使用它時,都會收到NullPointerException
。 我將分享一些代碼,以展示如何訪問自定義類,該類extends Application
:
這是我正在使用的課程:
public class SharedProperties extends Application {
private String currentCategory;
private String dataNews;
public SharedProperties() {
super();
}
public String getCurrentCategory() {
return currentCategory;
}
public void setCurrentCategory(String currentCategory) {
this.currentCategory = currentCategory;
}
public String getDataNews() {
return dataNews;
}
public void setDataNews(String dataNews) {
this.dataNews = dataNews;
}
}
...這就是我設置和從中獲取值的方式:
SharedProperties shared = ((SharedProperties)getApplication());
shared.setCurrentCategory(categories[currentCategory]);
shared.setDataNews(rssList.get(position).getData());
......
SharedProperties shared = ((SharedProperties)getApplication());
String category = shared.getCurrentCategory();
String newstext = shared.getDataNews();
我訪問它的方式是否錯誤,或者我錯過了SharedProperties.class
某些內容?
這是我的清單:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.news.reader"
android:versionCode="1"
android:versionName="1.0">
<uses-sdk android:minSdkVersion="4" />
<application android:name="SharedProperties" android:icon="@drawable/logo" android:label="@string/app_name">
<activity android:name="Splash"
android:label="@string/app_name"
android:screenOrientation="portrait">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name="Home"
android:label="@string/app_name"
android:screenOrientation="sensor"
android:configChanges="keyboardHidden|orientation" />
<activity android:name="News"
android:label="@string/app_name"
android:screenOrientation="sensor"
android:configChanges="keyboardHidden|orientation" />
</application>
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"></uses-permission>
<uses-permission android:name="android.permission.READ_PHONE_STATE"></uses-permission>
</manifest>
將android:name
屬性放在<application>
條目中,該條目包含您的所有活動,而不是作為單獨的實體。 將其更改為該類的標准名稱(例如com.this.is.your.package.SharedPreferences
)。
另外,請勿這樣做。 使用單例 。 請 。
首先,您的Application類的名稱是SharedProperties
,而不是MyApp
,因此應將其強制轉換為該名稱。
其次,為了使Android知道使用您的自定義應用程序,您需要在AndroidManifest.xml
這樣說:
<application
android:name="SharedProperties"
android:icon="@drawable/icon"
android:label="@string/app_name">
我有類似的問題,不記得我做了什么,但是請嘗試添加
public SharedProperties()
{
super();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.