简体   繁体   English

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

[英]Passing variable from Custom class to Fragment (Android)

I'm currently working with android for my project and I can't figure out the way to passing variable from Custom class to Fragment. 我目前正在为我的项目使用android,但我不知道将变量从Custom类传递到Fragment的方法。 I can exchange variable between MainActivity and Fragment but I can't use the same way to do it in Custom class and Fragment. 我可以在MainActivity和Fragment之间交换变量,但是不能在Custom类和Fragment中使用相同的方法来实现。

The way that I use to send variable between MainActivity and Fragment is something like this 我用来在MainActivity和Fragment之间发送变量的方式是这样的

In Fragment file: 在片段文件中:

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

and after that I can use any methods from MainActivity in my Fragment.It's work fine! 之后,我可以在Fragment中使用MainActivity中的任何方法。一切正常! So I try to do the same way to passing variable from Custom class to Fragment but it's didn't work out. 因此,我尝试以相同的方式将变量从Custom类传递到Fragment,但没有成功。

The code that I tried. 我尝试过的代码。 This is my Custom Class (MyAdapter.java) 这是我的自定义类(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); } } } 

And This one is my Fragment (FourthFragment.java) I only cut some parts of it that important. 这是我的片段(FourthFragment.java),我只剪切了其中一些重要的片段。

 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(); } 

And when I run all the program its caused a problem like this when I start to click 'Yes' in Dialog that start to do a method fourthFragment.imgSend(i); 当我运行所有程序时,当我开始在对话框中单击“是”并开始执行方法FourthFragment.imgSend(i)时,它引起了类似的问题。

 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) 

So what can I do or any other way to send the variable? 那么我该怎么办或以其他任何方式发送变量? If anything else is needed, I will post it! 如果还有其他需要,我会发布! Thank you 谢谢

It's because you cast the context to MainActivity, you need to be more general in this case. 这是因为您将上下文转换为MainActivity,所以在这种情况下,您需要更加通用。 Use just Activity for the variable. 仅将Activity用作变量。 And check the type before casting it. 并在投射之前检查类型。

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();
    }
}

Your activity variable is null. 您的activity变量为null。 Have you committed the fragment? 您提交了片段吗? I don't see a place in your code that you do that. 在您的代码中没有看到您这样做的地方。

A fragment is committed and attached to its activity using the FragmentManager . 使用FragmentManager提交片段并将其附加到其活动。 Typically, you will commit a fragment in Activity.onCreate() , but you can also commit elsewhere depending on your use case. 通常,您将在Activity.onCreate()提交一个片段,但也可以根据您的用例在其他地方提交。

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

}

Once your Fragment is committed and attached, you shouldn't get a null pointer exception anymore. 一旦您的片段被提交并附加,您就不会再获得空指针异常。

For reference, here's the documentation related to attaching fragments 供参考,以下是与附加片段有关的文档

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM