The application has three activities with fragments. The first fragment of the RecyclerView with the list, the second one too, the third fragment of the detail of the previous one. When you click on the first list, the id is passed through the intent and the second list opens. Then, when you click on the second list, the id (but already another) is also transmitted through the intent and the third (detailed) activity is opened. When you press the UP Button (in the upper left corner) from the third fragment - the application crashes. In Stacktrace NullPointer Exception - there is no id for the second activity (parent to the third). Although when you click Back Button, everything is displayed and working fine. How can I get this id from parental activity and how to insert it back when pressing UP Button?

We start the parent

public void onClick(View view){ int position = getAdapterPosition(); if (position != RecyclerView.NO_POSITION){ Department department = mDepartments.get(position); int deptId = department.getId(); Bundle bundle = new Bundle(); bundle.putInt(DEPARTMENT_ID, deptId); Intent intent = new Intent(mContext, CoworkersActivity.class); intent.putExtras(bundle); mContext.startActivity(intent); } 

Parent activity:

 @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_coworkers); if (savedInstanceState == null){ CoworkersFragment fragment = CoworkersFragment .newInstance(getIntent().getExtras().getInt(DepartmentAdapter.ViewHolder.DEPARTMENT_ID)); getSupportFragmentManager().beginTransaction() .add(R.id.coworkers_container, fragment) .commit(); } } 

We start from the adapter of the parent activity detailed with a fragment

  public void onClick(View v) { int position = getAdapterPosition(); if (position != RecyclerView.NO_POSITION){ Employee employee = mEmployees.get(position); Bundle bundle = new Bundle(); bundle.putSerializable(ARG_EMPLOYEE, employee); Intent intent = new Intent(mContext, DetailActivity.class); intent.putExtras(bundle); mContext.startActivity(intent); } } 
  • You have an Employee object in the Bundle , and you get the value using the getInt(...) method. - post_zeew
  • And why you do not use directly the method Intent.putExtra(String name, Serializable value) ? - post_zeew
  • Not quite clearly described, added a bit of code - ZolkiBy
  • NPE on which line? - post_zeew
  • .newInstance(getIntent().getExtras().getInt(DepartmentAdapter.ViewHolder.DEPARTMENT_ID)); - ZolkiBy

1 answer 1

each time you press the UP button, a new instance activity without parameters was created, which provoked the NPE, in order for the activity to open in the state it was in, you need to prescribe the android:launchMode="singleTop" attribute in the manifest android:launchMode="singleTop"