The app crashes while accessing the RecyclerView - java

Error msg :
( - Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void androidx.recyclerview.widget.RecyclerView.setHasFixedSize(boolean)' on a null object reference)
The app crashes while accessing this RecyclerView :
if (!type.equals("Admin"))
{
userNameTextView.setText(Prevalent.currentOnlineUser.getName());
Picasso.get().load(Prevalent.currentOnlineUser.getImage()).placeholder(R.drawable.profile).into(profileImageView);
}
recyclerView = (RecyclerView) findViewById(R.id.recycler_menu);
recyclerView.setHasFixedSize(true);
layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
}
and this is the RecyclerView :
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/recycler_menu"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scrollbars="vertical"/>
The Java Class :
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
recyclerView = (RecyclerView) findViewById(R.id.recycler_menu) ;
Intent intent = getIntent();
Bundle bundle = intent.getExtras();
if (bundle != null)
{
type = getIntent().getExtras().get("Admin").toString();
}
ProductsRef = FirebaseDatabase.getInstance().getReference().child("Products");
Paper.init(this);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
toolbar.setTitle("Home");
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view)
{
if (!type.equals("Admin"))
{
Intent intent = new Intent(HomeActivity.this, CartActivity.class);
startActivity(intent);
}
}
});
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
View headerView = navigationView.getHeaderView(0);
TextView userNameTextView = headerView.findViewById(R.id.user_profile_name);
CircleImageView profileImageView = headerView.findViewById(R.id.user_profile_image);
if (!type.equals("Admin"))
{
userNameTextView.setText(Prevalent.currentOnlineUser.getName());
Picasso.get().load(Prevalent.currentOnlineUser.getImage()).placeholder(R.drawable.profile).into(profileImageView);
}
recyclerView = (RecyclerView) findViewById(R.id.recycler_menu);
recyclerView.setHasFixedSize(true);
layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
}
#Override
protected void onStart()
{
super.onStart();
FirebaseRecyclerOptions<Products> options =
new FirebaseRecyclerOptions.Builder<Products>()
.setQuery(ProductsRef, Products.class)
.build();
FirebaseRecyclerAdapter<Products, ProductViewHolder> adapter =
new FirebaseRecyclerAdapter<Products, ProductViewHolder>(options) {
#Override
protected void onBindViewHolder(#NonNull ProductViewHolder holder, int position, #NonNull final Products model)
{
holder.txtProductName.setText(model.getPname());
holder.txtProductDescription.setText(model.getDescription());
holder.txtProductPrice.setText("Price = " + model.getPrice() + "$");
Picasso.get().load(model.getImage()).into(holder.imageView);
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view)
{
if (type.equals("Admin"))
{
Intent intent = new Intent(HomeActivity.this, AdminMaintainProductsActivity.class);
intent.putExtra("pid", model.getPid());
startActivity(intent);
}
else
{
Intent intent = new Intent(HomeActivity.this, ProductDetailsActivity.class);
intent.putExtra("pid", model.getPid());
startActivity(intent);
}
}
});
}
#NonNull
#Override
public ProductViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType)
{
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.product_items_layout, parent, false);
ProductViewHolder holder = new ProductViewHolder(view);
return holder;
}
};
recyclerView.setAdapter(adapter);
adapter.startListening();
}

I can see that your code has no problem. So I think you are putting the wrong layout in setContentView()
OR if this is not the case, just make sure that there is really a RecyclerView with the specified id in your layout.
If you are sure, just invalidate cache & restart and build again

Related

Fragment recyclerview on click to open another fragment

Below is the code for my adapter
DashboardAdapter.java
public class DashboardAdapter extends RecyclerView.Adapter<DashboardAdapter.DashviewHolder> {
ArrayList<DashModel> dashHolder;
private LayoutInflater layoutInflater;
public DashboardAdapter(ArrayList<DashModel> dashHolder) {
this.dashHolder = dashHolder;
}
#NonNull
#Override
public DashviewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.dash_layout, parent, false);
return new DashviewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull DashviewHolder holder, int position) {
holder.dashImg.setImageResource(dashHolder.get(position).getImage());
holder.header.setText(dashHolder.get(position).getHeader());
holder.desc.setText(dashHolder.get(position).getDesc());
}
#Override
public int getItemCount() {
return dashHolder.size();
}
class DashviewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
ImageView dashImg;
TextView header, desc;
public DashviewHolder(#NonNull View itemView) {
super(itemView);
dashImg = itemView.findViewById(R.id.dash_slide_img);
header = itemView.findViewById(R.id.dash_slide_txt1);
desc = itemView.findViewById(R.id.dash_slide_txt2);
itemView.setOnClickListener(this);
}
#Override
public void onClick(View v) {
final Fragment fm;
switch (getLayoutPosition()) {
case 0:
fm = new SavingsFragment();
break;
case 1:
fm = new TargetFragment();
break;
case 2:
fm = new InvestFragment();
break;
}
}
}
}
DashboardFragment.java
public class DashboardFragment extends Fragment {
private RecyclerView recyclerView;
ArrayList<DashModel> dashDataHolder;
private View view;
private DashboardAdapter dashboardAdapter;
private FragmentManager fm;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
view = inflater.inflate(R.layout.fragment_dashboard, container, false);
recyclerView = view.findViewById(R.id.dash_slider_layout);
recyclerView.setLayoutManager(new LinearLayoutManager(getContext(), LinearLayoutManager.HORIZONTAL, false));
dashDataHolder = new ArrayList<>();
DashModel ob1 = new DashModel(R.drawable.ic_savings, R.string.first_slide_dash, R.string.first_slide_dash_amt);
dashDataHolder.add(ob1);
DashModel ob2 = new DashModel(R.drawable.ic_savings, R.string.second_slide_dash, R.string.second_slide_dash_amt);
dashDataHolder.add(ob2);
DashModel ob3 = new DashModel(R.drawable.ic_savings, R.string.third_slide_dash, R.string.third_slide_dash_amt);
dashDataHolder.add(ob3);
recyclerView.setAdapter(new DashboardAdapter(dashDataHolder));
//fm.getFragmentManager().beginTransaction().replace(R.id.fragment_container,getTargetFragment(),"New Fragment").commit();
return view;
}
}
Then the code for my main activity that has both drawer and bottom navigation
public class RetailerDashboard extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
private static final String TAG = RetailerDashboard.class.getSimpleName();
ChipNavigationBar chipNavigationBar;
DrawerLayout drawerLayout;
Toolbar toolbar;
NavigationView navigationView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_retailer_dashboard);
/*--------------------HOOKS----------------------*/
drawerLayout = findViewById(R.id.drawer_layout);
navigationView = findViewById(R.id.nav_view);
toolbar = findViewById(R.id.toolbar);
chipNavigationBar = findViewById(R.id.bottom_bar);
/*--------------------BOTTOM MENU----------------------*/
chipNavigationBar.setItemSelected(R.id.menu_home, true);
getSupportFragmentManager().beginTransaction()
.replace(R.id.fragment_container, new DashboardFragment()).commit();
bottomMenu();
/*--------------------TOOLBAR----------------------*/
setSupportActionBar(toolbar);
/*--------------------NAVIGATION DRAWER MENU----------------------*/
navigationView.bringToFront();
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this,
drawerLayout,
toolbar,
R.string.navigation_drawer_open,
R.string.navigation_drawer_close);
toggle.syncState();
navigationView.setNavigationItemSelectedListener(this);
}
private void bottomMenu() {
chipNavigationBar.setOnItemSelectedListener(new ChipNavigationBar.OnItemSelectedListener() {
#Override
public void onItemSelected(int id) {
Fragment fragment = null;
switch (id) {
case R.id.menu_saving:
fragment = new SavingsFragment();
break;
case R.id.menu_home:
fragment = new DashboardFragment();
break;
case R.id.menu_target:
fragment = new TargetFragment();
break;
}
if (fragment != null) {
getSupportFragmentManager().beginTransaction()
.replace(R.id.fragment_container, fragment).commit();
} else {
Log.e(TAG, "Error in creating fragment");
}
}
});
}
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.nav_profile:
Intent accountIntent = new Intent(RetailerDashboard.this, Profile.class);
startActivity(accountIntent);
break;
case R.id.nav_account_balnce:
Intent balanceIntent = new Intent(RetailerDashboard.this, AccountBalance.class);
startActivity(balanceIntent);
break;
case R.id.nav_notifications:
Intent notifIntent = new Intent(RetailerDashboard.this, Notifications.class);
startActivity(notifIntent);
break;
case R.id.nav_settings:
Intent settingsIntent = new Intent(RetailerDashboard.this, Settings.class);
startActivity(settingsIntent);
break;
case R.id.nav_chat:
Intent chatIntent = new Intent(RetailerDashboard.this, Chat.class);
startActivity(chatIntent);
break;
case R.id.nav_faq:
Intent helpIntent = new Intent(RetailerDashboard.this, FAQ.class);
startActivity(helpIntent);
break;
}
drawerLayout.closeDrawer(GravityCompat.START);
return true;
}
#Override
public void onBackPressed() {
if (drawerLayout.isDrawerOpen(GravityCompat.START)) {
drawerLayout.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
finishAffinity();
}
}
}

Troubles navigation between fragment

I have been investigating for like 4 hours about this problem, but I didnt get any help.
On summary, I am trying to navigate between fragments in Android Studio, using Navigation View. I want to go from Home Fragment to Services Fragment.
The first Home Fragment always load, but when I click on Services item, the fragment Services load, but the data from Home always keeps on the fragment too.
This is my code:
HOME FRAGMENT CLASS
public class HomeFragment extends Fragment {
private HomeViewModel homeViewModel;
private PieChart pieChart;
private UserService userService;
private Calendar calendar;
public View onCreateView(#NonNull LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
homeViewModel = ViewModelProviders.of(this).get(HomeViewModel.class);
View root = inflater.inflate(R.layout.fragment_home, container, false);
pieChart = root.findViewById(R.id.pieChart);
userService = UserRepository.getUserService();
getData();
return root;
}
private void getData(){
calendar = Calendar.getInstance();
int month = calendar.get(Calendar.MONTH)+1;
Log.i("INT MONTH", String.valueOf(month));
userService.getHoursPerService(String.valueOf(UserCache.empleado.getId_emp()),String.valueOf(month)).enqueue(new Callback<List<Servicio>>() {
#Override
public void onResponse(Call<List<Servicio>> call, Response<List<Servicio>> response) {
if(response.body().size() == 0){
pieChart.setNoDataText("Sin horas actuales.");
pieChart.setNoDataTextColor(ContextCompat.getColor(getContext(), R.color.colorPrimaryDark));
pieChart.invalidate();
}else{
List<Servicio> list = response.body();
List<PieEntry> pieEntries = new ArrayList<>();
for(int cont=0;cont<list.size();cont++){
pieEntries.add(new PieEntry(list.get(cont).getTotalHoras(), list.get(cont).getLugarServicio()));
}
SimpleDateFormat sdf = new SimpleDateFormat("MMMM");
String actual_month = sdf.format(calendar.getTime());
PieDataSet dataSet = new PieDataSet(pieEntries, getResources().getString(R.string.txt_hours_of)+" "+actual_month);
dataSet.setSliceSpace(3f);
dataSet.setSelectionShift(5f);
dataSet.setColors(ColorTemplate.MATERIAL_COLORS);
PieData data = new PieData(dataSet);
data.setValueTextSize(10f);
data.setValueTextColor(ContextCompat.getColor(getContext(), R.color.colorPrimaryDark));
pieChart.getDescription().setEnabled(true);
pieChart.getDescription().setText(getResources().getString(R.string.txt_hours_of)+" "+actual_month+".");
pieChart.getDescription().setTextSize(12f);
pieChart.getDescription().setTextColor(ContextCompat.getColor(getContext(), R.color.colorPrimaryDark));
pieChart.setExtraOffsets(5, 10, 5, 5);
pieChart.setDragDecelerationFrictionCoef(0.99f);
pieChart.setDrawHoleEnabled(true);
pieChart.setHoleColor(Color.WHITE);
pieChart.setTransparentCircleRadius(61f);
pieChart.animateY(2000, Easing.EaseInOutCubic);
pieChart.setEntryLabelColor(ContextCompat.getColor(getContext(),R.color.colorPrimaryDark));
pieChart.setData(data);
pieChart.invalidate();
}
}
#Override
public void onFailure(Call<List<Servicio>> call, Throwable t) {
}
});
}
}
SERVICES FRAGMENT CLASS
public class ServicesFragment extends Fragment {
private ServicesViewModel servicesViewModel;
public View onCreateView(#NonNull LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
servicesViewModel = ViewModelProviders.of(this).get(ServicesViewModel.class);
View root = inflater.inflate(R.layout.fragment_myservices, container, false);
final TextView textView = root.findViewById(R.id.text_gallery);
servicesViewModel.getText().observe(this, new Observer<String>() {
#Override
public void onChanged(#Nullable String s) {
textView.setText(s);
}
});
return root;
}
}
MAIN ACTIVITY
public class MainActivityView extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {
private AppBarConfiguration mAppBarConfiguration;
private NavigationView navigationView;
private ActionBarDrawerToggle toggle;
private TextView userNameNav;
private TextView userEmailNav;
private DrawerLayout drawer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_view);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
/*FloatingActionButton fab = findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});*/
drawer = findViewById(R.id.drawer_layout);
navigationView = findViewById(R.id.nav_view);
// Passing each menu ID as a set of Ids because each
// menu should be considered as top level destinations.
mAppBarConfiguration = new AppBarConfiguration.Builder(
R.id.nav_home, R.id.nav_myservices, R.id.nav_startservice)
.setDrawerLayout(drawer)
.build();
NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
NavigationUI.setupActionBarWithNavController(this, navController, mAppBarConfiguration);
NavigationUI.setupWithNavController(navigationView, navController);
View headerView = navigationView.getHeaderView(0);
navigationView.setNavigationItemSelectedListener(this);
userNameNav = headerView.findViewById(R.id.userNameNav);
userEmailNav = headerView.findViewById(R.id.userEmailNav);
userNameNav.setText(UserCache.empleado.getNombre()+" "+UserCache.empleado.getApellidos());
userEmailNav.setText(UserCache.empleado.getEmail());
navigationView.bringToFront();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main_activity_view, menu);
return true;
}
#Override
public boolean onSupportNavigateUp() {
NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
return NavigationUI.navigateUp(navController, mAppBarConfiguration)
|| super.onSupportNavigateUp();
}
#Override
public void onBackPressed() {
if(drawer.isDrawerOpen(GravityCompat.START)){
drawer.closeDrawer(GravityCompat.START);
}else{
AlertDialog.Builder alerta = new AlertDialog.Builder(this);
alerta.setTitle(getResources().getString(R.string.txt_dialog_exit_app));
alerta.setPositiveButton(getResources().getString(R.string.txt_yes_option), new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
finish();
}
});
alerta.setNegativeButton(getResources().getString(R.string.txt_no_option), new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
}
});
alerta.show();
}
}
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem menuItem) {
switch (menuItem.getItemId()){
case R.id.nav_home:
getSupportFragmentManager().popBackStack(null,FragmentManager.POP_BACK_STACK_INCLUSIVE);
getSupportFragmentManager().beginTransaction().replace(R.id.nav_host_fragment,new HomeFragment()).commit();
case R.id.nav_myservices:
getSupportFragmentManager().popBackStack(null,FragmentManager.POP_BACK_STACK_INCLUSIVE);
getSupportFragmentManager().beginTransaction().replace(R.id.nav_host_fragment, new ServicesFragment()).commit();
//NavHostFragment.findNavController(new ServicesFragment());
break;
case R.id.nav_startservice:
getSupportFragmentManager().popBackStack(null,FragmentManager.POP_BACK_STACK_INCLUSIVE);
getSupportFragmentManager().beginTransaction().replace(R.id.nav_host_fragment, new StartServiceFragment()).commit();
break;
}
drawer.closeDrawer(GravityCompat.START);
return true;
}
}
onNavigationItemSelected is where I do the navigation.
I tried everything, changing the ConstraintLayout to Relative, insert the fragments from xml into framelayout...
Also, I am using MVVM.
If more information is needed i can post here then.
PD: Sorry if I posting something wrong, this is my first time here.
SOLUTION: I forgot completly to break the first case onNavigationItemSelected.

my app running normally but when i am clicking cart button it takes me to first screen from where i started

I am making an online food ordering app.My app was running good but when i add cart code it is showing abnormal behaviour like the cart button takes me to first screen i started.following is the cart.java code
public class Cart extends AppCompatActivity {
RecyclerView recyclerView;
RecyclerView.LayoutManager layoutManager;
FirebaseDatabase database;
DatabaseReference requests;
TextView txtTotalPrice;
FButton btnPlace;
List<Order> cart=new ArrayList<>();
CartAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_cart);
//Firebase
database = FirebaseDatabase.getInstance();
requests = database.getReference("Requests");
//Init
recyclerView = (RecyclerView) findViewById(R.id.listCart);
recyclerView.setHasFixedSize(true);
layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
txtTotalPrice = (TextView) findViewById(R.id.total);
btnPlace =(FButton)findViewById(R.id.btnPlaceOrder);
btnPlace.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v) {
showAlertDialog();
}
});
loadlistfood();
}
private void showAlertDialog() {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(Cart.this);
alertDialog.setTitle("One more step!");
alertDialog.setMessage("Enter your Address: ");
final EditText edtAddress = new EditText(Cart.this);
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.MATCH_PARENT
);
edtAddress.setLayoutParams(lp);
alertDialog.setView(edtAddress);//add edt text to alert box
alertDialog.setIcon(R.drawable.ic_shopping_cart_black_24dp);
alertDialog.setPositiveButton("YES", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Request request = new Request(
Common.currentUser.getPhone(),
Common.currentUser.getName(),
edtAddress.getText().toString(),
txtTotalPrice.getText().toString(),
cart
);
//submit to firebase
//we will use system.currntMill to key
requests.child(String.valueOf(System.currentTimeMillis()))
.setValue(request);
//Delete cart
new Database(getBaseContext()).cleanCart();
Toast.makeText(Cart.this, "Thank you,Order placed", Toast.LENGTH_SHORT).show();
finish();
}
});
alertDialog.setNegativeButton("NO", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
alertDialog.show();
}
private void loadlistfood() {
cart=new Database(this).getCarts();
adapter=new CartAdapter(cart,this);
recyclerView.setAdapter(adapter);
//calculate price
int total=0;
for(Order order:cart)
total+=(Integer.parseInt(order.getPrice()))*(Integer.parseInt(order.getQuantity()));
Locale locale=new Locale("en","US");
NumberFormat fmt=NumberFormat.getCurrencyInstance(locale);
txtTotalPrice.setText(fmt.format(total));
}
Rest i had put a intent in where cart button is put and else i have cartAdapter class and request.java.If you need them i will edit the question.Please help me.
Here is code that take me to cart.java.
public class Home extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
FirebaseDatabase database;
DatabaseReference category;
TextView txtFullName;
RecyclerView recycler_menu;
RecyclerView.LayoutManager layoutManager;
FirebaseRecyclerAdapter<Category,MenuViewHolder> adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
toolbar.setTitle("Menu");
setSupportActionBar(toolbar);
//init firebase
database = FirebaseDatabase.getInstance();
category = database.getReference("Category");
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent cartIntent = new Intent(getApplicationContext(),Cart.class);
startActivity(cartIntent);
}
});
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
//set name for user
View headerView = navigationView.getHeaderView(0);
txtFullName = (TextView)headerView.findViewById(R.id.txtFullName);
txtFullName.setText(Common.currentUser.getName());
//Load menu
recycler_menu=(RecyclerView)findViewById(R.id.recycler_meu);
recycler_menu.setHasFixedSize(true);
layoutManager = new LinearLayoutManager(this);
recycler_menu.setLayoutManager(layoutManager);
loadMenu();
}
private void loadMenu() {
adapter=new FirebaseRecyclerAdapter<Category, MenuViewHolder>(Category.class,R.layout.menu_item,MenuViewHolder.class,category) {
#Override
protected void populateViewHolder(MenuViewHolder viewHolder, Category model, int position) {
viewHolder.txtMenuName.setText(model.getName());
Picasso.with(getBaseContext()).load(model.getImage())
.into(viewHolder.imageView);
final Category clickItem = model;
viewHolder.setItemClickListener(new ItemClickListener() {
#Override
public void onClick(View view, int position, boolean isLongClick) {
//Get category id and send to new Activity
Intent foodList=new Intent(Home.this,FoodList.class);
foodList.putExtra("CategoryId",adapter.getRef(position).getKey());
startActivity(foodList);
}
});
}
};
recycler_menu.setAdapter(adapter);
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.home, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
return super.onOptionsItemSelected(item);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_menu) {
// Handle the camera action
} else if (id == R.id.nav_cart) {
// Intent cartIntent = new Intent(Home.this,Cart.class);startActivity(cartIntent);
} else if (id == R.id.nav_orders) {
} else if (id == R.id.log_out) {
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
}
Thank you in advance

How to implement navigation activity and Recyclerview in MainActivity

I started off with a Navigation drawer activity and I added a recyclerView into the content_main.xml but I have been unable to implement the RecyclerView into the ManiActivity.java file.
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_camera) {
// Handle the camera action
} else if (id == R.id.nav_gallery) {
} else if (id == R.id.nav_slideshow) {
} else if (id == R.id.nav_manage) {
} else if (id == R.id.nav_share) {
} else if (id == R.id.nav_send) {
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
}
That is what my MainAcitity.java looks like when I haven't only implemented the NavigationView Activity.
public class MainActivity extends AppCompatActivity implements MyRecyclerViewAdapter.ItemClickListener {
MyRecyclerViewAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// data to populate the RecyclerView with
ArrayList<String> animalNames = new ArrayList<>();
animalNames.add("Horse");
animalNames.add("Cow");
animalNames.add("Camel");
animalNames.add("Sheep");
animalNames.add("Goat");
// set up the RecyclerView
RecyclerView recyclerView = (RecyclerView) findViewById(R.id.rvAnimals);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
adapter = new MyRecyclerViewAdapter(this, animalNames);
adapter.setClickListener(this);
recyclerView.setAdapter(adapter);
}
#Override
public void onItemClick(View view, int position) {
Toast.makeText(this, "You clicked " + adapter.getItem(position) + " on row number " + position, Toast.LENGTH_SHORT).show();
}
}
And I also need this(the recyclerview) into my MainActivity.java There isn't room for both
This code below is my adapter class and the whole struggle is to add this to the MainActivity.java
public class MyRecyclerViewAdapter extends RecyclerView.Adapter<MyRecyclerViewAdapter.ViewHolder> {
private List<String> mData = Collections.emptyList();
private LayoutInflater mInflater;
private ItemClickListener mClickListener;
// data is passed into the constructor
public MyRecyclerViewAdapter(Context context, List<String> data) {
this.mInflater = LayoutInflater.from(context);
this.mData = data;
}
// inflates the row layout from xml when needed
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = mInflater.inflate(R.layout.recyclerview_row, parent, false);
ViewHolder viewHolder = new ViewHolder(view);
return viewHolder;
}
// binds the data to the textview in each row
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
String animal = mData.get(position);
holder.myTextView.setText(animal);
}
// total number of rows
#Override
public int getItemCount() {
return mData.size();
}
// stores and recycles views as they are scrolled off screen
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
public TextView myTextView;
public ViewHolder(View itemView) {
super(itemView);
myTextView = (TextView) itemView.findViewById(R.id.tvAnimalName);
itemView.setOnClickListener(this);
}
#Override
public void onClick(View view) {
if (mClickListener != null) mClickListener.onItemClick(view, getAdapterPosition());
}
}
// convenience method for getting data at click position
public String getItem(int id) {
return mData.get(id);
}
// allows clicks events to be caught
public void setClickListener(ItemClickListener itemClickListener) {
this.mClickListener = itemClickListener;
}
// parent activity will implement this method to respond to click events
public interface ItemClickListener {
void onItemClick(View view, int position);
}
}
You need to implement both NavigationView.OnNavigationItemSelectedListener and MyRecyclerViewAdapter.ItemClickListener interfaces on the MainActivity class. This way you would be able to call the adapter class for the Recycler view.Your code should look like this:
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener, MyRecyclerViewAdapter.ItemClickListener {
MyRecyclerViewAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
// data to populate the RecyclerView with
ArrayList<String> animalNames = new ArrayList<>();
animalNames.add("Horse");
animalNames.add("Cow");
animalNames.add("Camel");
animalNames.add("Sheep");
animalNames.add("Goat");
// set up the RecyclerView
RecyclerView recyclerView = (RecyclerView) findViewById(R.id.rvAnimals);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
adapter = new MyRecyclerViewAdapter(this, animalNames);
adapter.setClickListener(this);
recyclerView.setAdapter(adapter);
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_camera) {
// Handle the camera action
} else if (id == R.id.nav_gallery) {
} else if (id == R.id.nav_slideshow) {
} else if (id == R.id.nav_manage) {
} else if (id == R.id.nav_share) {
} else if (id == R.id.nav_send) {
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
#Override
public void onItemClick(View view, int position) {
Toast.makeText(this, "You clicked " + adapter.getItem(position) + " on row number " + position, Toast.LENGTH_SHORT).show();
}
}
In Java, a class can implement more than one interfaces and a class can only extend from one parent. Implementation of more than one interfaces eliminates multiple inheritance which is not allowed in Java.
For example:
ClassA implements ClassB, ClassC
Your edited code can be found here
Problem seems to be associated with Adapter class. I would like to see your code for adapter.
1. Make sure if count is not equal to zero.
2. Make sure you are inflating a proper view in adapter class.
3. The view you are inflating must have external layout Relative or Linear or Constraint.
public class HomeActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener{
TabLayout tabLayout;
ViewPager viewPager;
NavigationView navigationView;
View navHeaderView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
navHeaderView = navigationView.getHeaderView(0);
viewPager = (ViewPager) findViewById(R.id.viewPagerContainer);
tabLayout = (TabLayout) findViewById(R.id.tabLayout);
textViewNavigationName = (TextView)
navHeaderView.findViewById(R.id.textViewNavigationName);
textViewNavigationEmail = (TextView)
navHeaderView.findViewById(R.id.textViewNavigationEmail);
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction =
fragmentManager.beginTransaction();
Fragment_Home objFragment1 = new Fragment_Home();
fragmentTransaction.add(R.id.viewPagerContainer, objFragment1).addToBackStack("backkkkkkkkkkkkk");
fragmentTransaction.commit();
}
}
public class Fragment_Home extends Fragment
{
private static final String ARG_PAGE_KEY = "arg_page";
String nextPageToken;
String prevPageToken;
String pageToken;
int sizeOfPlaylist;
int sizeOfCurrentList;
int firstItemPosition;
MenuItem nextItem;
MenuItem lastItem;
LinearLayout linearLayoutProgress, linearLayoutNoConnection;
Button buttonReload;
RecyclerView recyclerViewVideos;
AllVideosAdapterR adapter;
TextView textViewProgress;
public static Fragment_Home newInstance(int pageNumber) {
Fragment_Home myFragment = new Fragment_Home();
Bundle arguments = new Bundle();
arguments.putInt(ARG_PAGE_KEY, pageNumber);
myFragment.setArguments(arguments);
return myFragment;
}
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
setHasOptionsMenu(true);
LayoutInflater inflater1 = (LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = inflater1.inflate(R.layout.fragment_home, container, false);
getActivity().invalidateOptionsMenu();
findControls(view);
gettingList();
buttonReload.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
gettingList();
}
});
return view;
}
public void findControls(View view)
{
recyclerViewVideos = (RecyclerView)view.findViewById(R.id.recyclerViewVideos);
linearLayoutProgress = (LinearLayout)view. findViewById(R.id.linearLayoutProgress);
textViewProgress = (TextView) view.findViewById(R.id.textViewProgress);
linearLayoutProgress.setVisibility(View.INVISIBLE);
linearLayoutNoConnection = (LinearLayout)view.findViewById(R.id.linearLayoutNoConnection);
linearLayoutNoConnection.setVisibility(View.INVISIBLE);
buttonReload = (Button)view.findViewById(R.id.buttonReload);
}
private boolean isDeviceOnline() {
ConnectivityManager connMgr =
(ConnectivityManager)getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
return (networkInfo != null && networkInfo.isConnected());
}
public void setAdapter(List<Item> listItems) {
recyclerViewVideos.setLayoutManager(new
LinearLayoutManager(getActivity()));
adapter = new AllVideosAdapterR(getActivity(), listItems);
recyclerViewVideos.setAdapter(adapter);
}
public void showProgress(String message) {
textViewProgress.setText(message);
linearLayoutProgress.setVisibility(View.VISIBLE);
}
public void stopProgress() {
linearLayoutProgress.setVisibility(View.INVISIBLE);
}
public void gettingList() {
if (!isDeviceOnline()) {
linearLayoutNoConnection.setVisibility(View.VISIBLE);
} else {
linearLayoutNoConnection.setVisibility(View.INVISIBLE);
}
showProgress("Loading videos..");
Retrofit retrofit = newRetrofit.Builder().baseUrl(BaseUrls.BASE_URL).addConverterFactory(GsonConverterFactory.create()).build();
WebApis call1 = retrofit.create(WebApis.class);
Call<ListResponse> call = call1.requestList();
call.enqueue(new Callback<ListResponse>() {
#Override
public void onResponse(Call<ListResponse> call, Response<ListResponse> response) {
System.out.println("size....................." + response.body().getItems().size());
setAdapter(response.body().getItems());
sizeOfPlaylist = response.body().getPageInfo().getTotalResults();
try {
nextPageToken = response.body().getNextPageToken();
prevPageToken = response.body().getPrevPageToken();
firstItemPosition = response.body().getItems().get(0).getSnippet().getPosition();
sizeOfCurrentList = response.body().getItems().size();
} catch (Exception e) {
Toast.makeText(getActivity(), "More pages not available", Toast.LENGTH_SHORT).show();
}
stopProgress();
}
#Override
public void onFailure(Call<ListResponse> call, Throwable t) {
stopProgress();
Toast.makeText(getActivity(), "Check your Network connection", Toast.LENGTH_LONG).show();
linearLayoutNoConnection.setVisibility(View.VISIBLE);
}
});
}
public void gettingNextList(String token) {
showProgress("Loading videos..");
Retrofit retrofit = new Retrofit.Builder().baseUrl(BaseUrls.BASE_URL).addConverterFactory(GsonConverterFactory.create()).build();
WebApis call1 = retrofit.create(WebApis.class);
Call<ListResponse> call = call1.requestNextList(token);
call.enqueue(new Callback<ListResponse>() {
#Override
public void onResponse(Call<ListResponse> call, Response<ListResponse> response) {
System.out.println("size....................." + response.body().getItems().size());
setAdapter(response.body().getItems());
try {
nextPageToken = response.body().getNextPageToken();
prevPageToken = response.body().getPrevPageToken();
firstItemPosition = response.body().getItems().get(0).getSnippet().getPosition();
sizeOfCurrentList = response.body().getItems().size();
} catch (Exception e) {
Toast.makeText(getActivity(), "More pages not available", Toast.LENGTH_SHORT).show();
}
stopProgress();
}
#Override
public void onFailure(Call<ListResponse> call, Throwable t) {
stopProgress();
Toast.makeText(getActivity(), "Network Problem", Toast.LENGTH_LONG).show();
}
});
}
public interface WebApis {
#GET(BaseUrls.GETTING_LIST)
Call<ListResponse> requestList();
#GET(BaseUrls.GETTING_LIST)
Call<ListResponse> requestNextList(#Query("pageToken") String pageToken);
}
}

How recreate or refresh fragment

i have fragment for display the NavigationDrawer. In that i have the first section the header with some information. This information change and with EventBus i control this event, but how can update this fragment?
The implementation below work only if i rotate the device.
extract from MainActivity:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_activity);
mNavigationNavDrawerFragment = (Nav_DrawerFragment) getFragmentManager().findFragmentById(R.id.fragment_drawer);
mNavigationNavDrawerFragment.setup(R.id.fragment_drawer, (DrawerLayout) findViewById(R.id.drawer), mToolbar);
inizialized(mServices);
}
....
....
EventBus.getDefault().postSticky(new PersonDetails(mNomeCognome, mEmail));
//HERE HOW CAN REFRESH OR RECREATE THIS mNavigationNavDrawerFragment?
}
Extract from Nav_DrawerFragment:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_navigation_drawer, container, false);
mDrawerList = (RecyclerView) view.findViewById(R.id.drawerList);
LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
mDrawerList.setLayoutManager(layoutManager);
mDrawerList.setHasFixedSize(true);
final List<NavigationItem> navigationItems = getMenu();
//HERE I SET THE UPDATE DATA
Nav_adapter adapter = new Nav_adapter(navigationItems,mNomeCognome,mEmail);
adapter.setNavigationDrawerCallbacks(this);
mDrawerList.setAdapter(adapter);
selectItem(mCurrentSelectedPosition,items);
return view;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
EventBus.getDefault().registerSticky(this);
}
public void onEventMainThread(PersonDetails event){
mNomeCognome = event.mNomeCognome;
mEmail = event.mEmail;
}
public void setup(int fragmentId, DrawerLayout drawerLayout, Toolbar toolbar) {
mFragmentContainerView = getActivity().findViewById(fragmentId);
mDrawerLayout = drawerLayout;
mActionBarDrawerToggle = new ActionBarDrawerToggle(getActivity(), mDrawerLayout, toolbar, R.string.drawer_open, R.string.drawer_close) {
#Override
public void onDrawerClosed(View drawerView) {
super.onDrawerClosed(drawerView);
if (!isAdded()) return;
getActivity().invalidateOptionsMenu();
}
#Override
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
if (!isAdded()) return;
getActivity().invalidateOptionsMenu();
}
};
I can see you're using a RecyclerView with the adapter
Nav_adapter adapter = new Nav_adapter(navigationItems,mNomeCognome,mEmail);
and then you're updating the values that were used to create the adapter on the event
mNomeCognome = event.mNomeCognome;
mEmail = event.mEmail;
the problem is that you didn't pass those values to the adapter.
So you'll have to create a way to pass those updated values to the existing adapter, something like this:
// first define your adapter as a field:
Nav_adapter adapter;
// then on your event
public void onEventMainThread(PersonDetails event){
mNomeCognome = event.mNomeCognome;
mEmail = event.mEmail;
adapter.setNewValues(mNomeCognome, mEmail);
}
then inside this setNewValues you update the adapter values and don't forget to call one of the notifyItemChanged or notifyItemRangeChanged method on the adapter so that the new value can be updated on the screen.

Categories

Resources