我跟随着一些视频制作气象应用程序,最终以某种方式尝试通过从动作栏下拉菜单中按下的按钮启动我的AsyncTask。现在,asynctask是一个单独的类,应用程序在第一次加载aynctask时就很好,但是当我尝试刷新并从动作栏菜单中的按钮重新启动async任务时,应用程序崩溃并显示NullPointerException

07-18 00:45:05.615    5849-5849/johnpark.sunshine E/AndroidRuntime﹕ FATAL EXCEPTION: main
    java.lang.NullPointerException
            at johnpark.sunshine.MainActivityFragment.processFinish(MainActivityFragment.java:70)
            at johnpark.sunshine.ForeCastLoader.onPostExecute(ForeCastLoader.java:39)
            at johnpark.sunshine.ForeCastLoader.onPostExecute(ForeCastLoader.java:23)
            at android.os.AsyncTask.finish(AsyncTask.java:631)
            at android.os.AsyncTask.access$600(AsyncTask.java:177)
            at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:644)
            at android.os.Handler.dispatchMessage(Handler.java:99)
            at android.os.Looper.loop(Looper.java:137)
            at android.app.ActivityThread.main(ActivityThread.java:4745)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:511)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
            at dalvik.system.NativeStart.main(Native Method)


尝试再次访问适配器时,它得到nullPointer异常。本质上,我的主活动下拉菜单中有一个刷新按钮,用于扩展ActionBar。当我单击该按钮时,它从MainActivityFragment类调用一个方法,该类调用ForeCastLoader asynctask的execute方法。在onPostExecute()方法中,结果通过processFinish()方法传递回片段。回到ActivityFragment中的该方法中,当尝试使用适配器时,我得到了一个空指针异常。有什么想法我做错了什么?

主要活动

public class MainActivity extends ActionBarActivity
                implements OnNavigationListener, android.support.v7.app.ActionBar.OnNavigationListener {

private final String TAG = this.getClass().getSimpleName();
private boolean mNaviFirstHit = true;
MainActivityFragment mfa;

@TargetApi(Build.VERSION_CODES.HONEYCOMB)
@Override
protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    String[] dropdownValues = getResources().getStringArray(R.array.nav_list);

    android.support.v7.app.ActionBar actionBar = getSupportActionBar();

    ArrayAdapter<String> adapter = new ArrayAdapter<String>(actionBar.getThemedContext(),
            android.R.layout.simple_spinner_item, android.R.id.text1,
            dropdownValues);
    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

    actionBar.setDisplayShowTitleEnabled(false);
    actionBar.setNavigationMode(NAVIGATION_MODE_LIST);
    actionBar.setListNavigationCallbacks(adapter, this);
}

@Override
public boolean onNavigationItemSelected(int position, long id) {
    if (mNaviFirstHit) {
        mNaviFirstHit = false;
        return true;
    }

    if(position==1)
    {
        Intent in = new Intent(getApplicationContext(),SettingsActivity.class);
        startActivity(in);
    }
    if(position==2)
    {
        mfa = new MainActivityFragment();
        mfa.update();
    }
    return true;
}
}


MainActivityFragment

public class MainActivityFragment extends Fragment implements AsyncResponse{

private ArrayList <String> list = new ArrayList<>();
static ListView lv;
ForeCastLoader  f = new ForeCastLoader();
ArrayAdapter<String> adapter;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    f.delegate = this;
    adapter = new ArrayAdapter<String>(getActivity().getApplicationContext(),
            R.layout.list_item_forecast,
            R.id.list_item_forecast_textview, list);

    f.execute("94043");
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState)
{
    View v = inflater.inflate(R.layout.fragment_main, container, false);
    lv = (ListView)v.findViewById(R.id.listview_forecast);
    lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            Intent in = new Intent(getActivity().getApplicationContext(), DetailView.class);
            in.putExtra("tempData", adapter.getItem(position));
            startActivity(in);
        }
    });
    lv.setAdapter(adapter);
    return v;
}

public void update()
{
    f.delegate = this;
    f.execute("97865");
}

public void processFinish(String[] output)
{
    list.clear();
    for(String s:output)
    {
        list.add(s);
    }
    adapter.notifyDataSetChanged();
    lv.setAdapter(adapter);
}


我省略了aSyncTask类,因为我已经正确地知道了它的返回值,而且我认为问题可能不在任何地方。
感谢您的帮助,我确定它只是被忽略了。

最佳答案

好吧,我可以看到您单击NavigationItem时创建了一个新的MainActivityFragment。这样,新创建的MainActivityFragment并不是您首次启动该应用程序时添加到MainActivity的那个。新的onCreate方法未调用,因此您无法访问其中的adapter

访问Fragment中先前添加的Activity的正确方法是使用findFragmentByTagFragmentManager方法。

我假设您使用这样的标签添加MainActivityFragment

transaction.add(id, maf, MainActivityFragmentTag);


添加后,您可以像这样访问它。

if(position==2)
{
    mfa = getSupportFragmentManager().findFragmentByTag(MainActivityFragmentTag);
    mfa.update();
}

07-27 13:40