java.lang.NullPointerException当我尝试在android中的片段之间获取数据时

时间:2014-04-08 15:19:25

标签: java android android-fragments

我正在尝试开发依赖于网络服务的Android应用程序,并且我使用片段让我的应用程序在移动设备和平板电脑上运行..

这是在两种模式下保存片段并检查哪种模式的活动 然后根据哪种模式定义onItemClickListener,详细信息显示在DetailFragment(Landscape)或DetailActivity(Portrait)

public class AppelsFragment extends Fragment implements AdapterView.OnItemClickListener {
    boolean mDualPane;
    int mCurCheckPosition = 0;

    public static List<Appel> appels = null;
    ListView mListView;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.list_fragment, container, false);

        return view;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        mListView = (ListView) getActivity().findViewById(R.id.listAppels);

        if (this.mListView != null) {
            this.mListView.setOnItemClickListener(this);
            this.mListView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
        }

        // this is an asynctask that retreive data from RestAPI and set the Adapter for my listview
        new Appels().execute();


        View detailsFrame = getActivity().findViewById(R.id.details);


        mDualPane = detailsFrame != null
                && detailsFrame.getVisibility() == View.VISIBLE;


        if (savedInstanceState != null) {
            // Restore last state for checked position.
            mCurCheckPosition = savedInstanceState.getInt("curChoice", 0);
        }

        if (mDualPane) {

            showDetails(mCurCheckPosition);
        } else {
            mListView.setItemChecked(mCurCheckPosition, true);
        }
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);

        outState.putInt("curChoice", mCurCheckPosition);
    }

    @Override
    public void onItemClick(AdapterView<?> l, View v, int position, long id) {

        showDetails(position);
    }


    void showDetails(int index) {
        mCurCheckPosition = index;

        if (mDualPane) {

            mListView.setItemChecked(index, true);

            DetailsFragment details = (DetailsFragment) getFragmentManager()
                    .findFragmentById(R.id.details);
            if (details == null || details.getShownIndex() != index) {

                details = DetailsFragment.newInstance(index);

                FragmentTransaction ft = getFragmentManager()
                        .beginTransaction();
                ft.replace(R.id.details, details);
                ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
                ft.commit();
            }

        } else {

            Intent intent = new Intent();

            intent.setClass(getActivity(), DetailsActivity.class);

            intent.putExtra("index", index);

            startActivity(intent);
        }
    }

class Appels extends AsyncTask<String, Void, List<Appel>> {
..... }
}
我面临的问题是DetailFragment中的NullPointerException,在Portrait模式下我没有问题

java.lang.RuntimeException: Unable to start activity ComponentInfo{com.mycompany.marocbusiness11.app/com.mycompany.marocbusiness11.app.FragmentLayout}: java.lang.NullPointerException
            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2195)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245)
            at android.app.ActivityThread.access$800(ActivityThread.java:135)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:136)
            at android.app.ActivityThread.main(ActivityThread.java:5017)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:515)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
            at dalvik.system.NativeStart.main(Native Method)
     Caused by: java.lang.NullPointerException
            at com.mycompany.marocbusiness11.app.DetailsFragment.onCreateView(DetailsFragment.java:42)
            at android.app.Fragment.performCreateView(Fragment.java:1700)
            at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:890)
            at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:1062)
            at android.app.BackStackRecord.run(BackStackRecord.java:684)
            at android.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1447)
            at android.app.Activity.performStart(Activity.java:5240)
            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2168)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245)
            at android.app.ActivityThread.access$800(ActivityThread.java:135)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:136)
            at android.app.ActivityThread.main(ActivityThread.java:5017)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:515)

这是DetailFragment的代码

public class DetailsFragment extends Fragment {

    public static DetailsFragment newInstance(int index) {
        DetailsFragment f = new DetailsFragment();

        // Supply index input as an argument.
        Bundle args = new Bundle();
        args.putInt("index", index);
        f.setArguments(args);

        return f;
    }

    public int getShownIndex() {
        return getArguments().getInt("index", 0);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        if(container == null)
            return null;

        View v = inflater.inflate(R.layout.details,container,false);
        TextView txtAffichage = (TextView) v.findViewById(R.id.txtAffichage);
        txtAffichage.setText(AppelsFragment.appels.get(getShownIndex()).getNumOrdre().toString());

        return v;

    }
}

此指令触发的问题

txtAffichage.setText(AppelsFragment.appels.get(getShownIndex()).getNumOrdre().toString());

我认为我定义列表的方式是

public static List<Appel> appels = null; 

可能是导致此问题的原因,如果有任何关于我如何处理它的建议 或者我应该改变什么

提前致谢

///////发布后编辑

在纵向模式中我使用DetailsActivity来实例化DetailsFragment,所以它总是关于Fragment ..

这是DetailsActivity的代码

public class DetailsActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {

            finish();
            return;
        }

        if (savedInstanceState == null) {

            DetailsFragment details = new DetailsFragment();

            details.setArguments(getIntent().getExtras());

            getFragmentManager().beginTransaction()
                    .add(android.R.id.content, details).commit();
        }
    }
}

和details.xml布局

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">

        <TextView
            android:id="@+id/txtAffichage"
            android:layout_width="match_parent"
            android:layout_height="match_parent" />

</LinearLayout>

2 个答案:

答案 0 :(得分:0)

这一行:

TextView txtAffichage = (TextView) v.findViewById(R.id.txtAffichage);

可能正在返回null。确保R.id.txtAffichage在布局资源文件的两个版本(纵向和横向)中都有效。

答案 1 :(得分:0)

我已经编辑了我的帖子以添加一些代码,但经过一些研究(herehere)并纠正我,如果我错了..我的asyncTask中的问题与片段有关,asnycTask负责从我的Rest API中获取数据作为List,列出我试图在我的片段中显示和使用的数据,由于连接和网络质量而导致的asyncTask无法在数据之前检索数据。片段尝试显示它们..

触发此指令时

TextView txtAffichage = (TextView) v.findViewById(R.id.txtAffichage);
        txtAffichage.setText(AppelsFragment.appels.get(getShownIndex()).getNumOrdre().toString());

List appels仍为空,并从那里出现NullPointerException异常..

我认为装载机是解决这个问题的方法,如果不是,请纠正我。