简体   繁体   English

当我单击片段 class 中的项目时,为什么我的应用程序会崩溃?

[英]Why does my app crash when I click items in a Fragment class?

When I go to click an item in the SettingsFragment, my app crashes.当我 go 单击 SettingsFragment 中的项目时,我的应用程序崩溃了。 Everything is displayed properly in this fragment class but only my parseUrl items work.此片段 class 中的所有内容都正确显示,但只有我的 parseUrl 项目有效。 i click on any other items and my app just closes out.我点击任何其他项目,我的应用程序就关闭了。 Why does that happen?为什么会这样? Below is my code.下面是我的代码。

public class SettingsFragment extends Fragment {
MainActivity context;


public SettingsFragment() {
    //public constructor
}

@NonNull
@Override
public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.navigation_drawer, container, false);


    FrameLayout instructions = view.findViewById(R.id.instructions);
    if (!getInstance().get("INSTRUCTIONS_ACTIVE", true)) {
        instructions.setVisibility(View.GONE);
    }
    instructions.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            openInstructions();

        }
    });


    return view;

}

// Main functions
void openInstructions(){
    Intent transactions = new Intent(context, FragmentsActivity.class);
    transactions.putExtra("show","instructions");
    startActivity(transactions);
}


public void settingsMenu(String Type){

    switch (Type) {



        case "instructions":

            openInstructions();

            break;

}

It seems that the context is null似乎上下文是 null
Use getContext() or getActivity() inside onCreateView to initialize the contextonCreateView中使用getContext()getActivity()来初始化上下文

context is not initialized, one way to do that is to add this method:上下文未初始化,一种方法是添加此方法:

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

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

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