1

I'm new to android programming and I have a problem in displaying data from firestore. I want to display the data in fragments in the navigation drawer. I found tutorials that display it on activities but nothing in fragments. Please help me with this.

public class MainActivity extends AppCompatActivity {

Toolbar toolbar;
DrawerLayout drawerLayout;
ActionBarDrawerToggle actionBarDrawerToggle;
NavigationView navigationView;
FragmentTransaction fragmentTransaction;
private boolean shouldLoadProductFragOnBackPress = false;
public static int navItemIndex = 0;
public FirebaseAuth mAuth;
FirebaseFirestore db = FirebaseFirestore.getInstance();
private void Load_Product_fragment() {
    navItemIndex = 0;
    fragmentTransaction = getSupportFragmentManager().beginTransaction();
    fragmentTransaction.replace(R.id.maincontainer,new ProductFragment());
    fragmentTransaction.commit();
    getSupportActionBar().setTitle(R.string.Productfragment_Title);
    drawerLayout.closeDrawers();


}
private void Load_Service_fragment(){
    navItemIndex = 1;
    fragmentTransaction = getSupportFragmentManager().beginTransaction();
    fragmentTransaction.replace(R.id.maincontainer,new ServiceFragment());
    fragmentTransaction.commit();
    getSupportActionBar().setTitle(R.string.Servicefragmnet_Title);
    drawerLayout.closeDrawers();
    shouldLoadProductFragOnBackPress = true;

}
private void Load_Account_fragment(){
    navItemIndex = 2;
    fragmentTransaction = getSupportFragmentManager().beginTransaction();
    fragmentTransaction.replace(R.id.maincontainer,new AccountFragment());
    fragmentTransaction.commit();
    getSupportActionBar().setTitle(R.string.Accountfragment_Title);
    drawerLayout.closeDrawers();
    shouldLoadProductFragOnBackPress = true;

}

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    toolbar=(Toolbar)findViewById(R.id.Toolbar_Layout);
    setSupportActionBar(toolbar);
    drawerLayout=(DrawerLayout) findViewById(R.id.Drawer_Layout);
    actionBarDrawerToggle = new ActionBarDrawerToggle(this,drawerLayout,toolbar,R.string.drawer_open,R.string.drawer_close);
    drawerLayout.addDrawerListener(actionBarDrawerToggle);

    drawerLayout.openDrawer(Gravity.LEFT);

    Load_Product_fragment();

    navigationView= findViewById(R.id.Navigation_View);
    navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
        @Override
        public boolean onNavigationItemSelected(@NonNull MenuItem item) {
            switch (item.getItemId())
            {
                case R.id.Productsfragment_ND:
                    Load_Product_fragment();
                    item.setChecked(true);
                    break;

                case R.id.Servicefragment_ND:
                    Load_Service_fragment();
                    item.setChecked(true);
                    break;

                case R.id.Accountfragemnt_ND:
                    Load_Account_fragment();
                    item.setChecked(true);
                    break;
            }
            return false;
        }
    });
}

@Override
public void onBackPressed() {
    if (drawerLayout.isDrawerOpen(GravityCompat.START)) {
        drawerLayout.closeDrawers();
        return;
    }

    // This code loads home fragment when back key is pressed
    // when user is in other fragment than home
    if (shouldLoadProductFragOnBackPress) {
        // checking if user is on other navigation menu
        // rather than home
        if (navItemIndex !=0) {
            navItemIndex = 0;
            shouldLoadProductFragOnBackPress = false;
            Load_Product_fragment();


            return;
        }
    }

    super.onBackPressed();
}




@Override
protected void onPostCreate(@Nullable Bundle savedInstanceState) {
    super.onPostCreate(savedInstanceState);
    actionBarDrawerToggle.syncState();
}

public void del(View view) {db.collection("products").document("test")
        .delete()
        .addOnSuccessListener(new OnSuccessListener<Void>() {
            @Override
            public void onSuccess(Void aVoid) {

            }
        })
        .addOnFailureListener(new OnFailureListener() {
            @Override
            public void onFailure(@NonNull Exception e) {

            }
        });

}
}

This is my main-activity.It contains the requirements for a navigation drawer for 3 fragments.I have a Firestore database linked to the app. I need to display the contents of the database in these fragments.

  • Next i will show one fragment and the recyclerview adapter and view holder i have tried using.
  • I am not sure if it is the correct way to do it.Please help me with this

    public class ProductFragment extends Fragment {
    
    private static final String TAG = ProductFragment.class.getSimpleName();
    private RecyclerView recipeRecyclerview;
    private LinearLayoutManager linearLayoutManager;
    private Product_adapter mAdapter;
    private DatabaseReference mDatabaseRef;
    private DatabaseReference childRef;
    
    public ProductFragment() {
    // Required empty public constructor
    }
    
    
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    
    // Inflate the layout for this fragment
    View view = inflater.inflate    (R.layout.fragment_product, container, false);
    
    
    getActivity().setTitle(getString(R.string.Productfrag_title));
    linearLayoutManager = new LinearLayoutManager(getActivity());
    recipeRecyclerview = view.findViewById(R.id.List_recycleview);
    recipeRecyclerview.setHasFixedSize(true);
    mDatabaseRef = FirebaseDatabase.getInstance().getReference();
    childRef = mDatabaseRef.child("recipes");
    
    
    mAdapter = new Product_adapter(Product_response.class, R.layout.list_layout, View_holder.class, childRef, getContext());
    recipeRecyclerview.setLayoutManager(linearLayoutManager);
    recipeRecyclerview.setAdapter(mAdapter);
    return view;
    

    } } This is my products-fragment. I have tried to add the recycler view.

Adapter

     public class Product_adapter extends RecyclerView.Adapter {

FirebaseFirestore db = FirebaseFirestore.getInstance();

private Context context;

Query query = db.collection("products");

FirestoreRecyclerOptions<Product_response> response = new FirestoreRecyclerOptions.Builder<Product_response>()
        .setQuery(query, Product_response.class)
        .build();


FirestoreRecyclerAdapter adapter = new FirestoreRecyclerAdapter<Product_response, View_holder>(response) {

    @Override
    protected void onBindViewHolder(View_holder holder, int position, Product_response model) {

    }

    @Override
    public View_holder onCreateViewHolder(ViewGroup group, int i) {
        // Create a new instance of the ViewHolder, in this case we are using a custom
        // layout called R.layout.message for each item
        View view = LayoutInflater.from(group.getContext())
                .inflate(R.layout.list_layout, group, false);

        return new View_holder(view);
    }





};

public Product_adapter(Class<Product_response> product_responseClass, int list_layout, Class<View_holder> view_holderClass, DatabaseReference childRef, Context context) {
}


@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    return null;
}

@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {

}

@Override
public int getItemCount() {
    return 0;
}
}

View holder

    public class View_holder extends RecyclerView.ViewHolder{

private static final String TAG = View_holder.class.getSimpleName();
public TextView main_text, subtext ;
public ImageView image;

public View_holder(View itemView) {
    super(itemView);
    main_text = (TextView)itemView.findViewById(R.id.List_maintext);
    subtext = (TextView)itemView.findViewById(R.id.List_subtext);
    image = (ImageView)itemView.findViewById(R.id.List_imageview);
}
}
  • Next i will show the response page where i used the getter and setter for the firebase

    import com.google.firebase.firestore.IgnoreExtraProperties;
    
    @IgnoreExtraProperties
    public class Product_response {
    
    private String Product;
    private String Cost;
    
    public Product_response() {
    }
    
    public Product_response(String Product, String Cost){
    
    this.Product= Product;
    this.Cost= Cost;
    }
    
    public String getProduct() {
    return Product;
    }
    
    public void setProduct(String Product) {
    this.Product = Product;
    }
    
    public String getCost(){
    return Cost;
    }
    
     public void setCost(String Cost)
     {
    this.Cost = Cost;
    }
    
    }
    

    This is how my database looks like. I need to display this products in my fragment

This is the github link of the app. Please help me complete this

sibin
  • 107
  • 9
  • Your question is too broad. Please be more specific and also paste some code examples that illustrate your problem. – m_____z Dec 23 '17 at 18:46
  • @m_____z I have added my main activity , fragment and the adapter for recyclerview. I'am not sure if any of that is correct. But the app doesnot crash but doesn't show any contents form the firestore database. Please help – sibin Dec 26 '17 at 07:22
  • **[This](https://stackoverflow.com/questions/49277797/how-to-display-data-from-firestore-in-a-recyclerview-with-android/49277842)** is how it can be done in an activity. Simmilar can be done in a fragment. – Alex Mamo Mar 14 '18 at 12:43

0 Answers0