-3

I have a class extending ParseQUeryAdapter so I can use the notifyDataSetChanged feature. The adapter class is called mainAdapter. Here's my notifyDataSetCHanged method in the mainAdapter:

@Override
public void notifyDataSetChanged() {
    super.notifyDataSetChanged();
    MainActivity mainActivity = new MainActivity();
    mainActivity.getItems();
}

Here's my getItems() method in MainActivity:

public void getItems(){
    if(adapter == null){
        Toast.makeText(MainActivity.this, "null", Toast.LENGTH_SHORT).show();
    }
}

The app crashes on loading. As you can see, I planted an if so that I can see if adapter was null. But it still crashes. According to the debugger, it says in green after getting to the if line, "adapter:null". However, I have this in onCreate():

adapter = new mainAdapter(this);

And I declared it:

mainAdapter adapter

Is there a method I can put in that will solve my issue? Although I am implementing the class, why is it still null? I clearly stated that adapter = new mainAdapter()

4

2 回答 2

2

你不应该用new;实例化你的活动类。它们应该与使用startActivity()和相关的 API 进行交互。

创建new的 Activity 不会在 ActivityManager 中注册,不会显示在屏幕上,也不会调用它的任何生命周期回调

由于您的MainActivity实例的onCreate()方法尚未运行,adapter因此尚未创建。

在您的情况下,您似乎希望 ParseQueryAdaptor 子类以某种方式引用您的活动,以便它可以访问正确的活动。

于 2016-03-01T17:49:03.230 回答
0

如果要引用现有活动,则必须将活动对象传递到要使用它的位置(或在具有可用的类中时使用 getContext 或 getActivity )。

您可以做的一件事是创建一个将 MainActivity 对象传递到 ParseQUEryAdapter 的方法。然后,当您在适配器中调用内容时:请activityObject.whatevermethodyouwantocallontheactiviy()务必先错误检查活动对象。

IE:

private MainActivity activity;
public void setup(MainActivity activity){ this.activity = activity;}

@Override
public void notifyDataSetChanged() {
    super.notifyDataSetChanged();
    if(activity != null){
        activity.getItems();
    }
}
于 2016-03-01T18:15:07.420 回答