When I start activity with fragment, recyclerview and adapter the app is stopping. I don't know where the problem is. I've tried different methods.
My logcat:
java.lang.NullPointerException: Attempt to invoke virtual method 'void
android.support.v7.widget.RecyclerView.setAdapter(android.support.v7.widget.RecyclerView$Adapter)'
on a null object reference
at com.orthodox.FeedActivity.onStart(FeedActivity.java:133)
at android.support.v4.app.Fragment.performStart(Fragment.java:2287)
My code:
public class FeedActivity extends Fragment{
private RecyclerView mBlogList;
private Query mQuery;
private Query mQueryck;
private DatabaseReference mDatabaseUsers;
private FirebaseUser mCurrent;
private FirebaseAuth mAuth;
private FirebaseAuth.AuthStateListener mAuthListener;
FirebaseRecyclerAdapter mAdapter;
public FeedActivity() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final FragmentActivity c = getActivity();
View layout = inflater.inflate(R.layout.fragment_feed, container, false);
return layout;
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
mBlogList = (RecyclerView) view.findViewById(R.id.blog_list);
mBlogList.setHasFixedSize(true);
LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
mBlogList.setLayoutManager(layoutManager);
mAuth = FirebaseAuth.getInstance();
mAuthListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
if(firebaseAuth.getCurrentUser() == null){
Intent loginIntent = new Intent(getActivity(), SignUpActivity.class);
loginIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(loginIntent);
}
}
};
mQuery = FirebaseDatabase.getInstance().getReference().child("Blog").limitToLast(20);
mQuery.keepSynced(true);
mQueryck = FirebaseDatabase.getInstance().getReference().child("Block").limitToLast(20);
mQueryck.keepSynced(true);
mDatabaseUsers = FirebaseDatabase.getInstance().getReference().child("users");
mDatabaseUsers.keepSynced(true);
mCurrent = mAuth.getCurrentUser();
}
#Override
public void onStart() {
super.onStart();
mAuth.addAuthStateListener(mAuthListener);
FirebaseRecyclerOptions<User> options = new FirebaseRecyclerOptions.Builder<User>().setQuery(mQuery, User.class).build();
FirebaseRecyclerOptions<User> optionss = new FirebaseRecyclerOptions.Builder<User>().setQuery(mQueryck, User.class).build();
mAdapter = new FirebaseRecyclerAdapter<User, BlogViewHolder>(options) {
#Override
public BlogViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
// Create a new instance of the ViewHolder
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.blog_row, parent, false);
return new BlogViewHolder(view);
}
#Override
protected void onBindViewHolder(BlogViewHolder viewHolder, int position, User model) {
final String post_key = getRef(position).getKey();
viewHolder.setTitle(model.getTitle());
viewHolder.setDesc(model.getDesc());
viewHolder.setTime(model.getFirstname());
viewHolder.setImage(getApplicationContext(), model.getImage());
}
};
mBlogList.setAdapter(mAdapter);
mAdapter.startListening();
mAdapter = new FirebaseRecyclerAdapter<User, BlogViewHolder>(optionss) {
#Override
protected void onBindViewHolder(BlogViewHolder viewHolder, int position, User model) {
final String post_key = getRef(position).getKey();
viewHolder.setTitle(model.getTitle());
viewHolder.setDesc(model.getDesc());
viewHolder.setTime(model.getFirstname());
viewHolder.setImage(getApplicationContext(), model.getImage());
viewHolder.mView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent bsingle = new Intent(getActivity(), SinglePostActivity.class);
bsingle.putExtra("post", post_key);
startActivity(bsingle);
}
});
}
#Override
public BlogViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.blog_row, parent, false);
return new BlogViewHolder(view);
}
};
}
public static class BlogViewHolder extends RecyclerView.ViewHolder {
View mView;
public BlogViewHolder(View itemView) {
super(itemView);
mView = itemView;
}
public void setTitle(String title){
TextView post_title = (TextView) mView.findViewById(R.id.post_title);
post_title.setText(title);
}
public void setDesc(String desc){
TextView post_desc = (TextView) mView.findViewById(R.id.post_desc);
post_desc.setText(desc);
}
public void setImage(Context ctx, String image){
if (image != null) {
ImageView post_image = (ImageView) mView.findViewById(R.id.post_image);
Picasso.with(ctx).load(image).into(post_image);
}
else {
ImageView post_image = (ImageView) mView.findViewById(R.id.post_image);
post_image.setVisibility(View.GONE);
}
}
public void setTime(String time){
TextView post_time = (TextView) mView.findViewById(R.id.post_username);
post_time.setText(time);
}
Initialize your all views in onCreateView method.
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final FragmentActivity c = getActivity();
View layout = inflater.inflate(R.layout.fragment_feed, container, false);
mBlogList = (RecyclerView) layout.findViewById(R.id.blog_list);
return layout;
}
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.
I cannot access the ID of the item to view it in ToastMessage, or even store it in the database (use Room DataBase)
I have tried but the message does not appear
I need the reference ID to use for database storage and complete the process for storing the shopping cart
itemAdapter.java
public class itemAdapter extends RecyclerView.Adapter<itemAdapter.ItemViewHolder> {
private Context context;
private ArrayList<Items> arrayList;
private AdapterView.OnItemClickListener listener;
public itemAdapter(Context context, ArrayList<Items> arrayList) {
this.context = context;
this.arrayList = arrayList;
}
#NonNull
#Override
public ItemViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(context).inflate(R.layout.item, parent, false);
return new ItemViewHolder(v);
}
#Override
public void onBindViewHolder(#NonNull ItemViewHolder holder, int position) {
holder.name.setText(arrayList.get(position).getItemName());
holder.desc.setText(arrayList.get(position).getItemDesc());
holder.price.setText(arrayList.get(position).getItemPrice());
holder.add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(context,arrayList.get(position).getItemIid(),Toast.LENGTH_SHORT);
}
});
holder.name.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(context,arrayList.get(position).getItemPrice(),Toast.LENGTH_SHORT);
}
});
}
#Override
public int getItemCount() {
return arrayList.size();
}
class ItemViewHolder extends RecyclerView.ViewHolder {
TextView name, desc, price;
ImageView remove, add;
public ItemViewHolder(#NonNull View itemView) {
super(itemView);
name = itemView.findViewById(R.id.tvName);
desc = itemView.findViewById(R.id.tvDesc);
price = itemView.findViewById(R.id.tvPrice);
remove = itemView.findViewById(R.id.btnDelete);
add = itemView.findViewById(R.id.btnAdd);
}
}
}
MealsFragment.java
public class MealsFragment extends Fragment {
public MealsFragment() {
// Required empty public constructor
}
RecyclerView recyclerView;
itemAdapter adapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_meals, container, false);
}
#Override
public void onViewCreated( View view, Bundle savedInstanceState) {
ArrayList<Items> ItemsList = (ArrayList<Items>) RoomDatabaseSingleton.getInstance(getContext().getApplicationContext())
.getAppDatabase()
.getDao()
.getItems("meals");
recyclerView = view.findViewById(R.id.rvMeals);
RecyclerView.LayoutManager manager = new LinearLayoutManager(
getContext(), RecyclerView.VERTICAL, false);
recyclerView.setLayoutManager(manager);
adapter = new itemAdapter(getContext(), ItemsList);
recyclerView.setAdapter(adapter);
}
}
Try the following instead
holder.add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(context,arrayList.get(position).getItemIid(),Toast.LENGTH_SHORT).show();
}
});
holder.name.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(context,arrayList.get(position).getItemPrice(),Toast.LENGTH_SHORT).show();
}
});
The static method makeText of Toast is used to create the Toast object and show() method on the Toast object is used to display the Toast
i have a ListFragment which contain a recycler view and i want to make it when an item is clicked the DetailFragmentdisplay beside it in a multi-pane layout i know how to create a multi-pane layout but i don't know how to send data between fragments because i don't where to initialize the click to send data, where should i initialize the on click so it passes data from ListFragment to DetailFragment and display it ? * note: i am getting my data from a dialog fragment
MainActivity
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
FragmentManager fm = getSupportFragmentManager();
Fragment fragment = fm.findFragmentById(R.id.fragment_list_container);
if (fragment == null) {
fragment = new ListFragment();
fm.beginTransaction()
.add(R.id.fragment_list_container, fragment)
.commit();
}
}
}
ListFragment
public class ListFragment extends Fragment implements MyDialog.OnInputSelected {
#Override
public void sendInput(String title, Uri imageUri) {
Wallpaper wallpaper = new Wallpaper(title, imageUri);
wallpaperList.add(wallpaper);
passWallpaper.passWallpaperMethod(wallpaper);
}
private List<Wallpaper> wallpaperList;
private RecyclerViewAdapter recyclerViewAdapter;
private RecyclerView recyclerView;
private FloatingActionButton fabOpenDialog;
public ListFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_list, container, false);
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
fabOpenDialog = view.findViewById(R.id.fab_open_dialog);
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
fabOpenDialog.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
MyDialog dialog = new MyDialog();
dialog.setTargetFragment(ListFragment.this, 1);
dialog.show(getFragmentManager(), "MyDialog");
}
});
wallpaperList = new ArrayList<>();
recyclerView = getView().findViewById(R.id.recyclerview);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
recyclerViewAdapter = new RecyclerViewAdapter(wallpaperList, getActivity());
recyclerView.setAdapter(recyclerViewAdapter);
}
}
RecyclerViewAdapter
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.ViewHolder> {
private List<Wallpaper> wallpaperList;
private Context context;
public RecyclerViewAdapter(List<Wallpaper> wallpaperList, Context context) {
this.wallpaperList = wallpaperList;
this.context = context;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.recycler_row, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, int position) {
Wallpaper wallpaper = wallpaperList.get(position);
holder.iv.setImageURI(wallpaper.getImageUrl());
holder.tvTitle.setText(wallpaper.getTitle());
}
#Override
public int getItemCount() {
return wallpaperList.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
public View view;
public ImageView iv;
public TextView tvTitle;
public ViewHolder(#NonNull View itemView) {
super(itemView);
view = itemView;
iv = itemView.findViewById(R.id.row_iv);
tvTitle = itemView.findViewById(R.id.row_tv_title);
}
}
}
DetailActivity
public class DetailsActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_details);
FragmentManager fm = getSupportFragmentManager();
Fragment fragment = fm.findFragmentById(R.id.details_container);
if (fragment == null) {
fragment = new DetailsFragment();
fm.beginTransaction()
.add(R.id.details_container, fragment)
.commit();
}
}
}
DetailsFrgament
public class DetailsFragment extends Fragment {
private TextView tvTitle;
private ImageView ivWallpaper;
public DetailsFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_details, container, false);
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
tvTitle = view.findViewById(R.id.fragment_details_tv_title);
ivWallpaper = view.findViewById(R.id.details_fragment_iv_wallpaper);
}
DialogFragment
public class MyDialog extends DialogFragment implements View.OnClickListener {
public interface OnInputSelected {
void sendInput(String title, Uri imageUri);
}
public OnInputSelected onInputSelected;
#Override
public void onAttach(#NonNull Context context) {
super.onAttach(context);
try {
// "getTargetFragment()" instead of "getActivity()"
onInputSelected = (OnInputSelected) getTargetFragment();
} catch (ClassCastException e) {
Log.d("DialogFragment", "Class Cast Exception: " + e.getMessage());
}
}
TextView yes, no;
private EditText etTitle;
private ImageView imageView;
private Uri imageUri;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
setCancelable(false);
return inflater.inflate(R.layout.dialog_add_wallpaper, null);
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
yes = view.findViewById(R.id.dialog_tv_ok);
no = view.findViewById(R.id.dialog_tv_cancel);
imageView = view.findViewById(R.id.dialog_iv_add_image);
imageView.setOnClickListener(this);
yes.setOnClickListener(this);
no.setOnClickListener(this);
etTitle = view.findViewById(R.id.et_add_title);
}
#NonNull
#Override
public Dialog onCreateDialog(#Nullable Bundle savedInstanceState) {
Dialog dialog = super.onCreateDialog(savedInstanceState);
dialog.setTitle("Title testing");
return dialog;
}
#Override
public void onClick(View v) {
if (v.getId() == R.id.dialog_tv_ok) {
onInputSelected.sendInput(etTitle.getText().toString().trim(), imageUri);
dismiss();
} else if (v.getId() == R.id.dialog_tv_cancel) {
onInputSelected.sendInput("got canceled", null);
dismiss();
} else {
Intent imageIntent = new Intent(Intent.ACTION_GET_CONTENT);
imageIntent.setType("image/*");
startActivityForResult(imageIntent, 1);
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 1 && resultCode == Activity.RESULT_OK && data != null &&
data.getData() != null) {
imageUri = data.getData();
imageView.setImageURI(imageUri);
}
}
}
You can initialize clickListener in onBindViewHolder in RecyclerViewAdapter and inside something like this:
holder.iv.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
((MainActivity) view.getContext()).getFragmentManager().beginTransaction()
.replace(R.id.fragment_list_container, new DetailsFrgament())
.commit();
}
});
For transfering data you can use Bundle
I am trying to add a button inside my recyclerview's cardview holder.
When the button is pressed, the user is directed to an external website when clicked.I also want to add multiple buttons to each cardview so that each button leads to a different website when clicked. How to do this?
My code:
Fragment class (i am using fragments):
public class BooksFragment extends Fragment {
private RecyclerView mRecyclerView;
private RecyclerView.Adapter mAdapter;
private RecyclerView.LayoutManager mLayoutManager;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_books, container, false);
mLayoutManager = new LinearLayoutManager(this.getActivity());
return view;
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
ArrayList<exampleItemBooks> exampleList = new ArrayList<>();
exampleList.add(new exampleItemBooks(R.drawable.thritysixstrategems, "The Thirty-Six Stratagems", "300 years ago, an unknown author compiled the Stratagems, a strangely seductive meditation on deception.", "-Unknown Author"));
exampleList.add(new exampleItemBooks(R.drawable.medidations, "Meditations", "A book by the great Stoic Roman Emperor Marcus Aurelius. The book was written in Koine Greek, during the Emperor's reign.", "-Marcus Aurelius"));
mRecyclerView = view.findViewById(R.id.recyclerViewBooks);
mRecyclerView.setHasFixedSize(false);
mAdapter = new exampleBooksAdapter(exampleList);
mRecyclerView.setLayoutManager(mLayoutManager);
mRecyclerView.setAdapter(mAdapter);
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
}
Adapter:
public class exampleBooksAdapter extends RecyclerView.Adapter<exampleBooksAdapter.ExampleViewHolder> {
private ArrayList<exampleItemBooks> mExampleList;
public static class ExampleViewHolder extends RecyclerView.ViewHolder {
public ImageView mImageView;
public TextView mTextView1;
public TextView mTextView2;
public TextView mTextView3;
public ExampleViewHolder(View itemView) {
super(itemView);
mImageView = itemView.findViewById(R.id.imageViewCards);
mTextView1 = itemView.findViewById(R.id.textViewCard1);
mTextView2 = itemView.findViewById(R.id.textViewCard2);
mTextView3 = itemView.findViewById(R.id.textViewCard3);
}
}
public exampleBooksAdapter(ArrayList<exampleItemBooks> exampleItemBooks) {
mExampleList = exampleItemBooks;
}
#Override
public ExampleViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.example_item_books, parent, false);
ExampleViewHolder evh = new ExampleViewHolder(v);
return evh;
}
#Override
public void onBindViewHolder(#NonNull ExampleViewHolder holder, int position) {
exampleItemBooks currentItem = mExampleList.get(position);
holder.mImageView.setImageResource(currentItem.getImageResource());
holder.mTextView1.setText(currentItem.getText1());
holder.mTextView2.setText(currentItem.getText2());
holder.mTextView3.setText(currentItem.getText3());
}
#Override
public int getItemCount() {
return mExampleList.size();
}
}
ArrayList class:
private int mImageResource;
private String mText1;
private String mText2;
private String mText3;
public exampleItemBooks(int imageResource, String text1, String text2, String text3) {
mImageResource = imageResource;
mText1 = text1;
mText2 = text2;
mText3 = text3;
}
public int getImageResource() {
return mImageResource;
}
public String getText1() {
return mText1;
}
public String getText2() {
return mText2;
}
public String getText3() {
return mText3;
}
}
Add a button to your viewholder layout and
#Override
public void onBindViewHolder(#NonNull ExampleViewHolder holder, int position) {
exampleItemBooks currentItem = mExampleList.get(position);
...
holder.mButton.setTag("URL OF THE SITE");
holder.mButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Take user to browser.
}
});
}
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;
}