将变量从Custom类传递到Fragment(Android)

时间:2017-01-25 01:05:07

标签: java android android-fragments nullpointerexception fragment

我目前正在为我的项目使用android,但我无法找到将变量从Custom类传递到Fragment的方法。我可以在MainActivity和Fragment之间交换变量,但我不能在Custom class和Fragment中使用相同的方法。

我用来在MainActivity和Fragment之间发送变量的方式是这样的

在片段文件中:



public class FourthFragment extends Fragment {

    MainActivity activity;
    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        activity = (MainActivity) getActivity();
    }




之后我可以在Fragment中使用MainActivity中的任何方法。它的工作正常!所以我尝试以同样的方式将变量从Custom类传递给Fragment,但它没有成功。

我试过的代码。 这是我的自定义类(MyAdapter.java)



public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> {
        MainActivity activity;



        FourthFragment fourthfragment = new FourthFragment();



        private ArrayList<CreateList> galleryList;
            private Context context;





        public MyAdapter(Context context, ArrayList<CreateList> galleryList) {
                this.galleryList = galleryList;
                this.context = context;
            }

            @Override
            public MyAdapter.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
                View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.cell_layout, viewGroup, false);
                return new ViewHolder(view);
            }




        @Override
            public void onBindViewHolder(MyAdapter.ViewHolder viewHolder, final int i) {
                viewHolder.title.setText(galleryList.get(i).getImage_title());
                viewHolder.img.setScaleType(ImageView.ScaleType.CENTER_CROP);
                viewHolder.img.setImageResource((galleryList.get(i).getImage_ID()));

            viewHolder.img.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        AlertDialog.Builder builder1 = new AlertDialog.Builder(context);
                        builder1.setMessage("Are you sure you want to send this "+ galleryList.get(i).getImage_title());
                        builder1.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                Toast.makeText(context,"Yes",Toast.LENGTH_SHORT).show();



                                //TODO: Problem here NULL pointer exception


                                fourthfragment.imgSend();

                            }
                        });
                        builder1.setNegativeButton("No", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                Toast.makeText(context,"No",Toast.LENGTH_SHORT).show();
                            }
                        });
                        builder1.show();
                        Toast.makeText(context,"Image", Toast.LENGTH_SHORT).show();
                    }
                });
            }




            @Override
            public int getItemCount() {
                return galleryList.size();
            }

            public class ViewHolder extends RecyclerView.ViewHolder{
                private TextView title;
                private ImageView img;
                public ViewHolder(View view) {
                    super(view);

                    title = (TextView)view.findViewById(R.id.title);
                    img = (ImageView) view.findViewById(R.id.img);
                }
            }
        }
&#13;
&#13;
&#13;

这个是我的片段(FourthFragment.java)我只剪掉了一些重要部分。

&#13;
&#13;
public class FourthFragment extends Fragment {

        MainActivity activity;
        MyAdapter myAdapter;
        RecyclerView recyclerView;
        byte[] dataOut2 = {(byte)255, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ,0};

    @Override
        public void onAttach(Context context) {
            super.onAttach(context);
            activity = (MainActivity) getActivity();
        }

        @Override
        public void onCreate(@Nullable Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            init(savedInstanceState);

            if (savedInstanceState != null)
                onRestoreInstanceState(savedInstanceState);
              }
        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                 Bundle savedInstanceState) {
            View rootView = inflater.inflate(R.layout.fragment_fourth, container, false);
            initInstances(rootView, savedInstanceState);
            return rootView;
        }

        private void init(Bundle savedInstanceState) {
            // Init Fragment level's variable(s) here
        }

        @SuppressWarnings("UnusedParameters")
        private void initInstances(View rootView, Bundle savedInstanceState) {
            // Init 'View' instance(s) with rootView.findViewById here
            recyclerView = (RecyclerView) rootView.findViewById(R.id.imageGallery);
            recyclerView.setHasFixedSize(true);
            RecyclerView.LayoutManager layoutManager = new GridLayoutManager(getContext(),2);
            recyclerView.setLayoutManager(layoutManager);
            ArrayList<CreateList> createLists = prepareData();
            MyAdapter adapter = new MyAdapter(getContext(), createLists);
            recyclerView.setAdapter(adapter);

        }



       //Below this is a method that I create to recieve variable(i) from Custom Class (MyAdapter.java)

        public void imgSend(int i)
        {
            if( i< 28)
            {
                dataOut2[8] = (byte)1;
                int j = 0;
                j = i + 1;
                dataOut2[9] = (byte)j;
                activity.sendMessage(dataOut2);
            }
            else if(i>=28)
            {
                dataOut2[8] = (byte)2;
                int k = 0;
                k = i - 27;
                dataOut2[9]= (byte)k;
                activity.sendMessage(dataOut2);
            }
            Toast.makeText(getContext(),""+dataOut2,Toast.LENGTH_SHORT).show();
        }
&#13;
&#13;
&#13;

当我运行所有程序时,它引起了这样的问题 当我开始点击“是”&#39;在Dialog中开始做一个方法     fourthFragment.imgSend(ⅰ);

&#13;
&#13;
FATAL EXCEPTION: main
                                                                                      Process: myapplication.example.com.botcontrol, PID: 22397
                                                                                      java.lang.NullPointerException: Attempt to invoke virtual method 'void myapplication.example.com.botcontrol.MainActivity.sendMessage(byte[])' on a null object reference
                                                                                          at myapplication.example.com.botcontrol.Fragment.FourthFragment.imgSend(FourthFragment.java:156)
                                                                                          at myapplication.example.com.botcontrol.Fragment.MyAdapter$1$1.onClick(MyAdapter.java:70)
                                                                                          at android.support.v7.app.AlertController$ButtonHandler.handleMessage(AlertController.java:157)
                                                                                          at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                                          at android.os.Looper.loop(Looper.java:145)
                                                                                          at android.app.ActivityThread.main(ActivityThread.java:6939)
                                                                                          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:1404)
                                                                                          at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1199)
&#13;
&#13;
&#13;

那么我可以做什么或以其他方式发送变量?如果还需要其他任何东西,我会发布它! 谢谢

2 个答案:

答案 0 :(得分:0)

这是因为您将上下文强制转换为MainActivity,在这种情况下您需要更加通用。仅使用Activity作为变量。并在投射之前检查类型。

Activity activity;

...

@Override
public void onAttach(Context context) {
    super.onAttach(context);
    if(getActivity() instanceOf MainActivity){
        activity = (MainActivity) getActivity();
    } else if(getActivity() instanceOf CustomActivity){
        activity = (CustomActivity) getActivity();
    }
}

答案 1 :(得分:0)

您的activity变量为空。你有没有提交片段?我没有在你的代码中看到你这样做的地方。

使用FragmentManager提交片段并将其附加到其活动。通常,您将在Activity.onCreate()中提交片段,但您也可以根据您的使用情况在其他地方提交。

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    if(savedInstanceState == null) {
        getSupportFragmentManager().beginTransaction().add(R.id.my_fragment_container, new FourthFragment()).commitNow();
    }

}

一旦提交并附加了Fragment,就不应该再获得空指针异常了。

For reference, here's the documentation related to attaching fragments