I am new in Android Studio. I have a Navigation Drawer and I am trying to call an activity which is not a fragment activity and I am confused about it. I want to call the RecipeActivity to add in the Navigation Drawer but that activity extends AppCompatActivity and not a Fragment. How can I fix this?
RecipeActivity.java
public class RecipeActivity extends AppCompatActivity {
List<Recipe> listRecipe;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_recipe);
RecyclerView myRv = (RecyclerView) findViewById(R.id.recyclerview_id);
RecyclerViewAdapter myAdapter = new RecyclerViewAdapter(this, listRecipe);
myRv.setLayoutManager(new GridLayoutManager(this, 2));
myRv.setAdapter(myAdapter);
}
}
The HomePage.java contains the navigation drawer code
public class HomePage extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {
private DrawerLayout drawer;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home_page);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
drawer = findViewById(R.id.drawer_layout);
NavigationView navigationView = findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, drawer, toolbar,
R.string.navigation_draw_open, R.string.navigation_draw_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
if (savedInstanceState == null){
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
new HomeFragment()).commit();
navigationView.setCheckedItem((R.id.nav_home));
}
}
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {
switch(item.getItemId()){
case R.id.nav_home:
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
new HomeFragment()).commit();
break;
case R.id.nav_recipe:
//startActivity(new Intent(HomePage.this, RecipeActivity.class));
startActivity(new Intent(getActivity(), RecipeActivity.class));
//getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
// new RecipeActivity()).commit();
// Intent newIntent = new Intent(HomePage.this, RecipeActivity.class);
// startActivity(newIntent);
break;
case R.id.nav_logout:
Toast.makeText(this, "Logged out", Toast.LENGTH_SHORT).show();
break;
}
drawer.closeDrawer(GravityCompat.START);
return true;
}
@Override
public void onBackPressed() {
if (drawer.isDrawerOpen(GravityCompat.START)){
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
super.onBackPressed();
}
}
Thank you.
CodePudding user response:
Change your
startActivity(new Intent(getActivity(), RecipeActivity.class));
to startActivity(new Intent(HomePage.this, RecipeActivity.class));
And make sure that all the Activities are added in the AndroidManifest.xml