我已经为全局变量创建了其他类,现在我只想这样抛出它:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity1);
class2 global;
global = (class2)getApplicationContext();
我收到错误:
android.app.Application无法强制转换为eu.tools.test_training_home.class2
class2
:
public class class2 extends Application {
private String name="name1";
private int number =0;
答案 0 :(得分:0)
此处getApplicationContext()
返回类Context
的对象,但不返回class2
。
检查https://stackoverflow.com/a/907368/1435132。
请参阅Custom global Application class breaks with "android.app.Application cannot be cast to"
答案 1 :(得分:-1)
问题是Class2中的Consructor 进入class2,我有1个constuctor,2个setter,2个getter 我删除了构造函数,然后错误没来了
public class class2 extends Application {
private String name ="name1";
private int number =10;
public class2(String name, int number) { // this was the problem
this.name = name;
this.number = number;
}
public void setName(String name) {
this.name = name;
}
public void setNumber(int number) {
this.number = number;
}
public String getName() {
return name;
}
public int getNumber() {
return number;
}
}