getApplicationContext()无法强制转换Android

时间:2015-07-26 16:26:27

标签: java android casting singleton

我正在创建一个Application Singleton,用于在各个活动之间共享数据。

AppData (单身人士)

import android.app.Application;

public class AppData extends Application {

    private String data;
    public String getData(){ return this.data;}
    public void setData(String data){this.data = data; }

}

MainActivity

public class SectionListExampleActivity extends Activity {

    AppData appData;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.news_list_layout);

        appData = (AppData) getApplicationContext();  // error here

    }

错误:android.app.Application cannot be cast to com.example....AppData

2 个答案:

答案 0 :(得分:5)

您是否忘记在Manifest.xml中定义应用程序?

您需要以下内容:

 <application
    android:name="package.AppName"
    ...
 </application>

答案 1 :(得分:0)

您需要在清单中注册您的应用程序类并尝试

public class SectionListExampleActivity extends Activity {

    AppData appData;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.news_list_layout);

        appData = (AppData) getApplication();

    }
}