ViewPager - Android将数据从片段发送到活动时出现错误setCurrentItem(int,boolean)

时间:2018-02-21 05:49:21

标签: java android nullpointerexception android-viewpager fragment

我正在使用NonSwipeableViewPager

NonSwipeableViewPager.Java

public class NonSwipeableViewPager extends ViewPager {
    public NonSwipeableViewPager(Context context) {
        super(context);
    }

    public NonSwipeableViewPager(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    @Override
    public boolean onInterceptTouchEvent(MotionEvent event) {
        // Never allow swiping to switch between pages
        return false;
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        // Never allow swiping to switch between pages
        return false;
    }
}

我有使用此ViewPager和两个碎片的MainActivity

activity_main.xml中

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.advancetechindia.fragmenttest.MainActivity">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center_horizontal"
            android:text="Hello"
            android:textSize="20sp"
            android:textStyle="bold" />

        <com.advancetechindia.fragmenttest.NonSwipeableViewPager
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center_horizontal"
            android:id="@+id/viewpager_id"/>

    </LinearLayout>

</RelativeLayout>

MainActivity.java

public class MainActivity extends AppCompatActivity {

private NonSwipeableViewPager viewpager;
private FragmentFirst fragmentFirst=new FragmentFirst();

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    viewpager=(NonSwipeableViewPager)findViewById(R.id.viewpager_id);
    viewpager.setAdapter(new SamplePagerAdapter(
            getSupportFragmentManager()));
}

public void getData(String s) {
    Log.d("TAG",s);
    viewpager.setCurrentItem(1,true);
}

public class SamplePagerAdapter extends FragmentPagerAdapter {

    public SamplePagerAdapter(FragmentManager fm) {
        super(fm);
    }

    @Override
    public Fragment getItem(int position) {
        /** Show a Fragment based on the position of the current screen */

        if (position==0) {
            return new FragmentFirst();
        } else return new FragmentTwo();
    }

    @Override
    public int getCount() {
        return 2;
    }

} }

frag_one.xml

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

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">

        <EditText
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@+id/et_id"
            android:hint="texthere"/>

        <Button
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@+id/btn_id"
            android:text="Fire"
            android:onClick="GetString"/>

    </LinearLayout>

</RelativeLayout>

frag_one.xml

FragmentFirst.java

public class FragmentFirst extends Fragment {

private EditText et;
private Button btn;
private MainActivity mainact;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.frag_one, container,
            false);
    mainact=new MainActivity();

    et=(EditText)rootView.findViewById(R.id.et_id);
    btn=(Button)rootView.findViewById(R.id.btn_id);

    btn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            String abc=et.getText().toString();
            Log.d("TAG",abc);
            mainact.getData(abc);
        }
    });

    return rootView;
} }

另外,我有另一个片段--- FragmentTwo.java

当我点击Fire按钮时,它会调用

getData(String s)

MainActivity的方法,我得到了字符串,但它显示错误

viewpager.setCurrentItem(int,boolean)

请让我摆脱这个障碍。感谢

错误

  

10:54:46.205 31492-31492 / com.advancetechindia.fragmenttest   E / AndroidRuntime:致命例外:主要   过程:com.advancetechindia.fragmenttest,PID:31492
  java.lang.NullPointerException:尝试调用虚方法'void   com.advancetechindia.fragmenttest.NonSwipeableViewPager.setCurrentItem(INT,   boolean)'在空对象引用上   在   com.advancetechindia.fragmenttest.MainActivity.getData(MainActivity.java:30)   atcom.advancetechindia.fragmenttest.FragmentFirst $ 1.onClick(FragmentFirst.java:37)在   android.view.View.performClick(View.java:5612)在   android.view.View $ PerformClick.run(View.java:22285)在   android.os.Handler.handleCallback(Handler.java:751)在   android.os.Handler.dispatchMessage(Handler.java:95)在   android.os.Looper.loop(Looper.java:154)                                                                                              在android.app.ActivityThread.main(ActivityThread.java:6123)                                                                                              at java.lang.reflect.Method.invoke(Native Method)                                                                                              在   com.android.internal.os.ZygoteInit $ MethodAndArgsCaller.run(ZygoteInit.java:867)                                                                                              在com.android.internal.os.ZygoteInit.main(ZygoteInit.java:757)

2 个答案:

答案 0 :(得分:1)

FragmentFirst.java

中替换它
mainact.getData(abc);

((MainActivity)getActivity()).getData(abc);

答案 1 :(得分:1)

jQuery(document).ready(function() { var soft1414; $( ".single_variation_wrap" ).on( "show_variation", function ( event, variation ) { soft1414 = $("#pa_soft-cover-1414").val(); console.log(soft1414); }); }); 在Old对象中创建新对象并且mainact=new MainActivity();处于活动状态,因此您需要访问ViewPager的旧对象

MainActivity