Reputation: 1
@Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState);
binding = FragmentAlarmBinding.inflate(getLayoutInflater());
return binding.getRoot();
createNotificationChannel(); //problem is here. The name of the problem "Unreachable statement"
binding.cancelAlarmBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
cancelAlarm();
}
});
}
Upvotes: 0
Views: 107
Reputation: 1037
So you have to familiarize yourself with what a return
keyword does in a method. You can go through this article.
In Java, the return keyword returns a value from a method. The method will return the value immediately when the keyword is encountered. This means that the method will not execute any more statements beyond the return keyword, and any local variables created in the method will be discarded.
So back to your case, you have the following code:
@Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState);
binding = FragmentAlarmBinding.inflate(getLayoutInflater());
return binding.getRoot();
createNotificationChannel(); //problem is here. The name of the problem "Unreachable statement"
binding.cancelAlarmBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
cancelAlarm();
}
});
}
You are having return binding.getRoot();
in the second line of your method. And that is already an ending point of your method. All the remaining lines you have within the method will not be executed. And hence that's why Unreachable statement will be prompted.
So the correct code for onCreateView()
function should look like this:
@Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState);
binding = FragmentAlarmBinding.inflate(getLayoutInflater());
return binding.getRoot();
}
Then you may wonder how to deal with the remaining lines of your method? So for a Fragment, after the View is being loaded with onCreateView()
, onViewCreated()
will be called and you can do your next action there. So you should implement another override method onViewCreated()
:
@Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState);
binding = FragmentAlarmBinding.inflate(getLayoutInflater());
return binding.getRoot();
}
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
createNotificationChannel();
binding.cancelAlarmBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
cancelAlarm();
}
});
}
Upvotes: 1