无法将活动强制转换为界面

时间:2019-10-02 14:16:47

标签: android

我正在尝试将AddActivity数据发送到片段。

但是我不知道如何转换'callback =(OnDatabaseCallback)?在AddActivity中

我测试'〜getApplcation()','〜getApplicationContext()'

但我看到下一行错误……。

错误

Caused by: java.lang.ClassCastException: android.app.Application cannot be cast to com.devproject.eventmanager.OnDatabaseCallback
    at com.devproject.eventmanager.AddActivity.onCreate(AddActivity.java:115)

我的界面

import java.util.ArrayList;

public interface OnDatabaseCallback {
    public void insert(String name, String date, String category, String relation, String money);
    public ArrayList<AddList> selectAll();
}

MainActivity

public class MainActivity extends AppCompatActivity implements OnDatabaseCallback {
...
...
@Override
public void insert(String name, String date, String category, String relation, String money) {
    database.insertRecord(name, date, category, relation, money);
    Toast.makeText(getApplicationContext(), "Add", Toast.LENGTH_SHORT).show();
}

@Override
public ArrayList<AddList> selectAll() {
    ArrayList<AddList> result = database.selectAll();
    Toast.makeText(getApplicationContext(), "Check", Toast.LENGTH_SHORT).show();
    return result;
}

AddActivity

public class AddActivity extends AppCompatActivity {
...
OnDatabaseCallback callback;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_add);
...
...
callback = (OnDatabaseCallback) ??????
        callback = (OnDatabaseCallback) getApplication();
        saveButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            String name = nameData.getText().toString();
            String date = calendarData.getText().toString();
            String category = categoryData.getText().toString();
            String relation = relationData.getText().toString();
            String money = moneyData.getText().toString();

            callback.insert(name, date, category, relation, money);

            Intent intent = new Intent(AddActivity.this, MainActivity.class);
            startActivity(intent);
        }
    });

片段使用演员表获取MainActivity的界面

片段

@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    View v = inflater.inflate(R.layout.fragment_input, container, false);

    recyclerView = v.findViewById(R.id.addRecyclerView);
    LinearLayoutManager layoutManager = new LinearLayoutManager(getContext());
    recyclerView.setLayoutManager(layoutManager);

    adapter = new AddAdapter();
    recyclerView.setAdapter(adapter);

    ArrayList<AddList> result = callback.selectAll();
    adapter.setItems(result);

    return v;
}

@Override
public void onAttach(Context context) {
    super.onAttach(context);
    callback = (OnDatabaseCallback) getActivity();
}

0 个答案:

没有答案