片段中的 Tablayout 包 - 空对象引用

Tablayout bundle in fragment - null object reference

我在这里使用本指南制作 activity:http://www.androidhive.info/2015/09/android-material-design-working-with-tabs

然后我添加了一个 AsyncTask。

我正在努力通过

Activity.java

private void setupViewPager(ViewPager viewPager) {
    ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
    adapter.addFrag(new ProfileFragment(), "Profile");
    viewPager.setAdapter(adapter);
}

class ViewPagerAdapter extends FragmentPagerAdapter {
    private final List<Fragment> mFragmentList = new ArrayList<>();
    private final List<String> mFragmentTitleList = new ArrayList<>();

    public ViewPagerAdapter(FragmentManager manager) {
        super(manager);
    }

    @Override
    public Fragment getItem(int position) {
        return mFragmentList.get(position);
    }

    @Override
    public int getCount() {
        return mFragmentList.size();
    }

    public void addFrag(Fragment fragment, String title) {
        mFragmentList.add(fragment);
        mFragmentTitleList.add(title);
    }

    @Override
    public CharSequence getPageTitle(int position) {
        return mFragmentTitleList.get(position);
    }
}

@Override
    protected void onPostExecute(String JSON_STRING_GET_ID) {
        try {
            JSONObject jsonResponse = new JSONObject(JSON_STRING_GET_ID);
            JSONArray jsonMainNode = jsonResponse.optJSONArray("server_response");

            for (int i = 0; i < jsonMainNode.length(); i++) {
                JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
                get_nav_email = jsonChildNode.optString("email");

                Bundle bundle = new Bundle();
                bundle.putString("p_email", get_nav_email);
                ProfileFragment fragToProfile = new ProfileFragment();
                fragToProfile.setArguments(bundle);

            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

ProfileFragment.java:

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

    String p_email = getArguments().getString("p_email");
    TextView txtTitle = (TextView)myInflatedView.findViewById(R.id.tvUsername2);
    txtTitle.setText(p_email);
    // Inflate the layout for this fragment
    return myInflatedView;
}

这是我得到的错误:

1779-1779/com.testing.dev.application E/AndroidRuntime: FATAL EXCEPTION: main
                                                                              Process: com.testing.dev.application, PID: 1779
                                                                              java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.os.Bundle.getString(java.lang.String)' on a null object reference
                                                                                  at com.testing.dev.application.fragment.ProfileFragment.onCreateView(ProfileFragment.java:43)
                                                                                  at android.support.v4.app.Fragment.performCreateView(Fragment.java:1974)
                                                                                  at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1067)
                                                                                  at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1252)
                                                                                  at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:738)
                                                                                  at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1617)
                                                                                  at android.support.v4.app.FragmentManagerImpl.executePendingTransactions(FragmentManager.java:570)
                                                                                  at android.support.v4.app.FragmentPagerAdapter.finishUpdate(FragmentPagerAdapter.java:141)
                                                                                  at android.support.v4.view.ViewPager.populate(ViewPager.java:1177)
                                                                                  at android.support.v4.view.ViewPager.populate(ViewPager.java:1025)
                                                                                  at android.support.v4.view.ViewPager.onMeasure(ViewPager.java:1545)
                                                                                  at android.view.View.measure(View.java:17547)
                                                                                  at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5535)
                                                                                  at android.support.design.widget.CoordinatorLayout.onMeasureChild(CoordinatorLayout.java:664)
                                                                                  at android.support.design.widget.CoordinatorLayout.onMeasure(CoordinatorLayout.java:731)
                                                                                  at android.view.View.measure(View.java:17547)
                                                                                  at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5535)
                                                                                  at android.widget.FrameLayout.onMeasure(FrameLayout.java:436)
                                                                                  at android.support.v7.widget.ContentFrameLayout.onMeasure(ContentFrameLayout.java:135)
                                                                                  at android.view.View.measure(View.java:17547)
                                                                                  at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5535)
                                                                                  at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1436)
                                                                                  at android.widget.LinearLayout.measureVertical(LinearLayout.java:722)
                                                                                  at android.widget.LinearLayout.onMeasure(LinearLayout.java:613)
                                                                                  at android.view.View.measure(View.java:17547)
                                                                                  at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5535)
                                                                                  at android.widget.FrameLayout.onMeasure(FrameLayout.java:436)
                                                                                  at android.view.View.measure(View.java:17547)
                                                                                  at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5535)
                                                                                  at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1436)
                                                                                  at android.widget.LinearLayout.measureVertical(LinearLayout.java:722)
                                                                                  at android.widget.LinearLayout.onMeasure(LinearLayout.java:613)
                                                                                  at android.view.View.measure(View.java:17547)
                                                                                  at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5535)
                                                                                  at android.widget.FrameLayout.onMeasure(FrameLayout.java:436)
                                                                                  at com.android.internal.policy.impl.PhoneWindow$DecorView.onMeasure(PhoneWindow.java:2615)
                                                                                  at android.view.View.measure(View.java:17547)
                                                                                  at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:2015)
                                                                                  at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1173)
                                                                                  at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1379)
                                                                                  at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1061)
                                                                                  at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:5885)
                                                                                  at android.view.Choreographer$CallbackRecord.run(Choreographer.java:767)
                                                                                  at android.view.Choreographer.doCallbacks(Choreographer.java:580)
                                                                                  at android.view.Choreographer.doFrame(Choreographer.java:550)
                                                                                  at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:753)
                                                                                  at android.os.Handler.handleCallback(Handler.java:739)
                                                                                  at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                                  at android.os.Looper.loop(Looper.java:135)
                                                                                  at android.app.ActivityThread.main(ActivityThread.java:5254)
                                                                                  at java.lang.reflect.Method.invoke(Native Method)
                                                                                  at java.lang.reflect.Method.invoke(Method.java:372)
                                                                                  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
                                                                                  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)

当 Bundle 为 null 时,您正在尝试从 Bundle 中获取 String。 尝试添加检查包是否为空:

String p_email = null;
if(getArguments() != null) {
    p_email = getArguments().getString("p_email");
}

您应该使用 setArguments 方法将参数传递给 Fragment。通常推荐使用 newInstance 方法而不是默认构造函数来实例化片段。

参考this and this.

我有一个你可能想在这里考虑的方法!但是,当然,这取决于您。

创建您的 ViewPagerAdapter class 并在您的 addFrag() 方法中,您希望像这样传递电子邮件的值:

private String emailAddress;

public ViewPagerAdapter(FragmentManager manager, String email) {
    super(manager);
    emailAddress = email;
}

Thta 是您将在 Activity.

中创建的 ViewPagerAdapter 的构造函数

在同一个 ViewPagerAdapter class 中,您将拥有此方法 addFrag

public void addFrag(Fragment fragment, String title) {
    Bundle bundle = new Bundle();
    //important line here to note
    bundle.putString("email", emailAddress);

    fragment.setArguments(bundle);
    mFragmentList.add(fragment);
    mFragmentTitleList.add(title);
}

现在您正在将电子邮件传递给片段,在片段的 onAttach 方法中,您可以将其提取并设置为 class 级变量。

@Override
public void onAttach(Context ctx){
    super.onAttach(ctx);



    String emailAddress = getArguments().getInt("email");

    //do whatever you need here
}

但是,如果您想在用户不触摸选项卡的情况下更新片段,就像稍后在 AsyncTask 完成后一样,您可以考虑使用 Events.

您基本上是让要更新的片段从 AsyncTask 的 onPostExecute 方法订阅新事件。

我最喜欢的库正在使用 EventBus

您可以像这样简单地添加到您的 build.gradle 文件中:

compile 'org.greenrobot:eventbus:3.0.0'

希望这对您有所帮助,如果您需要任何进一步的帮助,请告诉我!