Can anyone help me with this firebase recycler view using fragments issue? I am having a problem with retrieving the data from firebase to my recycler view. I am using fragments and the app crashes everytime I run it.
Here's my code:
SubjecList.java
package com.google.myeclassrecordapp.mye_classrecord;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.firebase.ui.database.FirebaseRecyclerAdapter;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import org.w3c.dom.Text;
public class SubjectsList extends Fragment {
private View view;
private Context c;
private RecyclerView myTimeline;
private FirebaseDatabase databaseReference;
private DatabaseReference mFireDatabasaeRef;
private LinearLayoutManager mananger;
private RecyclerView mRecyclerView;
FirebaseRecyclerAdapter<ScheduleListAdapter, ViewHolder> firebaseRecyclerAdapter;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = LayoutInflater.from(container.getContext())
.inflate(R.layout.schedule_model, container, false);
mFireDatabasaeRef = FirebaseDatabase.getInstance().getReference().child("SubjectsList");
c = getContext();
mRecyclerView = (RecyclerView) view.findViewById(R.id.rcsched);
mananger = new LinearLayoutManager(c);
mRecyclerView.setHasFixedSize(true);
firebaseRecyclerAdapter = new FirebaseRecyclerAdapter<ScheduleListAdapter, ViewHolder>(
ScheduleListAdapter.class,
R.layout.schedule_model,
ViewHolder.class,
mFireDatabasaeRef
)
{
#Override
protected void populateViewHolder(ViewHolder viewHolder, ScheduleListAdapter model, int position) {
viewHolder.setSubjectCode(model.getSubjectCode());
viewHolder.setSection(model.getSection());
viewHolder.setTime(model.getTime());
viewHolder.setDay(model.getDay());
viewHolder.setRoom(model.getRoom());
}
};
mRecyclerView.setAdapter(firebaseRecyclerAdapter);
firebaseRecyclerAdapter.notifyDataSetChanged();
//mRecyclerView.setLayoutManager(mananger);
return view;
}
public static class ViewHolder extends RecyclerView.ViewHolder {
View mView;
public ViewHolder(View itemView) {
super(itemView);
mView = itemView;
}
public void setSubjectCode(String subjectcode){
TextView txtSubjectCode = (TextView) itemView.findViewById(R.id.txtsubjectcode);
txtSubjectCode.setText(subjectcode);
}
public void setSection(String section){
TextView txtSection = (TextView) itemView.findViewById(R.id.txtsection);
txtSection.setText(section);
}
public void setTime(String time){
TextView txtTime = (TextView) itemView.findViewById(R.id.txttime);
txtTime.setText(time);
}
public void setDay(String day){
TextView txtDay = (TextView) itemView.findViewById(R.id.txtday);
txtDay.setText(day);
}
public void setRoom(String room){
TextView txtRoom = (TextView) itemView.findViewById(R.id.txtroom);
txtRoom.setText(room);
}
}
}
ScheduleListAdapater.java
package com.google.myeclassrecordapp.mye_classrecord;
/**
* Created by Pau-Le on 5/12/17.
*/
public class ScheduleListAdapter {
private String SubjectCode;
private String Section;
private String Time;
private String Day;
private String Room;
public ScheduleListAdapter() {
}
public ScheduleListAdapter(String subjectCode, String section, String time, String day, String room) {
SubjectCode = subjectCode;
Section = section;
Time = time;
Day = day;
Room = room;
}
public String getSubjectCode() {
return SubjectCode;
}
public void setSubjectCode(String subjectCode) {
SubjectCode = subjectCode;
}
public String getSection() {
return Section;
}
public void setSection(String section) {
Section = section;
}
public String getTime() {
return Time;
}
public void setTime(String time) {
Time = time;
}
public String getDay() {
return Day;
}
public void setDay(String day) {
Day = day;
}
public String getRoom() {
return Room;
}
public void setRoom(String room) {
Room = room;
}
}
Related
I mixed things up. The initial error I had was this MainActivity.java:130: error: incompatible types: List<com.kuroniczstudio.splashscreen.CategoryItem> cannot be converted to List<com.kuroniczstudio.splashscreen.model.CategoryItem>
allCategoryList.add(new AllCategory(1,"VIP Hour", homeCatListItem1)); While try to fix it that was when things started getting confusing. So I am still having this error
MainActivity
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.viewpager.widget.ViewPager;
import android.os.Bundle;
import com.google.android.material.tabs.TabLayout;
import com.kuroniczstudio.splashscreen.adapter.BannerMoviesPagerAdapter;
import com.kuroniczstudio.splashscreen.adapter.MainRecyclerAdapter;
import com.kuroniczstudio.splashscreen.model.AllCategory;
import com.kuroniczstudio.splashscreen.model.BannerMovies;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
public class MainActivity extends AppCompatActivity {
BannerMoviesPagerAdapter bannerMoviesPagerAdapter;
TabLayout indicatorTab, categoryTab;
ViewPager bannerMoviesViewPager;
List<BannerMovies> homeBannerList;
List<BannerMovies> vipHourBannerList;
List<BannerMovies> prophecyBannerList;
List<BannerMovies> testimonyBannerList;
Timer sliderTimer;
MainRecyclerAdapter mainRecyclerAdapter;
RecyclerView mainRecycler;
List<AllCategory> allCategoryList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
indicatorTab = findViewById(R.id.tab_indicator);
categoryTab = findViewById(R.id.tablayout);
homeBannerList = new ArrayList<>();
homeBannerList.add(new BannerMovies(1, "Trailer - I cannot give up now!!!", "https://i.pinimg.com/originals/1a/5e/c6/1a5ec63c50513055ac7674ad65c2e1a1.jpg", "https://youtu.be/7w1YKrHW85c"));
homeBannerList.add(new BannerMovies(2, "Trailer - I must cross the Red Sea", "https://i.pinimg.com/originals/7f/8f/02/7f8f02fdfc2b09de9d01d86395d128b1.jpg", "https://youtu.be/88dHJdCyyBA"));
homeBannerList.add(new BannerMovies(3, "Trailer - I must be better than my Father", "https://i.pinimg.com/originals/ec/60/46/ec604668771e8916466be6835d2ea588.jpg", "https://youtu.be/GsNrJgLSTAM"));
vipHourBannerList = new ArrayList<>();
vipHourBannerList.add(new BannerMovies(1, "I will be better than my father", "https://i.pinimg.com/originals/ec/60/46/ec604668771e8916466be6835d2ea588.jpg", "https://youtu.be/ymIUteex694"));
vipHourBannerList.add(new BannerMovies(3, "I must cross the Red Sea", "https://i.pinimg.com/originals/7f/8f/02/7f8f02fdfc2b09de9d01d86395d128b1.jpg", "https://youtu.be/Sbbu536E9vA"));
vipHourBannerList.add(new BannerMovies(4, "My Hair Will Grow Again", "https://img.yts.mx/assets/images/movies/sharkula_2022/medium-cover.jpg", "https://youtu.be/yau5eQH1K_I"));
prophecyBannerList = new ArrayList<>();
prophecyBannerList.add(new BannerMovies(2, "Looking for Jackie", "https://img.yts.mx/assets/images/movies/looking_for_jackie_2009/medium-cover.jpg", "https://www.youtube.com/watch?v=ByYWL1SEe-k"));
prophecyBannerList.add(new BannerMovies(3, "Khuda Haafiz Chapter II", "https://sdmoviespoint.mba/wp-content/uploads/2022/07/Khuda-Haafiz-Chapter-II-Agni-Pariksha-2022-Full-Movie-Download-Free.jpg", "https://www.youtube.com/watch?v=ByYWL1SEe-k"));
prophecyBannerList.add(new BannerMovies(4, "Sharkula", "https://img.yts.mx/assets/images/movies/sharkula_2022/medium-cover.jpg", "https://youtu.be/6SOEYXZK6Q4"));
prophecyBannerList.add(new BannerMovies(5, "Looking for Jackie", "https://img.yts.mx/assets/images/movies/looking_for_jackie_2009/medium-cover.jpg", "https://www.youtube.com/watch?v=ByYWL1SEe-k"));
testimonyBannerList = new ArrayList<>();
testimonyBannerList.add(new BannerMovies(1, "See how this little boy survived under the water for 2 hours", "https://i.pinimg.com/originals/14/f1/5c/14f15cc3bbc780abdfecafa0f94024e1.jpg", "https://youtu.be/rRFkBLGQIs8"));
testimonyBannerList.add(new BannerMovies(2, "Testimony Blessing Nsikak Saved from spiritual attack", "https://i.pinimg.com/originals/14/f1/5c/14f15cc3bbc780abdfecafa0f94024e1.jpg", "https://youtu.be/TdYn24MdD1Q"));
testimonyBannerList.add(new BannerMovies(3, "See how this man got back his transformer working again", "https://i.pinimg.com/originals/14/f1/5c/14f15cc3bbc780abdfecafa0f94024e1.jpg", "https://youtu.be/HNjxxk3eWKk"));
//this is default tab selected
setBannerMoviesPagerAdapter(homeBannerList);
categoryTab.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
switch (tab.getPosition()){
case 1:
setBannerMoviesPagerAdapter(vipHourBannerList);
return;
case 2:
setBannerMoviesPagerAdapter(prophecyBannerList);
return;
case 3:
setBannerMoviesPagerAdapter(testimonyBannerList);
return;
default:
setBannerMoviesPagerAdapter(homeBannerList);
}
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
List<CategoryItem> homeCatListItem1 = new ArrayList<>();
homeCatListItem1.add(new CategoryItem(1, "Trailer - I cannot give up now!!!", "https://i.pinimg.com/originals/1a/5e/c6/1a5ec63c50513055ac7674ad65c2e1a1.jpg", "https://youtu.be/7w1YKrHW85c"));
homeCatListItem1.add(new CategoryItem(2, "Trailer - I must cross the Red Sea", "https://i.pinimg.com/originals/7f/8f/02/7f8f02fdfc2b09de9d01d86395d128b1.jpg", "https://youtu.be/88dHJdCyyBA"));
homeCatListItem1.add(new CategoryItem(3, "Trailer - I must be better than my Father", "https://i.pinimg.com/originals/ec/60/46/ec604668771e8916466be6835d2ea588.jpg", "https://youtu.be/GsNrJgLSTAM"));
homeCatListItem1.add(new CategoryItem(4, "My Hair Will Grow Again", "https://i.pinimg.com/originals/14/f1/5c/14f15cc3bbc780abdfecafa0f94024e1.jpg", "https://youtu.be/yau5eQH1K_I"));
homeCatListItem1.add(new CategoryItem(5, "See how this man got back his transformer working again", "https://i.pinimg.com/originals/7f/8f/02/7f8f02fdfc2b09de9d01d86395d128b1.jpg", "https://youtu.be/HNjxxk3eWKk"));
List<CategoryItem> homeCatListItem2 = new ArrayList<>();
homeCatListItem2.add(new CategoryItem(1, "Trailer - I cannot give up now!!!", "https://i.pinimg.com/originals/1a/5e/c6/1a5ec63c50513055ac7674ad65c2e1a1.jpg", "https://youtu.be/7w1YKrHW85c"));
homeCatListItem2.add(new CategoryItem(2, "Trailer - I must cross the Red Sea", "https://i.pinimg.com/originals/7f/8f/02/7f8f02fdfc2b09de9d01d86395d128b1.jpg", "https://youtu.be/88dHJdCyyBA"));
homeCatListItem2.add(new CategoryItem(3, "Trailer - I must be better than my Father", "https://i.pinimg.com/originals/ec/60/46/ec604668771e8916466be6835d2ea588.jpg", "https://youtu.be/GsNrJgLSTAM"));
homeCatListItem2.add(new CategoryItem(4, "My Hair Will Grow Again", "https://i.pinimg.com/originals/14/f1/5c/14f15cc3bbc780abdfecafa0f94024e1.jpg", "https://youtu.be/yau5eQH1K_I"));
homeCatListItem2.add(new CategoryItem(5, "See how this man got back his transformer working again", "https://i.pinimg.com/originals/7f/8f/02/7f8f02fdfc2b09de9d01d86395d128b1.jpg", "https://youtu.be/HNjxxk3eWKk"));
List<CategoryItem> homeCatListItem3 = new ArrayList<>();
homeCatListItem3.add(new CategoryItem(1, "Trailer - I cannot give up now!!!", "https://i.pinimg.com/originals/1a/5e/c6/1a5ec63c50513055ac7674ad65c2e1a1.jpg", "https://youtu.be/7w1YKrHW85c"));
homeCatListItem3.add(new CategoryItem(2, "Trailer - I must cross the Red Sea", "https://i.pinimg.com/originals/7f/8f/02/7f8f02fdfc2b09de9d01d86395d128b1.jpg", "https://youtu.be/88dHJdCyyBA"));
homeCatListItem3.add(new CategoryItem(3, "Trailer - I must be better than my Father", "https://i.pinimg.com/originals/ec/60/46/ec604668771e8916466be6835d2ea588.jpg", "https://youtu.be/GsNrJgLSTAM"));
homeCatListItem3.add(new CategoryItem(4, "My Hair Will Grow Again", "https://i.pinimg.com/originals/14/f1/5c/14f15cc3bbc780abdfecafa0f94024e1.jpg", "https://youtu.be/yau5eQH1K_I"));
homeCatListItem3.add(new CategoryItem(5, "See how this man got back his transformer working again", "https://i.pinimg.com/originals/7f/8f/02/7f8f02fdfc2b09de9d01d86395d128b1.jpg", "https://youtu.be/HNjxxk3eWKk"));
allCategoryList = new ArrayList<>();
allCategoryList.add(new AllCategory(1,"VIP Hour", homeCatListItem1));
allCategoryList.add(new AllCategory(2,"VIP Hour", homeCatListItem2));
allCategoryList.add(new AllCategory(3,"VIP Hour", homeCatListItem3));
setMainRecycler(allCategoryList);
}
private void setBannerMoviesPagerAdapter(List<BannerMovies> bannerMoviesList) {
bannerMoviesViewPager = findViewById(R.id.banner_viewPager);
bannerMoviesPagerAdapter = new BannerMoviesPagerAdapter(this, bannerMoviesList);
bannerMoviesViewPager.setAdapter(bannerMoviesPagerAdapter);
indicatorTab.setupWithViewPager(bannerMoviesViewPager);
sliderTimer = new Timer();
sliderTimer.scheduleAtFixedRate(new AutoSlider(), 4000, 6000);
indicatorTab.setupWithViewPager(bannerMoviesViewPager, true);
}
class AutoSlider extends TimerTask {
#Override
public void run() {
MainActivity.this.runOnUiThread(() ->{
if (bannerMoviesViewPager.getCurrentItem() < homeBannerList.size() - 1) {
bannerMoviesViewPager.setCurrentItem(bannerMoviesViewPager.getCurrentItem() + 1);
}
else{
bannerMoviesViewPager.setCurrentItem(0);
}
});
}
}
public void setMainRecycler(List<AllCategory> allCategoryList) {
mainRecycler = findViewById(R.id.main_recycler);
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(this, RecyclerView.VERTICAL, false);
mainRecycler.setLayoutManager(layoutManager);
mainRecyclerAdapter = new MainRecyclerAdapter(this, allCategoryList);
mainRecycler.setAdapter(mainRecyclerAdapter);
}
}
//Items in the model directory//
CategoryItem
public class CategoryItem {
Integer id;
String movieName;
String imageUrl;
String fileUrl;
public CategoryItem(Integer id, String movieName, String imageUrl, String fileUrl) {
this.id = id;
this.movieName = movieName;
this.imageUrl = imageUrl;
this.fileUrl = fileUrl;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getMovieName() {
return movieName;
}
public void setMovieName(String movieName) {
this.movieName = movieName;
}
public String getImageUrl() {
return imageUrl;
}
public void setImageUrl(String imageUrl) {
this.imageUrl = imageUrl;
}
public String getFileUrl() {
return fileUrl;
}
public void setFileUrl(String fileUrl) {
this.fileUrl = fileUrl;
}
}
AllCategory.Class
import java.util.List;
public class AllCategory {
String categoryTitle;
Integer categoryId;
private List<CategoryItem> categoryItemList = null;
public AllCategory(Integer categoryId, String categoryTitle, List<CategoryItem> categoryItemList) {
this.categoryTitle = categoryTitle;
this.categoryId = categoryId;
this.categoryItemList = categoryItemList;
}
public List<CategoryItem> getCategoryItemList() {
return categoryItemList;
}
public void setCategoryItemList(List<CategoryItem> categoryItemList) {
this.categoryItemList = categoryItemList;
}
public String getCategoryTitle(){
return categoryTitle;
}
public void setCategoryTitle(String categoryTitle){
this.categoryTitle = categoryTitle;
}
public Integer getCategoryId() {
return categoryId;
}
public void setCategoryId(Integer categoryId) {
this.categoryId = categoryId;
}
}
BannerMovies
package com.kuroniczstudio.splashscreen.model;
public class BannerMovies {
Integer id;
String movieName;
String imageUrl;
String fileUrl;
public BannerMovies(Integer id, String movieName, String imageUrl, String fileUrl) {
this.id = id;
this.movieName = movieName;
this.imageUrl = imageUrl;
this.fileUrl = fileUrl;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getMovieName() {
return movieName;
}
public void setMovieName(String movieName) {
this.movieName = movieName;
}
public String getImageUrl() {
return imageUrl;
}
public void setImageUrl(String imageUrl) {
this.imageUrl = imageUrl;
}
public String getFileUrl() {
return fileUrl;
}
public void setFileUrl(String fileUrl) {
this.fileUrl = fileUrl;
}
}
_____________________________________
**MainRecyclerAdapter**
package com.kuroniczstudio.splashscreen.adapter;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.kuroniczstudio.splashscreen.CategoryItem;
import com.kuroniczstudio.splashscreen.R;
import com.kuroniczstudio.splashscreen.model.AllCategory;
import java.util.List;
public class MainRecyclerAdapter extends RecyclerView.Adapter<MainRecyclerAdapter.MainViewHolder> {
Context context;
List<AllCategory> allCategoryList;
public MainRecyclerAdapter(Context context, List<AllCategory> allCategoryList) {
this.context = context;
this.allCategoryList = allCategoryList;
}
#NonNull
#Override
public MainViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
return new MainViewHolder(LayoutInflater.from(context).inflate(R.layout.main_recycler_row_item, parent));
}
#Override
public void onBindViewHolder(#NonNull MainViewHolder holder, int position) {
holder.categoryName.setText(allCategoryList.get(position).getCategoryTitle());
}
#Override
public int getItemCount() {
return allCategoryList.size();
}
public static final class MainViewHolder extends RecyclerView.ViewHolder{
TextView categoryName;
RecyclerView itemRecycler;
public MainViewHolder(#NonNull View itemView) {
super(itemView);
categoryName = itemView.findViewById(R.id.item_category);
itemRecycler = itemView.findViewById(R.id.item_recycler);
}
}
private void setItemRecycler(RecyclerView recyclerView, List<CategoryItem> categoryItemList){
ItemRecyclerAdapter itemRecyclerAdapter = new ItemRecyclerAdapter(context, categoryItemList);
recyclerView.setLayoutManager(new LinearLayoutManager(context, RecyclerView.HORIZONTAL, false));
recyclerView.setAdapter(itemRecyclerAdapter);
}
}
ItemRecyclerAdapter
package com.kuroniczstudio.splashscreen.adapter;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.bumptech.glide.Glide;
import com.kuroniczstudio.splashscreen.CategoryItem;
import com.kuroniczstudio.splashscreen.R;
import java.util.List;
public class ItemRecyclerAdapter extends RecyclerView.Adapter<ItemRecyclerAdapter.ItemViewHolder> {
Context context;
List<CategoryItem> categoryItemList;
public ItemRecyclerAdapter(Context context, List<CategoryItem> categoryItemList) {
this.context = context;
this.categoryItemList = categoryItemList;
}
#NonNull
#Override
public ItemViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
return new ItemViewHolder(LayoutInflater.from(context).inflate(R.layout.cat_recycler_row_items,parent, false));
}
#Override
public void onBindViewHolder(#NonNull ItemViewHolder holder, int position) {
Glide.with(context).load(categoryItemList.get(position).getImageUrl()).into(holder.itemImage);
}
#Override
public int getItemCount() {
return categoryItemList.size();
}
public static final class ItemViewHolder extends RecyclerView.ViewHolder{
ImageView itemImage;
public ItemViewHolder(#NonNull View itemView) {
super(itemView);
itemImage = itemView.findViewById(R.id.item_image);
}
}
}
BannerMoviesPagerAdapter
package com.kuroniczstudio.splashscreen.adapter;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import androidx.annotation.NonNull;
import androidx.viewpager.widget.PagerAdapter;
import com.bumptech.glide.Glide;
import com.kuroniczstudio.splashscreen.R;
import com.kuroniczstudio.splashscreen.model.BannerMovies;
import java.util.List;
public class BannerMoviesPagerAdapter extends PagerAdapter {
Context context;
List<BannerMovies> bannerMoviesList;
public BannerMoviesPagerAdapter(Context context, List<BannerMovies> bannerMoviesList) {
this.context = context;
this.bannerMoviesList = bannerMoviesList;
}
#Override
public int getCount() {
return bannerMoviesList.size();
}
#Override
public boolean isViewFromObject(#NonNull View view, #NonNull Object object) {
return view == object;
}
#Override
public void destroyItem(#NonNull ViewGroup container, int position, #NonNull Object object) {
container.removeView((View) object);
}
#NonNull
#Override
public Object instantiateItem(#NonNull ViewGroup container, int position) {
View view = LayoutInflater.from(context).inflate(R.layout.banner_movie_layout, null);
ImageView bannerImage = view.findViewById(R.id.banner_image);
Glide.with(context).load(bannerMoviesList.get(position).getImageUrl()).into(bannerImage);
container.addView(view);
return view;
}
}
The error itself is telling you where you are messing up. You have 2 CategoryItem classes in your project with the following hierarchies:
com.kuroniczstudio.splashscreen.CategoryItem
com.kuroniczstudio.splashscreen.model.CategoryItem
You're trying to use both these which is creating this conflict. Make sure you are using only one class.
In your application you have TWO classes called CategoryItem. One has the full name:
com.kuroniczstudio.splashscreen.CategoryItem
The other has the full name:
com.kuroniczstudio.splashscreen.model.CategoryItem
They are different classes, and you cannot convert from one class to the other one.
We cannot tell from the code that you have shown us why this is happening. For a start, you haven't show us both versions of CategoryItem. And you have left out all of the package statements. (So we can't tell which version of CategoryItem the AllCategory constructor expects ...)
But the compilation error message clearly proves that it is happening.
You probably shouldn't have two CategoryItem classes at all ...
I am looking some help for my application. I've built an app and i've included a chat feature. Within the chat fragment I have 2 additional fragments, one for chats currently open and one for all users which can be messaged. I want to incorroprate a search bar into each of these fragements to allow the user to find a certain user to message. I am
users fragment XML
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/gold"
tools:context=".ChatFragments.UsersFragment">
<EditText
android:id="#+id/etSearch"
android:layout_width="match_parent"
android:layout_height="50dp"
android:background="#android:color/white"
android:ems="20"
android:hint="#string/search"
android:layout_weight="0.5"
android:paddingLeft="15dp" />
<android.support.v7.widget.RecyclerView
android:id="#+id/recycler_view"
android:layout_below="#+id/etSearch"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</RelativeLayout>
users fragment java class
package com.alicearmstrong.coffeysloyaltyprojectv1.ChatFragments;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import com.alicearmstrong.coffeysloyaltyprojectv1.Adapter.CustomerAdapter;
import com.alicearmstrong.coffeysloyaltyprojectv1.R;
import com.alicearmstrong.coffeysloyaltyprojectv1.database.Customers;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.util.ArrayList;
import java.util.List;
public class UsersFragment extends Fragment {
private RecyclerView recyclerView;
private CustomerAdapter customerAdapter;
private List<Customers> customersList;
DatabaseReference databaseReference;
EditText etSearch;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
// Inflate the layout for this fragment
View view = inflater.inflate( R.layout.fragment_users , container, false);
etSearch = view.findViewById(R.id.etSearch);
recyclerView = view.findViewById( R.id.recycler_view );
recyclerView.setHasFixedSize( true );
recyclerView.setLayoutManager( new LinearLayoutManager( getContext() ) );
customersList = new ArrayList<>( );
readCustomers();
return view;
}
// Method for reading customers
private void readCustomers()
{
final FirebaseUser firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
databaseReference = FirebaseDatabase.getInstance().getReference().child("Customers");
databaseReference.addValueEventListener( new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot)
{
customersList.clear();
for (DataSnapshot snapshot : dataSnapshot.getChildren())
{
Customers customers = snapshot.getValue(Customers.class);
if (!customers.getId().equals(firebaseUser.getUid()))
{
customersList.add( customers );
}
}
customerAdapter = new CustomerAdapter( getContext(), customersList );
recyclerView.setAdapter( customerAdapter );
}
#Override
public void onCancelled( #NonNull DatabaseError databaseError) {
}
} );
}
}
customerAdapter.java
package com.alicearmstrong.coffeysloyaltyprojectv1.Adapter;
import android.content.Context;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Filter;
import android.widget.Filterable;
import android.widget.TextView;
import com.alicearmstrong.coffeysloyaltyprojectv1.uiOwner.chatOwner.MessageActivityOwner;
import com.alicearmstrong.coffeysloyaltyprojectv1.R;
import com.alicearmstrong.coffeysloyaltyprojectv1.database.Customers;
import java.util.ArrayList;
import java.util.List;
public class CustomerAdapter extends RecyclerView.Adapter<CustomerAdapter.ViewHolder>
{
private Context context;
private List<Customers> customersList;
public CustomerAdapter (Context context, List<Customers> customersList)
{
this.customersList = customersList;
this.context = context;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i)
{
// Set layout to user_item for displaying each user
View view = LayoutInflater.from(context).inflate( R.layout.user_item , viewGroup, false);
return new CustomerAdapter.ViewHolder( view );
}
#Override
public void onBindViewHolder(#NonNull ViewHolder viewHolder, int i)
{
final Customers customer = customersList.get( i );
// Set title to user's name
viewHolder.customerName.setText( customer.getFirstName() + " " + customer.getSurname() );
// Open Message Activity when user is selected
viewHolder.itemView.setOnClickListener( new View.OnClickListener() {
#Override
public void onClick(View v)
{
Intent intent = new Intent(context, MessageActivityOwner.class );
intent.putExtra( "userid", customer.getId() );
context.startActivity( intent );
}
} );
}
#Override
public int getItemCount()
{
return customersList.size();
}
/* #Override
public Filter getFilter() {
return exampleFilter;
}
private Filter exampleFilter = new Filter()
{
#Override
protected FilterResults performFiltering(CharSequence constraint) {
List<Customers> filteredList = new ArrayList<>( );
if (constraint == null || constraint.length() == 0)
{
filteredList.addAll( customersList );
}
else
{
// allows search to be case sensitive
String filteredPattern = constraint.toString().toLowerCase().trim();
for(Customers customers : customersList )
{
}
}
}
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
}
};*/
public class ViewHolder extends RecyclerView.ViewHolder
{
public TextView customerName;
public ViewHolder(#NonNull View view)
{
super( view );
customerName = view.findViewById( R.id.customerName );
}
}
public void upToDate(List<Customers> newList){
customersList = new ArrayList<>();
customersList.addAll(newList);
notifyDataSetChanged();
}
}
customers database
package com.alicearmstrong.coffeysloyaltyprojectv1.database;
public class Customers
{
String id, firstName,surname, DOB, contactNumber, email, qrCode;
Integer loyaltyScore;
public Customers(String id, String firstName, String surname, String DOB, String contactNumber, String email, String qrCode, Integer loyaltyScore)
{
this.id = id;
this.firstName = firstName;
this.surname = surname;
this.DOB = DOB;
this.contactNumber = contactNumber;
this.email = email;
this.qrCode = qrCode;
this.loyaltyScore = loyaltyScore;
}
public String getId() {
return id;
}
public String getFirstName()
{
return firstName;
}
public String getSurname()
{
return surname;
}
public String getDOB()
{
return DOB;
}
public String getContactNumber()
{
return contactNumber;
}
public String getEmail()
{
return email;
}
public String getQrCode()
{
return qrCode;
}
public Integer getLoyaltyScore()
{
return loyaltyScore;
}
public Customers()
{
}
}
I read in to the addTextChangeListener method just not sure how to implement the method. Any help would be greatly appreciated.
why using textView when searchView is exsist. check this code below but let me see ur Customers java class then i can help u better. at the first set search view then find view by id it then ....
search.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
String userInput = newText.toLowerCase();
List<Customers> newList = new ArrayList<>();
for (Customers customersList : accounts) {
if (customersList.customerName.toLowerCase().contains(userInput)) {
newList.add(accountList);
}
}
accountAdapter.upToDate(newList);
return true;
}
});
then add upToDate function in ur adapter and call it at the above code.
public void upToDate(List<Customers> newList){
customersList = new ArrayList<>();
customersList.addAll(newList);
notifyDataSetChanged();
}
This question already has answers here:
recyclerview No adapter attached; skipping layout
(38 answers)
Closed 2 years ago.
I am on a project now and am trying to obtain data from my firebase using recycler view and viewholder, but using my helper class, immediately when the app launches and I try retrieving data through my helper class it crashes, and when i look through my logcat, I get this error
E/RecyclerView: No adapter attached; skipping layout....
I have searched for a lot o answers and i see some but they are not related to my code...
Here is my mainactivity code
package com.example.android.journalapp;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import com.example.android.journalapp.users.LogInActivity;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
public class MainActivity extends AppCompatActivity {
private static final String DATE_FORMAT = "dd/MM/yyy";
private SimpleDateFormat dateFormat = new SimpleDateFormat(DATE_FORMAT,
Locale.getDefault());
private FirebaseAuth mFirebaseAuth;
private FirebaseUser mFirebaseUser;
private DatabaseReference mDatabase;
String mUserId;
private RecyclerView mRecyclerView;
private FirebaseHelper helper;
Context context;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mFirebaseAuth = FirebaseAuth.getInstance();
mFirebaseUser = mFirebaseAuth.getCurrentUser();
mRecyclerView = (RecyclerView) findViewById(R.id.journal_recycler);
mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
mRecyclerView.setHasFixedSize(true);
if (mFirebaseUser == null) {
// Not logged in, launch the Log In activity
loadLogInView();
} else {
mDatabase = FirebaseDatabase.getInstance().getReference();
mUserId = mFirebaseUser.getUid();
helper = new FirebaseHelper(context, mDatabase, mRecyclerView,
mUserId);
helper.refreshData();
}
FloatingActionButton fab = (FloatingActionButton)
findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent addJournalIntent = new Intent(MainActivity.this,
AddJournalActivity.class);
addJournalIntent.putExtra("USER_ID", mUserId);
startActivity(addJournalIntent);
}
});
}
private void loadLogInView() {
Intent intent = new Intent(this, LogInActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.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_logout) {
mFirebaseAuth.signOut();
loadLogInView();
}
return super.onOptionsItemSelected(item);
}
}
here is my firebase helper class
package com.example.android.journalapp;
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.RecyclerView;
import android.widget.Toast;
import com.example.android.journalapp.model.Journal;
import com.google.firebase.database.ChildEventListener;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Locale;
public class FirebaseHelper {
private String mUserId;
private Context context;
private DatabaseReference mDb;
RecyclerView mRecyclerView;
ArrayList<Journal> journals = new ArrayList<>();
public JournalAdapter mJournalAdapter;
private static final String DATE_FORMAT = "dd/MM/yyy";
private SimpleDateFormat dateFormat = new SimpleDateFormat(DATE_FORMAT, Locale.getDefault());
public FirebaseHelper(Context context, DatabaseReference mDb, RecyclerView mRecyclerView, String mUserId) {
this.context = context;
this.mDb = mDb;
this.mRecyclerView = mRecyclerView;
this.mUserId = mUserId;
}
public void saveData(String journal, String date) {
Journal journalEntry = new Journal(journal, date);
mDb.child("users").child(mUserId).child("journals").push().setValue(journalEntry) ;
// .child("journal")
}
public void recieveData(DataSnapshot ds) {
journals.clear();
for (DataSnapshot dataSnapshot : ds.getChildren()) {
Journal journal = dataSnapshot.getValue(Journal.class);
journals.add(journal);
}
mJournalAdapter = new JournalAdapter(context, journals);
mRecyclerView.setAdapter(mJournalAdapter);
// if (journals.size() > 0) {
//
// mJournalAdapter = new JournalAdapter(context, journals);
// mRecyclerView.setAdapter(mJournalAdapter);
// } else {
// Toast.makeText(context, "No data", Toast.LENGTH_SHORT).show();
// }
}
public void refreshData() {
mDb.child("users").child(mUserId).child("journals").addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
recieveData(dataSnapshot);
}
#Override
public void onChildChanged(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
recieveData(dataSnapshot);
}
#Override
public void onChildRemoved(#NonNull DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
}
here is my model class
package com.example.android.journalapp.model;
import java.util.Date;
public class Journal {
private String journalContent;
private String date;
public Journal(String journalContent, String date) {
this.journalContent = journalContent;
this.date = date;
}
public String getJournalContent() {
return journalContent;
}
public void setJournalContent(String journalContent) {
this.journalContent = journalContent;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
}
///
here is my adapter class
package com.example.android.journalapp;
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.example.android.journalapp.model.Journal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Locale;
public class JournalAdapter extends RecyclerView.Adapter<JournalHolder> {
Context context;
private ArrayList<Journal> journals;
private static final String DATE_FORMAT = "dd/MM/yyy";
private SimpleDateFormat dateFormat = new SimpleDateFormat(DATE_FORMAT, Locale.getDefault());
public JournalAdapter(Context context, ArrayList<Journal> journals) {
this.context = context;
this.journals = journals;
}
#NonNull
#Override
public JournalHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.journal_layout, parent, false);
JournalHolder holder = new JournalHolder(view);
return holder;
}
#Override
public void onBindViewHolder(#NonNull JournalHolder holder, int position) {
holder.mJournalTextView.setText(journals.get(position).getJournalContent());
String date = journals.get(position).getDate();
holder.mDateTextView.setText(date);
}
#Override
public int getItemCount() {
if (journals == null) {
return 0;
}
return journals.size();
}
}
//
here is my viewholder class
package com.example.android.journalapp;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.TextView;
public class JournalHolder extends RecyclerView.ViewHolder {
TextView mJournalTextView;
TextView mDateTextView;
public JournalHolder(View itemView) {
super(itemView);
mJournalTextView = itemView.findViewById(R.id.journal_text_view);
mDateTextView = itemView.findViewById(R.id.journal_date_text_view);
}
}
i am able to push into the data base, but to retrieve data gives me the error E/RecyclerView: No adapter attached; skipping layout
Try this code..
display_data.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v7.widget.RecyclerView
android:id="#+id/rvData"
android:layout_width="match_parent"
android:layout_height="match_parent">
</android.support.v7.widget.RecyclerView>
<TextView
android:id="#+id/dlTvEmpty"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="No Found"
android:textSize="16dp"
android:visibility="gone"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</android.support.constraint.ConstraintLayout>
DisplayActivity.java..
public class DisplayActivity extends AppCompatActivity {
private RecyclerView mRvData;
private DisplayAllData allDataAdapter;
private DatabaseReference mDatabase;
private TextView mTvEmpty;
private FirebaseDatabase mFirebaseInstance;
private List<User> mUserList = new ArrayList<>();
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.display_data);
initView();
}
private void initView() {
mFirebaseInstance = FirebaseDatabase.getInstance();
mDatabase = mFirebaseInstance.getReference("usersDb/UserTable");
mRvData = findViewById(R.id.rvData);
mTvEmpty = findViewById(R.id.dlTvEmpty);
mRvData.setLayoutManager(new LinearLayoutManager(this));
mDatabase.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
mUserList.clear();
for (DataSnapshot dataSnapshot1 : dataSnapshot.getChildren()) {
User user = dataSnapshot1.getValue(User.class);
mUserList.add(user);
}
allDataAdapter = new DisplayAllData(DisplayActivity.this, mUserList);
mRvData.setAdapter(allDataAdapter);
allDataAdapter.notifyDataSetChanged();
if (mUserList.isEmpty())
mTvEmpty.setVisibility(View.VISIBLE);
else
mTvEmpty.setVisibility(View.GONE);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
}
DisplayAdapter.java..
public class DisplayAllData extends RecyclerView.Adapter<DisplayAllData.ItemViewHolder> {
private List<User> mUserLsit = new ArrayList<>();
private Context mContext;
#Override
public ItemViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.row_layout, parent, false);
return new ItemViewHolder(view);
}
public DisplayAllData(Context mContext, List<User> mUserLsit) {
this.mContext = mContext;
this.mUserLsit = mUserLsit;
}
#Override
public void onBindViewHolder(ItemViewHolder holder, int position) {
User user = mUserLsit.get(position);
holder.mTvName.setText(user.name);
holder.mTvEmail.setText(user.email);
holder.mTvPwd.setText(user.pwd);
}
#Override
public int getItemCount() {
return mUserLsit.size();
}
public class ItemViewHolder extends RecyclerView.ViewHolder {
TextView mTvName, mTvEmail, mTvPwd;
public ItemViewHolder(View itemView) {
super(itemView);
mTvEmail = itemView.findViewById(R.id.rlTvEmail);
mTvName = itemView.findViewById(R.id.rlTvName);
mTvPwd = itemView.findViewById(R.id.rlTvPwd);
}
}
}
row_layout.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="10dp">
<TextView
android:id="#+id/rlTvName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Name"
android:textSize="20dp" />
<TextView
android:id="#+id/rlTvEmail"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Email"
android:textSize="20dp"
app:layout_constraintTop_toBottomOf="#+id/rlTvName" />
<TextView
android:id="#+id/rlTvPwd"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Password"
android:textSize="20dp"
app:layout_constraintTop_toBottomOf="#+id/rlTvEmail" />
</android.support.constraint.ConstraintLayout>
and i hope you add internet permission into android manifest file..
<uses-permission android:name="android.permission.INTERNET"/>
more information refer this link
https://www.simplifiedcoding.net/firebase-realtime-database-crud/
I have a Main Activity that holds a viewpager that contains three fragments. In each fragment is a listview populated by a custom adapter. I need the ability to sort by date, name and quantity (the fields that the listview shows)
Here is my Main Activity
package com.bkbeesites.bkbeesalessheet;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.preference.PreferenceManager;
import android.support.design.widget.TabLayout;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import java.text.Collator;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
private SectionsPageAdapter mSectionsPageAdapter;
private ViewPager viewPager;
private String TAG = "MainActivity";
public ArrayList<Customer> packageData;
Toolbar toolbar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = (Toolbar) findViewById(R.id.toolbar);
toolbar.setTitle("BK Bee Sales - Pending Sales");
setSupportActionBar(toolbar);
mSectionsPageAdapter = new SectionsPageAdapter(getSupportFragmentManager());
viewPager = (ViewPager) findViewById(R.id.container);
setupViewPager(viewPager);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
String dft = preferences.getString("default", "");
if(!dft.equalsIgnoreCase(""))
{
if (dft.equals("package")){
viewPager.setCurrentItem(0);
}else if (dft.equals("nuc")){
viewPager.setCurrentItem(1);
}else if (dft.equals("queen")){
viewPager.setCurrentItem(2);
} else {
viewPager.setCurrentItem(0);
}
}
}
public void showAddCustomer(View view){
Intent intent = new Intent(this, AddCustomer.class);
startActivity(intent);
}
public void sortDate (View view){
Tab1 tab1 = new Tab1();
Tab2 tab2 = new Tab2();
Tab3 tab3 = new Tab3();
if (viewPager.getCurrentItem()==0){
tab1.sortDate();
}
}
private void setupViewPager(ViewPager viewPager){
SectionsPageAdapter adapter = new SectionsPageAdapter(getSupportFragmentManager());
adapter.addFragment(new Tab1(), "Packages");
adapter.addFragment(new Tab2(), "Nucs");
adapter.addFragment(new Tab3(), "Queens");
viewPager.setAdapter(adapter);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.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) {
Intent intent = new Intent(this, Preferences.class);
startActivity(intent);
return true;
} else if (id==R.id.action_viewList){
Intent intent = new Intent(this,SalesRecord.class);
startActivity(intent);
}
return super.onOptionsItemSelected(item);
}
}
Here is my Tab1 Class
package com.bkbeesites.bkbeesalessheet;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.net.Uri;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import java.text.Collator;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class Tab1 extends Fragment {
private CustomerAdapter customerAdapter;
private static final String TAG = "fragment_tab1";
private ListView tab1ListView;
private ArrayList<Customer> packageData = new ArrayList<>();
TextView totalPackages;
TextView totalGross;
View rootView;
public Tab1() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
rootView = inflater.inflate(R.layout.fragment_tab1, container, false);
tab1ListView = (ListView) rootView.findViewById(R.id.tab1ListView);
totalPackages = (TextView)rootView.findViewById(R.id.totalPackages);
totalGross = (TextView)rootView.findViewById(R.id.totalGross);
return rootView;
}
#Override
public void onResume(){
super.onResume();
updatePackageList();
}
public void updatePackageList() {
packageData.clear();
tab1ListView.setAdapter(null);
int totalPackagesInt = 0;
try {
DatabaseHelper dbHelper = DatabaseHelper.getInstance(getActivity().getApplicationContext());
SQLiteDatabase db = dbHelper.getReadableDatabase();
Cursor c = db.rawQuery("SELECT * FROM packageCustomers", null);
if (c != null) {
if (c.moveToFirst()) {
while (!c.isAfterLast()){
Customer cus = new Customer();
cus.setDate(c.getString(c.getColumnIndex("date")));
cus.setName(c.getString(c.getColumnIndex("name")));
cus.setPhone(c.getString(c.getColumnIndex("phone")));
cus.setEmail(c.getString(c.getColumnIndex("email")));
cus.setQuantity(c.getInt(c.getColumnIndex("quantity")));
cus.setNotes(c.getString(c.getColumnIndex("notes")));
cus.setId(c.getInt(c.getColumnIndex("id")));
packageData.add(cus);
totalPackagesInt = totalPackagesInt + cus.getQuantity();
c.moveToNext();
}
}
}
customerAdapter = new CustomerAdapter(this.getContext(), packageData);
tab1ListView.setAdapter(customerAdapter);
db.close();
c.close();
String totalPackagesText = totalPackagesInt + " Total Packages Reserved";
totalPackages.setText(totalPackagesText);
packageMath(totalPackagesInt);
tab1ListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Customer cus = new Customer();
cus = customerAdapter.getItem(position);
int sqlId = cus.getId();
Intent intent = new Intent(getContext(), CustomerModel.class);
intent.putExtra("table", "packageCustomers");
intent.putExtra("id", sqlId);
startActivity(intent);
}
});
} catch (SQLiteException se) {
Log.e(getClass().getSimpleName(), "Could not create or Open the database");
}
}
public void packageMath(int i){
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(rootView.getContext());
String p = preferences.getString("packagePrice","");
if(!p.equals("")) {
int price = Integer.parseInt(p);
int totalGrossInt = i * price;
String grossText = "Projected Earnings: $" + String.valueOf(totalGrossInt);
totalGross.setText(grossText);
} else {
totalGross.setText("Edit Price Preferences");
}
}
public void sortDate(){
Collections.sort(packageData);
tab1ListView.setAdapter(customerAdapter);
updatePackageList();
}
}
Here is my Customer Class
package com.bkbeesites.bkbeesalessheet;
import android.support.annotation.NonNull;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
/**
* Created by Brett on 12/6/2017.
*/
public class Customer implements Comparable<Customer>{
public String name;
private String email;
private String phone;
private int quantity;
private String notes;
private String date;
private int id;
private Date dateTime;
public Customer (){
this.name = "";
this.email="";
this.phone="";
this.quantity=0;
this.notes="";
this.date="";
}
public Customer (int id, String name, String phone, String email, int quantity, String notes, String date) {
this.name = name;
this.email = email;
this.phone = phone;
this.quantity = quantity;
this.notes = notes;
this.date = date;
}
public Date getDateTime() throws ParseException {
String myFormat = "MM/dd/yy"; //In which you need put here
SimpleDateFormat sdf = new SimpleDateFormat(myFormat, Locale.US);
Date convertedDate = new Date();
convertedDate = sdf.parse(date);
return convertedDate;
}
public void setDateTime(Date dateTime) {
this.dateTime = dateTime;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public int getQuantity() {
return quantity;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}
public String getNotes() {
return notes;
}
public void setNotes(String notes) {
this.notes = notes;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
#Override
public int compareTo(#NonNull Customer o) {
try {
return getDateTime().compareTo(o.getDateTime());
} catch (ParseException e) {
e.printStackTrace();
return 0;
}
}
}
And Lastly, here is my CustomerAdapter
package com.bkbeesites.bkbeesalessheet;
import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import java.util.ArrayList;
/**
* Created by Brett on 12/6/2017.
*/
public class CustomerAdapter extends BaseAdapter {
private Context mContext;
private LayoutInflater mInflater;
private ArrayList<Customer> mDataSource;
public CustomerAdapter(Context context, ArrayList<Customer> items) {
super();
mContext = context;
mDataSource = items;
mInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return mDataSource.size();
}
//2
#Override
public Customer getItem(int position) {
return mDataSource.get(position);
}
//3
#Override
public long getItemId(int position) {
return position;
}
//4
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// Get view for row item
View rowView = mInflater.inflate(R.layout.list_item, parent, false);
// Get title element
TextView nameTextView =
(TextView) rowView.findViewById(R.id.nameTextView);
TextView quantityTextView =
(TextView) rowView.findViewById(R.id.quantityTextView);
TextView dateTextView =
(TextView) rowView.findViewById(R.id.dateTextView);
Customer cus = mDataSource.get(position);
nameTextView.setText(cus.getName());
quantityTextView.setText(String.valueOf(cus.getQuantity()));
dateTextView.setText(cus.getDate());
return rowView;
}
}
Sorry if that was a lot of unnecessary code but I'm a beginner here and did not know what you would want to see.
I'm trying to call Collections.sort when the Column Title Textview "Order Date" is clicked. The Data that contains the Customer objects is stored in an SQLite database (not sure if that's pertinent).
You need to write a method in adapter class that should look like this;
public void sort(){
Collections.sort(list, new Comparator<Customer>() {
#Override
public int compare(Customer o1, Customer o2) {
return o1.compareTo(o2);
}
});
notifyDataSetChanged();
}
if you don't want to create comparator every method call you can create variable of comparator.
private Comparator comp = new Comparator<Customer>() {
#Override
public int compare(Customer o1, Customer o2) {
return o1.compareTo(o2);
}
});
in this case you need to change sort method like;
public void sort(){
Collections.sort(list, comp);
notifyDataSetChanged();
}
whenever you want to sort in your activity class you need to call this sort method it will sort your list and update listview.
In your activity class you need to call method like below
adapter.sort();
Also if you want to compare according to other fields. You can create variable as
private int sortType;
You should pass parameter to adapter class.
public void sort(int sortType){
this.sortType = sortType;
Collections.sort(list, comp);
notifyDataSetChanged();
}
and change the comparator field as below
private Comparator comp = new Comparator<Customer>() {
#Override
public int compare(Customer o1, Customer o2) {
switch(sortType){
case 0: //By Name
return o1.getName().compareTo(o2.getName);
break;
case 1:
return o1.getQuantitiy() - o2.getQuantitiy();
break;
case 2:
return o1.compareTo(o2);
break;
default:
return 0;
}
}
});
im retrieving data in my database from firebase. and shoscription herew up this error can anyone help me? this is my mainactivity.java:
package com.example.infamouslegend.myapplication;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
FirebaseDatabase database;
DatabaseReference myRef ;
List<FireModel> list;
RecyclerView recycle;
Button view;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
view = (Button) findViewById(R.id.view);
recycle = (RecyclerView) findViewById(R.id.recycle);
database = FirebaseDatabase.getInstance();
myRef = database.getReference("Complaints");
myRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
// This method is called once with the initial value and again
// whenever data at this location is updated.
list = new ArrayList<FireModel>();
for(DataSnapshot dataSnapshot1 :dataSnapshot.getChildren()){
FireModel value = dataSnapshot.getValue(FireModel.class);
FireModel fire = new FireModel();
String Description = value.getDescription();
String Date = value.getDate();
String MediaURL = value.getMediaURL();
fire.setDescription(Description);
fire.setDate(Date);
fire.setMediaURL(MediaURL);
list.add(fire);
}
}
#Override
public void onCancelled(DatabaseError error) {
// Failed to read value
Log.w("Hello", "Failed to read value.", error.toException());
Toast.makeText(MainActivity.this, "Failed to read value !" + error.toException(), Toast.LENGTH_SHORT).show();
}
});
view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
RecyclerAdapter recyclerAdapter = new RecyclerAdapter(list,MainActivity.this);
RecyclerView.LayoutManager recyce = new GridLayoutManager(MainActivity.this,2);
/// RecyclerView.LayoutManager recyce = new LinearLayoutManager(MainActivity.this);
// recycle.addItemDecoration(new GridSpacingItemDecoration(2, dpToPx(10), true));
recycle.setLayoutManager(recyce);
recycle.setItemAnimator( new DefaultItemAnimator());
recycle.setAdapter(recyclerAdapter);
}
});
}
}
and this is my firemodel.java:
package com.example.infamouslegend.myapplication;
/**
* Created by Infamous Legend on 10/15/2017.
*/
public class FireModel {
public String Description;
public String Date;
public String MediaURL;
public String getDescription() {
return Description;
}
public void setDescription(String description) {
this.Description = description;
}
public String getDate() {
return Date;
}
public void setDate(String date) {
this.Date = date;
}
public String getMediaURL() {
return MediaURL;
}
public void setMediaURL(String MediaURL) {
this.MediaURL = MediaURL;
}
}
and my recycleradapter.java:
package com.example.infamouslegend.myapplication;
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.squareup.picasso.Picasso;
import java.util.List;
/**
* Created by Infamous Legend on 10/15/2017.
*/
public class RecyclerAdapter extends RecyclerView.Adapter<RecyclerAdapter.MyHoder>{
List<FireModel> list;
Context context;
public RecyclerAdapter(List<FireModel> list, Context context) {
this.list = list;
this.context = context;
}
#Override
public MyHoder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(context).inflate(R.layout.card,parent,false);
MyHoder myHoder = new MyHoder(view);
return myHoder;
}
#Override
public void onBindViewHolder(MyHoder holder, int position) {
FireModel mylist = list.get(position);
holder.Description.setText(mylist.getDescription());
holder.Date.setText(mylist.getDate());
//holder.MediaURL.setText(mylist.getMediaURL());
//Picasso.with(context).load(MediaURL.get(position).getMediaURL()).resize(120, 60).into(MyHoder.MediaURL);
}
#Override
public int getItemCount() {
int arr = 0;
try{
if(list.size()==0){
arr = 0;
}
else{
arr=list.size();
}
}catch (Exception e){
}
return arr;
}
class MyHoder extends RecyclerView.ViewHolder{
TextView Description,Date;
//ImageView MediaURL;
public MyHoder(View itemView) {
super(itemView);
Description = (TextView) itemView.findViewById(R.id.vname);
Date= (TextView) itemView.findViewById(R.id.vemail);
//MediaURL= (ImageView) itemView.findViewById(R.id.thumbnail);
}
}
}
Can anyone help me this? Im trying to retrieve data from firebase database to recyclerview with cardview. Thanks in advance
this is my firebase realtime database rule:
{
"rules": {
".read": true,
".write":true
}
}
If you have configured the app to connect with firebase correctly i would redownload the google-service.json and replace with an existing one.
check this solution