尝试在空对象引用上调用虚方法

时间:2017-05-17 15:12:00

标签: android nullpointerexception fragment

我尝试从Activity调用Fragment方法。需要在activity中设置文本t1..t6(在fragment.xml中)。所以有一个错误

  

FATAL EXCEPTION:java.lang.NullPointerException:尝试调用   null上的虚方法'void PageFragment.setTime(java.lang.String)'   对象参考。

PageFragment.java

公共类PageFragment扩展Fragment {

        static final String ARGUMENT_PAGE_NUMBER = "arg_page_number";
        TextView t1,t2,t3,t4,t5,t6;
        int pageNumber;

        static PageFragment newInstance(int page) {
            PageFragment pageFragment = new PageFragment();
            Bundle arguments = new Bundle();
            arguments.putInt(ARGUMENT_PAGE_NUMBER, page);

            pageFragment.setArguments(arguments);
            return pageFragment;
        }

        @Override
        public void onAttach(Activity activity) {
            super.onAttach(activity);   
        }

        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            pageNumber = getArguments().getInt(ARGUMENT_PAGE_NUMBER);
        }

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                 Bundle savedInstanceState) {
            View view = inflater.inflate(R.layout.fragment, null);
            t1=(TextView)view.findViewById(R.id.t1);
            t2=(TextView)view.findViewById(R.id.t2);
            t3=(TextView)view.findViewById(R.id.t3);
            t4=(TextView)view.findViewById(R.id.t4);
            t5=(TextView)view.findViewById(R.id.t5);
            t6=(TextView)view.findViewById(R.id.t6);
            return view;
        }

        public void setTime(String a){
            t1.setText(a);
        }
    }

Schedule.java

FragmentManager fm = getSupportFragmentManager();
PageFragment fragment =(PageFragment)fm.findFragmentById(R.id.RelativeLayout1);
fragment.setTime((input1.getText().toString()));

1 个答案:

答案 0 :(得分:0)

您尝试将数据传递给片段的方式是错误的。这是正确的方法

<强> Schedule.java

 Bundle bundle = new Bundle();
 bundle.putString("arg_page_number", input1.getText().toString());
 // set Fragmentclass Arguments
 PageFragment fragobj = new PageFragment();
 fragobj.setArguments(bundle);

<强> PageFragment.java

在片段onCreateView方法

中接收数据
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
     View view = inflater.inflate(R.layout.fragment, null);
     pageNumber = getArguments().getInt(ARGUMENT_PAGE_NUMBER,0);
     t1=(TextView)view.findViewById(R.id.t1);
     t2=(TextView)view.findViewById(R.id.t2);
               .......           
    return view;
   }

同样,您正在将课程扩展到Fragment。