I am new to android
. I want to pass data from activity
to fragment
. I saw several questions and they suggested me one solution. The Solution is passing data via bundle
. I tried that solution from stack overflow. But doesn't help me to fix this. It shows Null pointer Exception
. The weird thing is every answer has this comment that states null pointer exception error with lots of upvotes. Then what is the correct way to pass data from activity to fragment
Here's the Activity Code:
I have used Bottom Navigation Bar with 2 fragments
private BottomNavigationView.OnNavigationItemSelectedListener navigationItemSelectedListener=new BottomNavigationView.OnNavigationItemSelectedListener() {
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {
Fragment selectedFragment=null;
switch (item.getItemId())
{
case R.id.home_tab:
selectedFragment =new home_fragment();
Log.w("SelecetedFra", "Selfragloaded");
Bundle bundle = new Bundle();
bundle.putString("board_name", "cbse");
bundle.putString("class_name", "12th");
selectedFragment.setArguments(bundle);
break;
case R.id.analytics_tab:
selectedFragment =new analytics_fragment();
break;
}
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,selectedFragment).commit();
return true;
}
};
Fragment Code:
public class home_fragment extends Fragment {
private ViewGroup placeholder;
String board_name;
String class_name;
private View view;
public home_fragment() {
}
// TODO: Rename and change types and number of parameters
public static home_fragment newInstance(String param1, String param2) {
home_fragment fragment = new home_fragment();
return fragment;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// In here, I am getting the data
Bundle bundle = this.getArguments();
Log.w("bundle ", String.valueOf(bundle));
board_name = getArguments().getString("board_name");
class_name = getArguments().getString("class_name");
Log.w("homeFragBundle",class_name+""+board_name);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
view=inflater.inflate(R.layout.fragment_home_fragment_loader, container, false);
placeholder = (ViewGroup) view;
return placeholder;
}
}
Error I Got:
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.os.Bundle.getString(java.lang.String)' on a null object reference
I don't know how to pass data. Everyone suggests me to pass data via bundle. But it gives me null pointer exception
. Please help me with some solutions.