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

时间:2016-04-11 15:43:49

标签: java android android-fragments android-tablayout android-bundle

我在此处使用此指南进行活动: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)

3 个答案:

答案 0 :(得分:1)

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

创建您的ViewPagerAdapter类并在您的addFrag()方法中,您希望传递电子邮件的值,如下所示:

private String emailAddress;

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

Thta是您将在Activity中创建的ViewPagerAdapter的构造函数。

在同一个ViewPagerAdapter类中,您将使用此方法 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方法中,您可以将其提取并设置为类级变量。

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



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

    //do whatever you need here
}

但是,如果您想在没有用户触摸标签的情况下更新片段,就像稍后在AsyncTask完成后更新,您可以查看使用事件

你基本上让你想要更新的片段从AsyncTask的onPostExecute方法订阅一个新的事件。

我最喜欢的图书馆正在使用EventBus

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

compile 'org.greenrobot:eventbus:3.0.0'

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

答案 1 :(得分:0)

当Bundle为null时,您正在尝试从Bundle获取getString。 如果bundle为null,请尝试添加检查:

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

答案 2 :(得分:0)

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

请参阅thisthis