Android错误:无法投射

时间:2018-02-27 14:59:46

标签: java android

此代码有什么问题?

Receitas.java

// File Receitas.java
public class Receitas extends Application {

    ArrayList<Receita> mReceitas;
    ArrayList<String> mTipoReceitas;

    @Override
    public void onCreate() {
        super.onCreate();

        mReceitas = new ArrayList<>();
        mTipoReceitas = new ArrayList<>();
   }

}

InsertActivity.java

public class InsertActivity extends AppCompatActivity implements AdapterView.OnItemSelectedListener {

// ...

Receitas receitas = (Receitas) getApplication();

// ...

}

当我在AndroidStudio上尝试此代码时出现此错误:

java.lang.RuntimeException: Unable to start activity...
Caused by: java.lang.ClassCastException: android.app.Application cannot be cast to com.example.android.vegeeat.model.Receitas

2 个答案:

答案 0 :(得分:0)

你不能这样做。试试这种方式

public class Receitas extends Application {

// Singleton instance
private static Receitas sInstance = null;

    @Override
    public void onCreate() {
        super.onCreate();
        // Setup singleton instance
        sInstance = this;
    }

    // Getter to access Singleton instance
    public static Receitas getInstance() {
        return sInstance ; 
    }
    }

现在

InsertActivity.java

public class InsertActivity extends AppCompatActivity implements         
AdapterView.OnItemSelectedListener {

    // ...

    Receitas receitas = (Receitas) Receitas.getInstance();

    // ...
}

答案 1 :(得分:0)

感谢所有回复的人。 Mike M.的答案解决了这个问题。