1

当我运行应用程序时,即使代码看起来“合法”并且没有语法错误,它也会崩溃。我已经建立了两个类:

在第一堂课中,我将只预览调用两个导致应用程序崩溃的其他类。

HelpFragment.java
private void updateTab(String tabId, int placeholder) {
    FragmentManager fm = getFragmentManager();
    if (fm.findFragmentByTag(tabId) == null) {
        Bundle bundl = new Bundle() ;
        bundl.putString("tabId", tabId);
        MyListFragment list_fragment = new MyListFragment();
        list_fragment.setArguments(bundl);
        fm.beginTransaction()
                .replace(placeholder, list_fragment, tabId)
                .commit();
    }
}

我们正在调用的类(以及有问题的类):

MyListFragment.java

import java.util.ArrayList;
import java.util.List;
import android.annotation.SuppressLint;
import android.content.Context;
import android.os.Bundle;
import android.app.ListFragment;
import android.app.LoaderManager.LoaderCallbacks;
import android.content.AsyncTaskLoader;
import android.content.Loader;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;


public class MyListFragment extends ListFragment implements
    LoaderCallbacks<Void> {

private static final String TAG = "FragmentTabs";

private String mTag;
private MyAdapter mAdapter;
private ArrayList<String> mItems;
private LayoutInflater mInflater;

private int mPosition;
private int mTotal;

private static final String[] About = { "Lorem", "ipsum", "dolor", "sit",
        "amet", "consectetur", "adipiscing", "elit", "Fusce", "pharetra",
        "luctus", "sodales" };
private static final String[] FAQ = { "I", "II", "III", "IV", "V",
        "VI", "VII", "VIII", "IX", "X", "XI", "XII", "XIII", "XIV", "XV" };
private static final String[] Tips = { "hello" , "bitch" , "ass" , "partners" ,  "screw", "you" ,"all", "peace" , "out"};

private static final int SLEEP = 1000;

private final int wordBarColor = R.color.word_bar;
private final int numberBarColor = R.color.number_bar;

public MyListFragment() {
    mTag = getArguments().getString("tabId");
    mTotal = HelpFragment.TAB_About.equals(mTag) ? About.length : FAQ.length;

}


//  public MyListFragment(String tag) {
//      mTag = tag;
//      mTotal = HelpFragment.TAB_About.equals(mTag) ? About.length
//              : About.length;
//
//      Log.d(TAG, "Constructor: tag=" + tag);
//  }

@Override
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
    // this is really important in order to save the state across screen
    // configuration changes for example
    setRetainInstance(true);

    mInflater = LayoutInflater.from(getActivity());

    // you only need to instantiate these the first time your fragment is
    // created; then, the method above will do the rest
    if (mAdapter == null) {
        mItems = new ArrayList<String>();
        mAdapter = new MyAdapter(getActivity(), mItems);
    }
    getListView().setAdapter(mAdapter);

    // initiate the loader to do the background work
    getLoaderManager().initLoader(0, null, this);
}

@Override
public Loader<Void> onCreateLoader(int id, Bundle args) {
    AsyncTaskLoader<Void> loader = new AsyncTaskLoader<Void>(getActivity()) {

        @Override
        public Void loadInBackground() {
            try {
                // simulate some time consuming operation going on    in the
                // background
                Thread.sleep(SLEEP);
            } catch (InterruptedException e) {
            }
            return null;
        }
    };
    // somehow the AsyncTaskLoader doesn't want to start its job without
    // calling this method
    loader.forceLoad();
    return loader;
}

@Override
public void onLoadFinished(Loader<Void> loader, Void result) {

    // add the new item and let the adapter know in order to refresh the
    // views
    mItems.add(HelpFragment.TAB_About.equals(mTag) ? About[mPosition]
            : FAQ[mPosition]);
    mAdapter.notifyDataSetChanged();

    // advance in your list with one step
    mPosition++;
    if (mPosition < mTotal - 1) {
        getLoaderManager().restartLoader(0, null, this);
        Log.d(TAG, "onLoadFinished(): loading next...");
    } else {
        Log.d(TAG, "onLoadFinished(): done loading!");
    }
}

@Override
public void onLoaderReset(Loader<Void> loader) {
}

private class MyAdapter extends ArrayAdapter<String> {

    public MyAdapter(Context context, List<String> objects) {
        super(context, R.layout.list_item, R.id.text, objects);
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        View view = convertView;
        Wrapper wrapper;

        if (view == null) {
            view = mInflater.inflate(R.layout.list_item, null);
            wrapper = new Wrapper(view);
            view.setTag(wrapper);
        } else {
            wrapper = (Wrapper) view.getTag();
        }

        wrapper.getTextView().setText(getItem(position));
        wrapper.getBar().setBackgroundColor(
                mTag == HelpFragment.TAB_About ? getResources().getColor(
                        wordBarColor) :  getResources().getColor(
                        numberBarColor));
        return view;
    }

}

// use an wrapper (or view holder) object to limit calling the
// findViewById() method, which parses the entire structure of your
// XML in search for the ID of your view
private class Wrapper {
    private final View mRoot;
    private TextView mText;
    private View mBar;

    public Wrapper(View root) {
        mRoot = root;
    }

    public TextView getTextView() {
        if (mText == null) {
            mText = (TextView) mRoot.findViewById(R.id.text);
        }
        return mText;
    }

    public View getBar() {
        if (mBar == null) {
            mBar = mRoot.findViewById(R.id.bar);
        }
        return mBar;
    }
}
}

日志:

04-06 22:21:25.079: E/AndroidRuntime(5958): FATAL EXCEPTION: main
04-06 22:21:25.079: E/AndroidRuntime(5958): java.lang.NullPointerException
04-06 22:21:25.079: E/AndroidRuntime(5958): at com.example.poca2.MyListFragment. <init>(MyListFragment.java:46)
04-06 22:21:25.079: E/AndroidRuntime(5958): at com.example.poca2.HelpFragment.updateTab(HelpFragment.java:61)
04-06 22:21:25.079: E/AndroidRuntime(5958):     at com.example.poca2.HelpFragment.onActivityCreated(HelpFragment.java:51)
04-06 22:21:25.079: E/AndroidRuntime(5958):     at android.app.Fragment.performActivityCreated(Fragment.java:1707)
04-06 22:21:25.079: E/AndroidRuntime(5958):     at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:921)
04-06 22:21:25.079: E/AndroidRuntime(5958):     at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:1075)
04-06 22:21:25.079: E/AndroidRuntime(5958):     at android.app.BackStackRecord.run(BackStackRecord.java:682)
04-06 22:21:25.079: E/AndroidRuntime(5958):     at android.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1455)
04-06 22:21:25.079: E/AndroidRuntime(5958):     at android.app.FragmentManagerImpl$1.run(FragmentManager.java:441)
04-06 22:21:25.079: E/AndroidRuntime(5958):     at android.os.Handler.handleCallback(Handler.java:730)
04-06 22:21:25.079: E/AndroidRuntime(5958):     at android.os.Handler.dispatchMessage(Handler.java:92)
04-06 22:21:25.079: E/AndroidRuntime(5958):     at android.os.Looper.loop(Looper.java:137)
04-06 22:21:25.079: E/AndroidRuntime(5958):     at android.app.ActivityThread.main(ActivityThread.java:5419)
04-06 22:21:25.079: E/AndroidRuntime(5958):     at java.lang.reflect.Method.invokeNative(Native Method)
04-06 22:21:25.079: E/AndroidRuntime(5958):     at java.lang.reflect.Method.invoke(Method.java:525)
04-06 22:21:25.079: E/AndroidRuntime(5958):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1187)
04-06 22:21:25.079: E/AndroidRuntime(5958):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1003)
04-06 22:21:25.079: E/AndroidRuntime(5958):     at  dalvik.system.NativeStart.main(Native Method)
4

1 回答 1

1

移动

mTag = getArguments().getString("tabId");
mTotal = HelpFragment.TAB_About.equals(mTag) ? About.length : FAQ.length;

里面onActivityCreated。当您调用时,new MyListFragment您尚未调用 setArguments,但您仍在尝试访问相关的 Bundle,从而导致 NPE

于 2014-04-06T19:41:00.567 回答