Recycle view not displaying data its shows an empty screen, It displays data when I go back and click the icon again. Not sure why I'm facing this problem.Please check the activity, adaptor and fragment code below. I'm new to android and I'm doing my capstone project it would be great if you can help me.
public class AppDetailsActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setTitle("App Details");
setContentView(R.layout.activity_app);
AppDetailsFragment newFragment = new AppDetailsFragment();
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.recordAppFragmentContainer, newFragment);
transaction.addToBackStack(null);
transaction.commit();
}
public void refreshAppDuration(View v) {
Intent intent = new Intent(this, AppDetailsActivity.class);
startActivity(intent);
}
protected void onPause() {
super.onPause();
}
protected void onStop() {
super.onStop();
}
protected void onDestroy() {
super.onDestroy();
}
public void onBackAppDuration(View v) {
if (getFragmentManager().getBackStackEntryCount() > 0) {
getFragmentManager().popBackStack();
} else {
super.onBackPressed();
}
}
Adaptor
public class AppDetailsAdaptor extends RecyclerView.Adapter<AppDetailsAdaptor.ViewHolder> {
private List<AppUsage> mApps;
private Context mContext;
public AppDetailsAdaptor(Context context, List<AppUsage> apps) {
mApps = apps;
mContext = context;
}
private Context getContext() {
return mContext;
}
#Override
public AppDetailsAdaptor.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
Context context = parent.getContext();
LayoutInflater inflater = LayoutInflater.from(context);
// Inflate the custom layout
View appUsageView = inflater.inflate(R.layout.item_app_details, parent, false);
// Return a new holder instance
AppDetailsAdaptor.ViewHolder viewHolder = new AppDetailsAdaptor.ViewHolder(appUsageView);
return viewHolder;
}
#Override
public void onBindViewHolder(AppDetailsAdaptor.ViewHolder viewHolder, final int position) {
// Get the data model based on position
final AppUsage ch = mApps.get(position);
// Set item views based on your views and data model
viewHolder._appTextView.setText(ch.getAppName());
viewHolder._durationTextView.setText(ch.getDurationInMinutes());
viewHolder._dateTextView.setText(ch.getDate().substring(0,10));
final String key = ch.getKey();
}
#Override
public int getItemCount() {
return mApps.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
public TextView _appTextView;
public TextView _durationTextView;
public TextView _dateTextView;
super(itemView);
_appTextView = (TextView) itemView.findViewById(R.id.rvs_app_name);
_durationTextView = (TextView) itemView.findViewById(R.id.rvs_app_duration);
_dateTextView =(TextView) itemView.findViewById(R.id.rvs_app_date);
}
}
}
Fragment
public class AppDetailsFragment extends Fragment {
final FirebaseDatabase database = FirebaseDatabase.getInstance();
ArrayList<AppUsage> appList = new ArrayList<>();
ArrayList<AppUsage> appListTemp = new ArrayList<>();
ArrayList<AppUsage> appListAdaptor = new ArrayList<>();
ArrayList<AppUsage> appObject = new ArrayList<>();
ArrayList<AppUsage> appListDate = new ArrayList<>();
private AppDetailsFragment.OnFragmentInteractionListener mListener;
private RecyclerView rvApp;
private RecyclerView.Adapter appAdaptor;
private RecyclerView.LayoutManager eLayoutManager;
private EditText date;
private static final int DIALOG_DATE_PICKER = 100;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_app_list, container, false);
rvApp = (RecyclerView) rootView.findViewById(R.id.rvAppList);
rvApp.setHasFixedSize(true);
eLayoutManager = new LinearLayoutManager(getActivity());
rvApp.setLayoutManager(eLayoutManager);
appList = getAllAppRecords();
appAdaptor = new AppDetailsAdaptor(getActivity(), appList);
rvApp.setAdapter(appAdaptor);
return rootView;
}
public ArrayList<AppUsage> getAllAppRecords(){
DatabaseReference ref = database.getReference();
ref.child("AppUsage").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
appObject.clear();
HashMap<String,Object> app = null;
Iterator<DataSnapshot> items = dataSnapshot.getChildren().iterator();
while(items.hasNext()){
DataSnapshot item = items.next();
Log.e("Listener",item.toString() );
app =(HashMap<String, Object>) item.getValue();
appObject.add(new AppUsage(app.get("appName").toString(),app.get("durationInMinutes").toString(),app.get("date").toString(),item.getKey()));
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
return appObject;
}
Related
Im trying to use Material Container Transform in Recyclerview Adapter as described by this post MaterialContainerTransform transition is not Working on Return , but after implementing this in my project im getting null pointer exception error.
As everyone know Material Container Transform animation tutorials are in kotlin and im doing it in java.
So if anyone know how to properly use material container transform animation in recyclerview and point out my mistakes i will be very much thankful to him.
RecyclerView Adapter Class(source)
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.ViewHolder> implements Filterable {
private Context context;
private List<Astadhyayi> wordList;
private List<Astadhyayi> filwordList;
private DictionaryDB dictionaryDB;
private OnclickListenerInterface listener;
public RecyclerViewAdapter(Context context, List<Astadhyayi> itemList, DictionaryDB dictionaryDB) {
this.context = context;
this.wordList = itemList;
this.dictionaryDB = dictionaryDB;
filwordList = new ArrayList<Astadhyayi>(itemList);
}
public void setClickListener(OnclickListenerInterface onclickListener) {
this.listener = onclickListener;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(context);
View view = inflater.inflate(R.layout.wordslist_two_rv, parent, false);
ViewHolder viewHolder = new ViewHolder(view);
return viewHolder;
}
#Override
public void onBindViewHolder(final ViewHolder holder, int position) {
Astadhyayi word = wordList.get(position);
holder.rsutras.setText(word.mSutras);
// Animation******
holder.rsutras.setTransitionName(word.getMSutras());
if (word.mStatus != null && word.mStatus.equals(DictionaryDB.BOOKMARKED)) {
holder.bookmark.setImageResource(R.drawable.cards_heart);
} else {
holder.bookmark.setImageDrawable(null);
}
}
#Override
public Filter getFilter() {
return Searched_Filter;
}
private Filter Searched_Filter = new Filter() {
#Override
protected FilterResults performFiltering(CharSequence constraint) {
List<Astadhyayi> filteredList = new ArrayList<>();
if (constraint == null || constraint.length() == 0) {
filteredList.addAll(filwordList);
} else {
String filterPattern = constraint.toString().toLowerCase().trim();
for (Astadhyayi item : filwordList) {
if (item.getMSutras().toLowerCase().contains(filterPattern)) {
filteredList.add(item);
}
}
}
FilterResults results = new FilterResults();
results.values = filteredList;
return results;
}
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
wordList.clear();
wordList.addAll((ArrayList<Astadhyayi>)results.values);
notifyDataSetChanged();
}
};
#Override
public int getItemCount() {
return wordList.size();
}
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
private TextView rsutras;
private ImageView bookmark;
public ViewHolder(View itemView) {
super(itemView);
itemView.setOnClickListener(this);
rsutras = itemView.findViewById(R.id.tvSansTerm);
bookmark = itemView.findViewById(R.id.bookmarkBtn);
}
/*
#Override
public void onClick(View view) {
if(listener!=null) listener.onItemClicked(getAbsoluteAdapterPosition(), rsutras);
}
*/
#Override
public void onClick(View view) {
int position = this.getAbsoluteAdapterPosition();
Astadhyayi word = wordList.get(position);
//*************** Bundle **************\\
Bundle bundle = new Bundle();
bundle.putParcelable("allData", word);
bundle.putString("transition_name", word.getMSutras());
Fragment detailsFragment = new TermThreeDetailsFragment();
detailsFragment.setSharedElementEnterTransition(new MaterialContainerTransform());
detailsFragment.setArguments(bundle);
FragmentTransaction fT =((AppCompatActivity)context).getSupportFragmentManager().beginTransaction();
fT.setReorderingAllowed(true);
fT.addSharedElement(rsutras, rsutras.getTransitionName()); // Shared element!
fT.replace(R.id.fragment_container, detailsFragment);
fT.addToBackStack(null);
fT.commit();
}
}
}
RecyclerView Fragment Class(source)
public class ShowtermsTwoFragment extends Fragment {
private RecyclerView rv;
private EditText tV;
private Toolbar toolbar;
private LinearLayoutManager layoutManager;
private static DictionaryDB db;
private RecyclerViewAdapter rvAdapter;
private SearchView searchView = null;
private SearchView.OnQueryTextListener queryTextListener;
private List<Astadhyayi> wordsList = new ArrayList<>();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setExitTransition(new MaterialElevationScale(false));
setReenterTransition(new MaterialElevationScale(true));
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_terms_recyclerview, container, false);
return view;
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
toolbar = ((Toolbar) view.findViewById(R.id.toolbar_rv));
rv = view.findViewById(R.id.rvTerms);
tV = view.findViewById(R.id.tVinput);
//*********** TOOLBAR
AppCompatActivity activity = (AppCompatActivity) getActivity();
activity.setSupportActionBar(toolbar);
setHasOptionsMenu(true);
// new Get_DbData().execute();
databaseCheck();
recyclerCheck1();
postponeEnterTransition();
((ViewGroup) view.getParent()).getViewTreeObserver()
.addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
public boolean onPreDraw() {
startPostponedEnterTransition();
return true;
}
});
}
private void databaseCheck() {
String sanskritWord = getActivity().getIntent().getStringExtra("sanskritWord");
//*********** ### DATABASE OPENING ### ***********\\
db = DictionaryDB.getInstance(this.getActivity());
wordsList = db.getWords((sanskritWord));
}
private void recyclerCheck1() {
layoutManager = new LinearLayoutManager(getContext());
rv.setLayoutManager(layoutManager);
rv.setHasFixedSize(true);
DividerItemDecoration dividerItemDecoration = new DividerItemDecoration(rv.getContext(), layoutManager.getOrientation());
rv.addItemDecoration(dividerItemDecoration);
rvAdapter = new RecyclerViewAdapter(getContext(), wordsList, db);
rv.setAdapter(rvAdapter);
/////********** rvAdapter.setClickListener(this);
rvAdapter.notifyDataSetChanged();
}
}
Details Fragment Class(destination)
public class TermThreeDetailsFragment extends Fragment {
private TextView sutraTV,vrittiTV,padaTv,adhyayTV,sutraIdTV ;
private CoordinatorLayout coordinatorLayout;
private FloatingActionButton fabBtn;
private static DictionaryDB db;
private Astadhyayi word;
private BottomAppBar bottomAppBar;
private TextToSpeech pronunciation;
private AudioManager audio;
private String ttsID , trans;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
MaterialContainerTransform transform = new MaterialContainerTransform();
transform.setScrimColor(Color.TRANSPARENT);
setSharedElementEnterTransition(transform);
setSharedElementReturnTransition(transform);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.show_three_details, container, false);
view.findViewById(R.id.tvSutra).setTransitionName(word.getMSutras());
return view;
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
sutraTV = view.findViewById(R.id.tvSutra);
adhyayTV = view.findViewById(R.id.tVAdhyay);
padaTv = view.findViewById(R.id.tVPada);
sutraIdTV = view.findViewById(R.id.tVSutraId);
vrittiTV = view.findViewById(R.id.tvVritti);
fabBtn = view.findViewById(R.id.favFAB);
coordinatorLayout = view.findViewById(R.id.parentCordlayout);
bottomAppBar = view.findViewById(R.id.bottom_app_bar);
bundleCheckWithDb();
WordCheck();
}
private void bundleCheckWithDb() {
//*********** Geting Parcelable Data
word = new Astadhyayi(Parcel.obtain());
Bundle bundle = this.getArguments();
if (bundle != null) {
word = bundle.getParcelable("allData");
trans = bundle.getString("transition_name");
adhyayTV.setText(word.getMAdhyay());
padaTv.setText(word.getMPada());
sutraIdTV.setText(word.getMSutra_id());
sutraTV.setText(word.getMSutras());
vrittiTV.setText(word.getMVritti());
}
//*********** DATABASE OPENING
db = DictionaryDB.getInstance(this.getActivity());
}
private void WordCheck() {
if (word.mStatus != null && word.mStatus.equals(DictionaryDB.BOOKMARKED)) {
fabBtn.setImageResource(R.drawable.cards_heart);
} else {
fabBtn.setImageResource(R.drawable.cards_heart_white);
}
fabBtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
bookMarkWord(word, fabBtn);
}
});
}
}
Error im getting
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String com.sanskrit.mysearcher.models.Astadhyayi.getMSutras()' on a null object reference
at com.sanskrit.mysearcher.fragments.TermThreeDetailsFragment.onCreateView(TermThreeDetailsFragment.java:69)
From the current given information, I think you should do something like this:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
word = new Astadhyayi(Parcel.obtain());
Bundle bundle = this.getArguments();
if (bundle != null) {
word = bundle.getParcelable("allData");
}
View view = inflater.inflate(R.layout.show_three_details, container, false);
view.findViewById(R.id.tvSutra).setTransitionName(word.getMSutras());
return view;
}
Again, I am not sure what getMSutras() actually returns and if it's right to use that here.
Need help with android app (java)
My app starts with SplashActivity. During it I`m getting json via retrofit request and after successfull response I fill my DB
SplashActivity
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash);
ISplashInteractor splashInteractor = new SplashInteractor();
moviePresenter = new MoviePresenter(this, splashInteractor);
moviePresenter.initDB();
}
after DB successfully loaded automatically starts MovieListActivity
public class MovieListActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_movie_list);
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction transaction = fragmentManager.beginTransaction();
Fragment allMoviesFragment = new AllMoviesFragment();
String tag = "MovieList";
transaction.replace(R.id.main_container, allMoviesFragment, tag);
transaction.commit();
}
}
and at once list of movies loads inside inner fragment AllMoviesFragment(inside recyclerView). till this point everything is ok.
now I set onRecyclerViewItemClickListener - it must open another fragment inside MovieListActivity but instead of this - my app restarts from begining and I observe loading of SpalshActivity again(I put progressbar during request) and again my RecyclerView...
my RecyclerViewAdapter
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.ViewHolder> {
private List<MovieDetails> movieList;
private OnRecyclerViewItemClickListener onRecyclerViewItemClickListener;
public RecyclerViewAdapter(List<MovieDetails> movieList) {
this.movieList = movieList;
}
public void setOnRecyclerViewItemClickListener(OnRecyclerViewItemClickListener onRecyclerViewItemClickListener){
this.onRecyclerViewItemClickListener = onRecyclerViewItemClickListener;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.simple_selectable_list_item, parent, false);
return new ViewHolder(v);
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
MovieDetails movieDetails = (movieList.get(position));
holder.name.setText(movieDetails.getTitle());
holder.year.setText(String.valueOf(movieDetails.getReleaseYear()));
}
#Override
public int getItemCount() {
if (movieList == null)
return 0;
return movieList.size();
}
class ViewHolder extends RecyclerView.ViewHolder {
TextView name;
TextView year;
public ViewHolder(View itemView) {
super(itemView);
name = itemView.findViewById(R.id.movie_name);
year = itemView.findViewById(R.id.release_year);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(onRecyclerViewItemClickListener != null){
int position = getAdapterPosition();
if(position != RecyclerView.NO_POSITION){
onRecyclerViewItemClickListener.onRecyclerViewItemClick(position);
}
}
}
});
}
}
public interface OnRecyclerViewItemClickListener {
void onRecyclerViewItemClick(int position);
}
}
my AllMoviesFragment
public class AllMoviesFragment extends Fragment implements RecyclerViewAdapter.OnRecyclerViewItemClickListener {
private static final String CURR_MOVIE = "Current Movie";
private static final String TAG = "MSApp";
List<MovieDetails> movieList;
RecyclerView recyclerView;
public AllMoviesFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
movieList = App.getAppInstance().getDatabaseInstance().getMovieDao().getAllMovies();
movieList.sort(new Comparator<MovieDetails>() {
#Override
public int compare(MovieDetails o1, MovieDetails o2) {
return o2.getReleaseYear() - o1.getReleaseYear();
}
});
View resultView = inflater.inflate(R.layout.fragment_all_movies, container, false);
recyclerView = resultView.findViewById(R.id.recycler_view);
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getActivity());
recyclerView.setLayoutManager(layoutManager);
recyclerView.setHasFixedSize(true);
RecyclerViewAdapter adapter = new RecyclerViewAdapter(movieList);
adapter.setOnRecyclerViewItemClickListener(AllMoviesFragment.this);
recyclerView.setAdapter(adapter);
return resultView;
}
#Override
public void onRecyclerViewItemClick(int position) {
MovieDetails choosenMovie = movieList.get(position);
FragmentManager fragmentManager = getFragmentManager();
Fragment movieDetailsFragment = new MovieDetailsFragment();
Bundle args = new Bundle();
args.putParcelable(CURR_MOVIE, choosenMovie);
movieDetailsFragment.setArguments(args);
String tag = "MovieDetails";
FragmentTransaction transaction = fragmentManager.beginTransaction();
transaction.replace(R.id.main_container, movieDetailsFragment, tag);
transaction.addToBackStack(tag);
transaction.commit();
}
}
sorry for long post. I dont know how to cut it
I use App class for db access if it is important
#AkakiKapanadze
you was almost right
I didnot see the error message because it disappeared less 1 second
and class MovieDetailsFragment
after I remove binder of ButterKnife all work... I dont know WHY - I always use Butterknife inside Fragments
I get this error and I dont know how to fix it
java.lang.IndexOutOfBoundsException: Index: 2, Size: 2
at java.util.ArrayList.get(ArrayList.java:411)
at com.tijdelijk.firebasetest.Start$1.populateViewHolder(Start.java:69)
at com.tijdelijk.firebasetest.Start$1.populateViewHolder(Start.java:64)
I am working with firebase database and based on CategoryId I put the items in a arraylist for the SubCategories my code:
public class CategoryFragment extends Fragment {
View myFragment;
RecyclerView listCategory;
RecyclerView.LayoutManager layoutManager;
FirebaseRecyclerAdapter<Category, CategoryViewHolder> adapter;
FirebaseDatabase database;
DatabaseReference categories;
DatabaseReference subCategory;
public static CategoryFragment newInstance() {
CategoryFragment fragment = new CategoryFragment();
return fragment;
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
database = FirebaseDatabase.getInstance();
categories = database.getReference("Category");
subCategory = database.getReference("SubCategory");
}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
myFragment = inflater.inflate(R.layout.fragment_category, container, false);
listCategory = (RecyclerView) myFragment.findViewById(R.id.listCategory);
listCategory.setHasFixedSize(true);
layoutManager = new LinearLayoutManager(container.getContext());
listCategory.setLayoutManager(layoutManager);
loadCategories();
return myFragment;
}
private void loadCategories() {
adapter = new FirebaseRecyclerAdapter<Category, CategoryViewHolder>(
Category.class,
R.layout.category_layout,
CategoryViewHolder.class,
categories
) {
#Override
protected void populateViewHolder(CategoryViewHolder viewHolder, final Category model, int position) {
viewHolder.category_name.setText(model.getName());
Picasso.with(getActivity())
.load(model.getImage())
.into(viewHolder.category_image);
viewHolder.setItemClickListener(new ItemClickListener() {
#Override
public void onClick(View view, int position, boolean isLongClick) {
Intent startGame = new Intent(getActivity(), Start.class);
Common.categoryId = adapter.getRef(position).getKey();
loadSubCategory(Common.categoryId);
startActivity(startGame);
}
});
}
};
adapter.notifyDataSetChanged();
listCategory.setAdapter(adapter);
}
private void loadSubCategory(String categoryId) {
//Clear list if there are old subCategory
if (Common.subCategoryList.size() > 0) {
Common.subCategoryList.clear();
}
subCategory.orderByChild("CategoryId").equalTo(categoryId)
.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot postSnapshot : dataSnapshot.getChildren()) {
SubCategory ques = postSnapshot.getValue(SubCategory.class);
Common.subCategoryList.add(ques);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
}
in this activity I want to display also a recyclerview but this time based on the arraylist I got from the categoryfragment here is my code:
public class Start extends AppCompatActivity {
FirebaseDatabase database;
DatabaseReference subCategory;
FirebaseRecyclerAdapter<SubCategory, SubCategoryViewHolder> adapter;
RecyclerView listSubCategory;
RecyclerView.LayoutManager layoutManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_start);
database = FirebaseDatabase.getInstance();
subCategory = database.getReference("SubCategory");
listSubCategory = findViewById(R.id.listSubCategory);
listSubCategory.setHasFixedSize(true);
layoutManager = new LinearLayoutManager(getBaseContext());
listSubCategory.setLayoutManager(layoutManager);
loadSubCategories();
adapter.notifyDataSetChanged();
listSubCategory.setAdapter(adapter);
}
private void loadSubCategories() {
adapter = new FirebaseRecyclerAdapter<SubCategory, SubCategoryViewHolder>(
SubCategory.class,
R.layout.subcategory_layout,
SubCategoryViewHolder.class,
subCategory
) {
#Override
protected void populateViewHolder(SubCategoryViewHolder viewHolder, SubCategory model, int position) {
viewHolder.subcategory_nlname.setText(Common.subCategoryList.get(position).getLatijnseNaam());
viewHolder.subcategory_ltname.setText(Common.subCategoryList.get(position).getNederlandseNaam());
viewHolder.setItemClickListener(new ItemClickListener() {
#Override
public void onClick(View view, int position, boolean isLongClick) {
Intent startGame = new Intent(Start.this, Start.class);
Common.categoryId = adapter.getRef(position).getKey();
startActivity(startGame);
}
});
}
};
}
}
here is my viewholder:
public class SubCategoryViewHolder extends RecyclerView.ViewHolder
implements View.OnClickListener{
public TextView subcategory_nlname;
public TextView subcategory_ltname;
private ItemClickListener itemClickListener;
public SubCategoryViewHolder(View itemView) {
super(itemView);
subcategory_ltname = itemView.findViewById(R.id.latijnse_naam);
subcategory_nlname = itemView.findViewById(R.id.nederlandse_naam);
// itemView.findViewById(R.id.btnPlay).setOnClickListener(this);
}
public void setItemClickListener(ItemClickListener itemClickListener) {
this.itemClickListener = itemClickListener;
}
#Override
public void onClick(View view) {
itemClickListener.onClick(view,getAdapterPosition(),false);
}
}
IndexOutOfBoundException means that you are trying to access a value that is at an index out of the array.
In your case, you have an array of two values. So you have the keys 0 and 1. As said in the error, your code is trying to access the index 2, which does not exist.
You have to check that you are accessing an index that is in the range of values of the array.
Good day to you.
I want to pass a string value from my adapter class to my fragment. I tried storing the string in a bundle. To retrieve the value i used Bundle b = getArguments(); b.getString("key") the problem is im getting a null pointer exception. Below is the code that saves the string in a bundle. So my question is how can i pass a string value from adapterA to fragmentB.
Thanks in advance.
Adapter.java
public class ToDoRecyclerViewAdapter extends RecyclerView.Adapter<ToDoRecyclerViewAdapter.ViewHolder> {
private Context context;
private List<Aktivnost_> mValues;
private final OnListFragmentInteractionListener mListener;
public ToDoRecyclerViewAdapter td;
public ToDoRecyclerViewAdapter(List<Aktivnost_ > items, Context context, OnListFragmentInteractionListener listener) {
mValues = items;
mListener = listener;
this.context = context;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.fragment_todo, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(final ViewHolder holder, final int position) {
holder.mItem = mValues.get(position);
holder.mContentView.setText(mValues.get(position).getNaziv());
holder.mDateView.setText(mValues.get(position).getDatum());
holder.mView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (null != mListener) {
mListener.onListFragmentInteraction(holder.mItem);
Intent i = new Intent(context.getApplicationContext(), PodrobnostiActivity.class);
i.putExtra("task_id", mValues.get(position).getId_());
context.getApplicationContext().startActivity(i);
Toast.makeText(v.getContext(), "task - " + mValues.get(position).getId_(), Toast.LENGTH_SHORT).show();
}
}
});
holder.mView.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(final View v) {
AlertDialog.Builder adb = new AlertDialog.Builder(v.getContext());
CharSequence meni[] = new CharSequence[] {"DOING", "FINISHED"};
adb.setItems(meni, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
if(i == 0) {
Bundle b = new Bundle();
DoingFragment d = new DoingFragment();
mValues.get(i).setStanje("doing");
b.putString("doing", mValues.get(i).getStanje());
d.setArguments(b);
} else {
mValues.get(i).setStanje("koncano");
}
}
});
AlertDialog alertDialog = adb.create();
alertDialog.setCancelable(true);
alertDialog.show();
return true;
}
});
}
#Override
public int getItemCount() {
return mValues.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
public final View mView;
public final TextView mContentView;
public final TextView mDateView;
public long id;
public Aktivnost_ mItem;
public ViewHolder(View view) {
super(view);
mView = view;
this.id = id;
mDateView = (TextView) view.findViewById(R.id.Date);
mContentView = (TextView) view.findViewById(R.id.content);
}
#Override
public String toString() {
return super.toString() + " '" + mContentView.getText() + "'";
}
}
}
And i want to get the value i set in bundle in this fragment.
Fragment.java
public class DoingFragment extends Fragment {
DoingFragmentRecyclerViewAdapter mAdapter;
private OnListFragmentInteractionListener mListener;
public DoingFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_doingfragment_list, container, false);
RecyclerView recyclerView = (RecyclerView) view.findViewById(R.id.list_doing);
recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
recyclerView.addItemDecoration(new DividerItemDecoration(getContext(), LinearLayoutManager.VERTICAL));
mAdapter = new DoingFragmentRecyclerViewAdapter(listAktivnosti(),mListener);
recyclerView.setAdapter(mAdapter);
return view;
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnListFragmentInteractionListener) {
mListener = (OnListFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnListFragmentInteractionListener");
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
public interface OnListFragmentInteractionListener {
void onListFragmentInteraction1(Aktivnost_ item);
}
AppDatabase db;
public void openDB() {
db = new AppDatabase(getContext());
db.open();
}
Aktivnost_ ak;
List<Aktivnost_> array;
public List<Aktivnost_> listAktivnosti() {
array = new ArrayList<>();
openDB();
Bundle b = getArguments();
Cursor cursor = db.getAllRows(b.getString("doing"));
while(cursor.moveToNext()) {
ak = new Aktivnost_();
ak.setId_(cursor.getLong(cursor.getColumnIndex("_id")));
ak.setNaziv(cursor.getString(cursor.getColumnIndex("naziv")));
ak.setDatum(cursor.getString(cursor.getColumnIndex("datum")));
ak.setFk_projekt(cursor.getInt(cursor.getColumnIndex("fk_projekt")));
ak.setUdeleženci(cursor.getString(cursor.getColumnIndex("udelezenci")));
ak.setStanje(cursor.getString(cursor.getColumnIndex("stanje")));
array.add(ak);
}
return array;
}
}
From the code, I can see you are only setting the Bundle parameters in Fragment object, but not using that fragment object further.
You need to display that fragment object first, then it will reflect into your target fragment.
This is the edited version of my Fragment class inside my main activity. There were some bugs- it was not displaying anything and it was no longer saving the data to the database.
public static class DummyFragment extends Fragment {
int color;
public DummyFragment() {
}
#SuppressLint("ValidFragment")
public DummyFragment(int color) {
this.color = color;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.dummy_fragment, container, false);
final RecyclerView recyclerView = (RecyclerView) view.findViewById(R.id.dummyfrag_scrollableview);
final FrameLayout frameLayout = (FrameLayout) view.findViewById(R.id.dummyfrag_bg);
frameLayout.setBackgroundColor(color);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity().getBaseContext());
recyclerView.setLayoutManager(linearLayoutManager);
recyclerView.setHasFixedSize(true);
DatabaseReference mDatabaseGig;
final List<Dessert> dessertList;
// get the gig database
mDatabaseGig = FirebaseDatabase.getInstance().getReference("Gig Posts");
dessertList = new ArrayList<>();
mDatabaseGig.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
// dessertList.clear();
for(DataSnapshot gigSnapshot: dataSnapshot.getChildren()){
Dessert dessert = gigSnapshot.getValue(Dessert.class);
dessertList.add(dessert);
}
DessertAdapter adapter = new DessertAdapter(getContext());
recyclerView.setAdapter(adapter);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
// possible to put progress dialogue
return view;
}
}
I already got the saving to firebase working perfectly and I'm using the MVC model - I created an adapter, a model and wired it to the main activity but my problem is how to use this model into the onAddValueEventChangedListener();
public class DessertAdapter extendsRecyclerView.Adapter<DessertAdapter.DessertVh> {
private List<Dessert> desserts = new ArrayList<>();
private static final int VIEW_TYPE_EMPTY_LIST_PLACEHOLDER = 0;
private static final int VIEW_TYPE_OBJECT_VIEW = 1;
private Context context;
// TODO: placeholder stuff here
#Override
public int getItemViewType(int position) {
if (desserts.isEmpty()) {
return VIEW_TYPE_EMPTY_LIST_PLACEHOLDER;
} else {
return VIEW_TYPE_OBJECT_VIEW;
}
}
public DessertAdapter(Context context) {
this.context = context;
this.desserts = desserts;
desserts = Dessert.prepareDesserts(
context.getResources().getStringArray(R.array.dessert_names),
context.getResources().getStringArray(R.array.dessert_descriptions),
context.getResources().getStringArray(R.array.dessert_amounts));
}
// TODO: another placeholder stuff here
#Override
public DessertVh onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
View view = inflater.inflate(R.layout.item_dessert, parent, false);
return new DessertAdapter.DessertVh(view);
}
#Override
public void onBindViewHolder(DessertVh holder, int position) {
Dessert dessert = desserts.get(position);
holder.mName.setText(dessert.getName());
holder.mDescription.setText(dessert.getDescription());
holder.mFirstLetter.setText(String.valueOf(dessert.getFirstLetter()));
holder.mPrice.setText(String.valueOf(dessert.getAmount()));
}
#Override
public int getItemCount() {
// if nothing, return null,
// else return the number of items in the list
return desserts == null ? 0 : desserts.size();
}
public static class DessertVh extends RecyclerView.ViewHolder {
private TextView mName;
private TextView mPrice;
private TextView mDescription;
private TextView mFirstLetter;
public DessertVh(View itemView) {
super(itemView);
mName = (TextView) itemView.findViewById(R.id.txt_name);
mPrice = (TextView) itemView.findViewById(R.id.txt_price);
mDescription = (TextView) itemView.findViewById(R.id.txt_desc);
mFirstLetter = (TextView) itemView.findViewById(R.id.txt_firstletter);
}
}
}
main activity where the tabs are displayed
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tabs_header);
// get the gig database
mDatabaseGig = FirebaseDatabase.getInstance().getReference("Gig Posts");
dessertList = new ArrayList<>();
// Configure sign-in to request the user's ID, email address, and basic
// profile. ID and basic profile are included in DEFAULT_SIGN_IN.
GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestEmail()
.build();
mGoogleApiClient = new GoogleApiClient.Builder(this)
.enableAutoManage(this , this )
.addApi(Auth.GOOGLE_SIGN_IN_API, gso)
.build();
This handles the display of the data
#Override
public void onStart(){
super.onStart();
mFirebaseAuth.addAuthStateListener(firebaseAuthListener);
// load the data from database here
mDatabaseGig.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
dessertList.clear();
for(DataSnapshot gigSnapshot: dataSnapshot.getChildren()){
Dessert dessert = gigSnapshot.getValue(Dessert.class);
dessertList.add(dessert);
}
// maybe this will work?
DummyFragment dummyFragment = new DummyFragment();
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
some code missing here but still part of mainactivity
This is the Dummy Fragment Class inside the main activity
public static class DummyFragment extends Fragment {
int color;
public DummyFragment() {
}
#SuppressLint("ValidFragment")
public DummyFragment(int color) {
this.color = color;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.dummy_fragment, container, false);
final FrameLayout frameLayout = (FrameLayout) view.findViewById(R.id.dummyfrag_bg);
frameLayout.setBackgroundColor(color);
RecyclerView recyclerView = (RecyclerView) view.findViewById(R.id.dummyfrag_scrollableview);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity().getBaseContext());
recyclerView.setLayoutManager(linearLayoutManager);
recyclerView.setHasFixedSize(true);
// possible to put progress dialogue
DessertAdapter adapter = new DessertAdapter(getContext());
recyclerView.setAdapter(adapter);
return view;
}
}
Put the Firebase code inside the Fragment, not the Activity and also pass the dessertList as a param to the DessertAdapter.
Example:
public static class DummyFragment extends Fragment {
int color;
public DummyFragment() {
}
#SuppressLint("ValidFragment")
public DummyFragment(int color) {
this.color = color;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.dummy_fragment, container, false);
final RecyclerView recyclerView = (RecyclerView) view.findViewById(R.id.dummyfrag_scrollableview);
final FrameLayout frameLayout = (FrameLayout) view.findViewById(R.id.dummyfrag_bg);
frameLayout.setBackgroundColor(color);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity().getBaseContext());
recyclerView.setLayoutManager(linearLayoutManager);
recyclerView.setHasFixedSize(true);
DatabaseReference mDatabaseGig;
final List<Dessert> dessertList;
// get the gig database
mDatabaseGig = FirebaseDatabase.getInstance().getReference("Gig Posts");
dessertList = new ArrayList<>();
DessertAdapter adapter = new DessertAdapter(getContext(), dessertList);
recyclerView.setAdapter(adapter);
mDatabaseGig.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
// dessertList.clear();
for(DataSnapshot gigSnapshot: dataSnapshot.getChildren()){
Dessert dessert = gigSnapshot.getValue(Dessert.class);
dessertList.add(dessert);
adapter.notifyDataSetChanged();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
// possible to put progress dialogue
return view;
}
}