RecyclerView Doesn't Update The List After Adding New Item - android

I am fresher in android coding.
I am in a project that using tablayout, viewpager 2, fragements, bottom navigation
I designed two fragments, each in a tab, one for inputting items (fragment 1 in tab 1), one to show the items with a recyclerview.
The data will be stored with (and get from) Room Database.
I meet a trouble, the input items can not show immediately on recyclerview (in fragment 2, in tab 2), it has to restart the app to see it updated, noted that in the input fragment there is a toast message shows that it is done stored the items in its database.
Could you please help me to find out where i am stucking with the code ? I appreciate a lot :-*
View mView;
EditText addTitle;
EditText addContent;
ImageButton btnSave;
public WriteFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
mView = inflater.inflate(R.layout.fragment_write, container, false);
addTitle = mView.findViewById(R.id.edt_add_title);
addContent = mView.findViewById(R.id.edt_add_content);
btnSave = mView.findViewById(R.id.btn_save);
btnSave.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) { addItems();
}
});
hideSoftKeyboard();
return mView;
}
private void addItems() {
String strTitle = addTitle.getText().toString().trim(); //trim dùng để xóa ký tự trắng ở đầu và cuối trong edittext
String strContent = addContent.getText().toString().trim();
if (TextUtils.isEmpty(strTitle)|| TextUtils.isEmpty(strContent)){
return;
}
ItemsObject itemsObject = new ItemsObject(strTitle,strContent);
MainActivity.diaryDatabase.getInstance(getActivity()).userDAO().insert(itemsObject);
Toast.makeText(getActivity(),"Successfully Added",Toast.LENGTH_SHORT).show();
//thêm dữ liệu thành công thì cần phải reset hint trong trường nhập dữ liệu:
addTitle.setText("");
addContent.setText("");
hideSoftKeyboard(); //ẩn bàn phím ảo
}
public void hideSoftKeyboard() {
try {
InputMethodManager inputMethodManager = (InputMethodManager)
getActivity().getSystemService(Activity.INPUT_METHOD_SERVICE);
inputMethodManager.hideSoftInputFromWindow(getActivity().getCurrentFocus().getWindowToken(), 0);
} catch (NullPointerException exception) {
exception.printStackTrace();
}
}
}`
code in fragment 2:
package com.haki.mysimplehakidiarynotes.fragments.diary_tabs;
import android.os.Bundle;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.haki.mysimplehakidiarynotes.ItemsAdapter;
import com.haki.mysimplehakidiarynotes.ItemsObject;
import com.haki.mysimplehakidiarynotes.MainActivity;
import com.haki.mysimplehakidiarynotes.R;
import java.util.ArrayList;
import java.util.List;
public class DiaryLogFragment extends Fragment {
View mView;
private RecyclerView rcvItems;
private ItemsAdapter itemsAdapter;
private List<ItemsObject> itemsObjectList;
public DiaryLogFragment(){
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
mView = inflater.inflate(R.layout.fragment_diary_log, container, false);
rcvItems =mView.findViewById(R.id.rcv_items);
itemsAdapter = new ItemsAdapter();
itemsObjectList = DiaryDatabase.getInstance(getActivity()).userDAO().getListUser(); //hiển thị danh sách
itemsAdapter.setData(itemsObjectList);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity());
rcvItems.setLayoutManager(linearLayoutManager);
rcvItems.setFocusable(true);
rcvItems.setAdapter(itemsAdapter);
return mView;
}
}
package com.haki.mysimplehakidiarynotes;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.ramotion.foldingcell.FoldingCell;
import java.util.List;
public class ItemsAdapter extends RecyclerView.Adapter<ItemsAdapter.ItemViewHolder>{
private List<ItemsObject> mListItems;
public void setData(List<ItemsObject> list) {
this.mListItems =list;
notifyDataSetChanged();
}
#NonNull
#Override
public ItemViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).
inflate(R.layout.layout_items, parent, false);
return new ItemViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull ItemViewHolder holder, int position) {
ItemsObject itemsObject =mListItems.get(position);
if (itemsObject==null){
return;
}
holder.txtTitle.setText(itemsObject.getTitle());
holder.txtContent.setText(itemsObject.getContent());
holder.foldingCell.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
holder.foldingCell.toggle(false);
}
});
}
#Override
public int getItemCount() {
if (mListItems!=null){
return mListItems.size();
}
return 0;
}
public class ItemViewHolder extends RecyclerView.ViewHolder {
FoldingCell foldingCell;
TextView txtTitle;
TextView txtContent;
public ItemViewHolder(#NonNull View itemView) {
super(itemView);
foldingCell =itemView.findViewById(R.id.folding_cell);
txtTitle =itemView.findViewById(R.id.tv_title);
txtContent =itemView.findViewById(R.id.tv_content);
}
}
}

Related

passing string variable from recyclerview to fragment

i try to get the name of the movies which are in recycler view n store in variable 'name' but how do i pass in to dictionary fragment n set it on definitionn(edittext). i tried with this code but it shows empty
i try to get the name of the movies which are in recycler view n store in variable 'name' but how do i pass in to dictionary fragment n set it on definitionn(edittext). i tried with this code but it shows empty
import android.net.Uri;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.RecyclerView;
import java.util.ArrayList;
import java.util.List;
// item of recyclerview was not visible until included
app:layoutManager="android.support.v7.widget.LinearLayoutManager">
public class MainActivity extends AppCompatActivity {
RecyclerView recyclerView;
RecyclerAdapter recyclerAdapter;
List<String> moviesList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
moviesList = new ArrayList<>();
recyclerView = findViewById(R.id.recyclerView);
recyclerAdapter = new RecyclerAdapter(moviesList);
recyclerView.setAdapter(recyclerAdapter);
DividerItemDecoration dividerItemDecoration = new
DividerItemDecoration(this, DividerItemDecoration.VERTICAL);
recyclerView.addItemDecoration(dividerItemDecoration);
moviesList.add("IronMan");
moviesList.add("The Incredible Hulk");
moviesList.add("Iron Man 2");
moviesList.add("Thor");
moviesList.add("Captain America: The First Avenger");
moviesList.add("The Avengers");
moviesList.add("Iron Man 3");
moviesList.add("Thor: The Dark World");
moviesList.add("Captain America: The Winter Soldier");
moviesList.add("Guardians of the Galaxy");
moviesList.add("Avengers: Age of Ultron");
moviesList.add("Ant-Man");
moviesList.add("Captain America: Civil War");
moviesList.add("Doctor Strange");
moviesList.add("Guardians of the Galaxy Vol. 2");
moviesList.add("Spider-Man: Homecoming");
moviesList.add("Thor: Ragnarok");
moviesList.add("Black Panther");
moviesList.add("Avengers: Infinity War");
moviesList.add("Ant-Man and the Wasp");
moviesList.add("Captain Marvel");
moviesList.add("Avengers: Endgame");
moviesList.add("Spider-Man: Far From Home");
}
}
import android.support.annotation.NonNull;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
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 android.widget.Toast;
import java.util.List;
public class RecyclerAdapter extends
RecyclerView.Adapter<RecyclerAdapter.ViewHolder> {
String name="";
private static final String TAG = "RecyclerAdapter";
List<String> moviesList;
public RecyclerAdapter(List<String> moviesList) {
this.moviesList = moviesList;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int
viewType) {
LayoutInflater layoutInflater =
LayoutInflater.from(parent.getContext());
View view = layoutInflater.inflate(R.layout.row_item, parent,
false);
ViewHolder viewHolder = new ViewHolder(view);
return viewHolder;
}
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, int
position) {
holder.rowCountTextView.setText(String.valueOf(position));
holder.textView.setText(moviesList.get(position));
}
#Override
public int getItemCount() {
return moviesList.size();
}
class ViewHolder extends RecyclerView.ViewHolder implements
View.OnClickListener {
ImageView imageView;
TextView textView, rowCountTextView;
public ViewHolder(#NonNull View itemView) {
super(itemView);
imageView = itemView.findViewById(R.id.imageView);
textView = itemView.findViewById(R.id.textView);
rowCountTextView =
itemView.findViewById(R.id.rowCountTextView);
itemView.setOnClickListener(this);
itemView.setOnLongClickListener(new
View.OnLongClickListener() {
#Override
public boolean onLongClick(View view) {
moviesList.remove(getAdapterPosition());
notifyItemRemoved(getAdapterPosition());
return true;
}
});
}
#Override
public void onClick(View view) {
name=moviesList.get(getAdapterPosition()).toString();
AppCompatActivity activity=(AppCompatActivity)
view.getContext();
Fragment myfragment = new Dictionary();
activity.getSupportFragmentManager().beginTransaction().
replace(R.id.activitymain,myfragment).addToBackStack(null).commit();
}
}
}
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
public class Dictionary extends Fragment {
public EditText definitionnn;
public Dictionary() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_dictionary, container, false);
definitionnn = (EditText) v.findViewById(R.id.definition);
RecyclerAdapter recycle = new RecyclerAdapter(null);
String word = recycle.name;
return v;
}
#Override
public void onStart() {
super.onStart();
RecyclerAdapter recycle = new RecyclerAdapter(null);
String word = recycle.name;
definitionnn.setText(word);
}
}
The problem is that in your OnClick() Method you create and add the new Dictionary Fragment without passing the value you want. Something like this would be your solution.
In your RecyclerAdapter class:
Bundle bundle = new Bundle();
bundle.putString(yourVariable, "word");
Fragment fragment = new Dictionary();
fragobj.setArguments(bundle);
activity.getSupportFragmentManager().beginTransaction().
replace(R.id.activitymain,fragment).addToBackStack(null).commit();
And in your Dictionary Fragment
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_dictionary, container, false);
String word = getArguments().getString("word");
definitionnn = (EditText) v.findViewById(R.id.definition)
definitionnn.setText(word);
return v;
}

How to call a custom dialog fragment from a RecyclerViewAdapter inside a fragment in Android

I am trying to call a custom dialog fragment i have created from a dialog fragment adapter that extends a recyclerView. I'm using the latest android studio with androidx. the following code is for the Custom dialog Adapter
import android.app.DialogFragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import tino.varconn.com.instantecocash.R;
public class DialogSendMoneyFirst extends DialogFragment {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_send_money_first, container, false);
// Do all the stuff to initialize your custom view
return v;
}
The following code i am trying to use to call the dialog fragment
package tino.varconn.com.instantecocash;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import androidx.cardview.widget.CardView;
import androidx.fragment.app.FragmentTransaction;
import androidx.recyclerview.widget.RecyclerView;
import java.util.List;
import tino.varconn.com.instantecocash.dialogs.DialogSendMoneyFirst;
public class EcocashAdapter extends
RecyclerView.Adapter<EcocashAdapter.MyViewHolder> {
private List<EcocashModel> itemList;
Context context;
public class MyViewHolder extends RecyclerView.ViewHolder {
public TextView title;
public ImageView img;
public CardView cardView;
public MyViewHolder(View view) {
super(view);
title = (TextView) view.findViewById(R.id.listtext);
img = (ImageView) view.findViewById(R.id.logo);
cardView = (CardView) view.findViewById(R.id.cardView);
}
}
public EcocashAdapter(List<EcocashModel> itemList) {
this.itemList = itemList;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.my_list_row, parent, false);
return new MyViewHolder(itemView);
}
#Override
public void onBindViewHolder(MyViewHolder holder, final int position) {
EcocashModel ecocashModel = itemList.get(position);
holder.title.setText(ecocashModel.getName());
holder.img.setImageResource(ecocashModel.getImage());
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (position == 0){
Toast.makeText(v.getContext(), "Send Money", Toast.LENGTH_SHORT).show();
DialogSendMoneyFirst dialog = new DialogSendMoneyFirst();
dialog.show(((AppCompatActivity)context).getFragmentManager(), "MyCustomDialog");
}
if (position == 1){
Toast.makeText(v.getContext(), "Pay Merchant", Toast.LENGTH_SHORT).show();
}
}
});
}
#Override
public int getItemCount() {
return itemList.size();
}
And this is the error :
Attempt to invoke virtual method 'android.app.FragmentManagerandroidx.appcompat.app.AppCompatActivity.getFragmentManager()' on a null object reference
Try this
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.my_list_row, parent, false);
context = itemView.getContext()
return new MyViewHolder(itemView);
}
If not work :
1.Check your activity is AppCompact or not.
2.If you are calling your adapter from fragment then use getChildFragmentManager()
If you are calling your adapter from Activity then use getSupportFragmentManager()
Your context is null
Try this:
getActivity().getSupportFragmentManager()
instead of:
(AppCompatActivity)context).getFragmentManager()
If your context arrives from Fragment, then you have to use below: [cast context to FragmentActivity]
dialog.show(((FragmentActivity) mContext).getSupportFragmentManager(), tag);

Save, Share & Favourite Imageview in recyclerview

this codes contains a share button, download button, and a favourate button.
till now its working properly with favourate button, if i remove onClick method from ViewHolder.
I want to implement share/save button onClick share/download the Image in the ImageView in recyclerview.
Please ignore gramatical mistakes
This is my cardFragment Class.
import android.content.ContentResolver;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
public class CardFragment extends Fragment {
ArrayList<WonderModel> listitems = new ArrayList<>();
RecyclerView MyRecyclerView;
String Wonders[] = {"Chichen Itza","Christ the Redeemer","Great Wall of China","Machu Picchu","Petra","Taj Mahal","Colosseum"};
int Images[] = {R.drawable.chichen_itza,R.drawable.christ_the_redeemer,R.drawable.great_wall_of_china,R.drawable.machu_picchu,R.drawable.petra,R.drawable.taj_mahal,R.drawable.colosseum};
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
initializeList();
getActivity().setTitle("7 Wonders of the Modern World");
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_card, container, false);
MyRecyclerView = (RecyclerView) view.findViewById(R.id.cardView);
MyRecyclerView.setHasFixedSize(true);
LinearLayoutManager MyLayoutManager = new LinearLayoutManager(getActivity());
MyLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
if (listitems.size() > 0 & MyRecyclerView != null) {
MyRecyclerView.setAdapter(new MyAdapter(listitems));
}
MyRecyclerView.setLayoutManager(MyLayoutManager);
return view;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
public class MyAdapter extends RecyclerView.Adapter<MyViewHolder> {
private ArrayList<WonderModel> list;
public MyAdapter(ArrayList<WonderModel> Data) {
list = Data;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent,int viewType) {
// create a new view
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.recycle_items, parent, false);
MyViewHolder holder = new MyViewHolder(view);
return holder;
}
#Override
public void onBindViewHolder(final MyViewHolder holder, int position) {
holder.titleTextView.setText(list.get(position).getCardName());
holder.coverImageView.setImageResource(list.get(position).getImageResourceId());
holder.coverImageView.setTag(list.get(position).getImageResourceId());
holder.likeImageView.setTag(R.drawable.ic_like);
}
#Override
public int getItemCount() {
return list.size();
}
}
public class MyViewHolder extends RecyclerView.ViewHolder {
public TextView titleTextView;
public ImageView coverImageView;
public ImageView likeImageView;
public ImageView shareImageView;
public MyViewHolder(View v) {
super(v);
titleTextView = (TextView) v.findViewById(R.id.titleTextView);
coverImageView = (ImageView) v.findViewById(R.id.coverImageView);
likeImageView = (ImageView) v.findViewById(R.id.likeImageView);
shareImageView = (ImageView) v.findViewById(R.id.shareImageView);
likeImageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int id = (int)likeImageView.getTag();
if( id == R.drawable.ic_like){
likeImageView.setTag(R.drawable.ic_liked);
likeImageView.setImageResource(R.drawable.ic_liked);
Toast.makeText(getActivity(),titleTextView.getText()+" added to favourites",Toast.LENGTH_SHORT).show();
}else{
likeImageView.setTag(R.drawable.ic_like);
likeImageView.setImageResource(R.drawable.ic_like);
Toast.makeText(getActivity(),titleTextView.getText()+" removed from favourites",Toast.LENGTH_SHORT).show();
}
}
});
shareImageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Uri imageUri = Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE +
"://" + getResources().getResourcePackageName(coverImageView.getId())
+ '/' + "drawable" + '/' + getResources().getResourceEntryName((int)coverImageView.getTag()));
Intent shareIntent = new Intent();
shareIntent.setAction(Intent.ACTION_SEND);
shareIntent.putExtra(Intent.EXTRA_STREAM,imageUri);
shareIntent.setType("image/jpeg");
startActivity(Intent.createChooser(shareIntent, getResources().getText(R.string.send_to)));
}
});
}
}
public void initializeList() {
listitems.clear();
for(int i =0;i<7;i++){
WonderModel item = new WonderModel();
item.setCardName(Wonders[i]);
item.setImageResourceId(Images[i]);
item.setIsfav(0);
item.setIsturned(0);
listitems.add(item);
}
}
}
Here is MainActivity.Java
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v7.app.AppCompatActivity;
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.fragmentContainer);
if (fragment == null) {
fragment = new CardFragment();
;
fm.beginTransaction()
.add(R.id.fragmentContainer, fragment)
.commit();
}
}
}
Create your ViewHolder Constructor Like this
public MyViewHolder(View v,Activity activity) {
super(v);
this.activity = activity
/////Remaining code
Now you able to get the activity context in your viewholder class.
Hope it will helps you!!

how to add clicklistener for each item

I have an Array list here,
I want each of them when clicked, they will do a specific function or intent an activity.
Currently: each item contains, ImageButton and a Textview in a list.
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.BottomSheetDialogFragment;
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 java.util.ArrayList;
import java.util.List;
public class MyBottomSheetDialogFragment extends BottomSheetDialogFragment {
String mString;
private RecyclerView mRecyclerView;
private VerticalListAdapter mVerticalListAdapter;
static MyBottomSheetDialogFragment newInstance(String string) {
MyBottomSheetDialogFragment f = new MyBottomSheetDialogFragment();
Bundle args = new Bundle();
args.putString("string", string);
f.setArguments(args);
return f;
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mString = getArguments().getString("string");
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.bottom_sheet_modal_list, container, false);
mRecyclerView = (RecyclerView) v.findViewById(R.id.recycler_view);
return v;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
List<Model> list = new ArrayList<Model>();
list.add(new Model(R.drawable.a1, "Call"));
list.add(new Model(R.drawable.a2, "Chat"));
list.add(new Model(R.drawable.a3, "Android"));
list.add(new Model(R.drawable.a4, "Location"));
list.add(new Model(R.drawable.a5, "Call"));
list.add(new Model(R.drawable.a6, "Chat"));
list.add(new Model(R.drawable.a7, "Android"));
mVerticalListAdapter = new VerticalListAdapter(getContext(), list);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getContext(), LinearLayoutManager.VERTICAL, false);
mRecyclerView.setLayoutManager(linearLayoutManager);
mRecyclerView.setAdapter(mVerticalListAdapter);
}
I can provide additional XML , Java codes of the project that is relatively connected to this code, Please leave a comment for clarification.
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.ImageButton;
import android.widget.TextView;
import java.util.List;
public class VerticalListAdapter extends RecyclerView.Adapter<VerticalListAdapter.MyViewHolder>{
private Context mContext;
private List<Model> mModelList;
public VerticalListAdapter(Context context, List<Model> list) {
this.mContext = context;
this.mModelList = list;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.modal_list_item, parent, false);
return new MyViewHolder(itemView);
}
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
holder.txtView.setText(mModelList.get(position).getName());
holder.imgView.setImageDrawable(mContext.getResources().getDrawable(mModelList.get(position).getImgId()));
}
#Override
public int getItemCount() {
return mModelList.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder {
public TextView txtView;
public ImageButton imgView;
public MyViewHolder(View view) {
super(view);
txtView = (TextView) view.findViewById(R.id.txtView);
imgView = (ImageButton) view.findViewById(R.id.imgView);
}
}
}
What you need to do is to implement the OnClickListener to your Holder class and add id to your LinearLayout in modal_list_item.xml so you can click on the entire layout not only its views (if I understand you correctly) and eventually set the onClickListener.
When you do this, you will need to implement the onClick method. For inspiration see the code below:
public class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
public TextView txtView;
public ImageButton imgView;
private LinearLayout linearLayout;
public MyViewHolder(View view) {
super(view);
txtView = (TextView) view.findViewById(R.id.txtView);
imgView = (ImageButton) view.findViewById(R.id.imgView);
linearLayout = (LinearLayout) view.findViewById(R.id.linear_l);
linearLayout.setOnClickListener(this);
}
#Override
public void onClick(View v) {
Log.i("RecyclerView Item", String.valueOf(getLayoutPosition()));
mModelList.remove(getLayoutPosition());
notifyDataSetChanged();
}
}

RecyclerView giving errors

Hi i am new to android project so i am trying to use recycler view. but it is not working. i keep getting errors # this line " RecyclerAdapter adapter = new RecyclerAdapter(this, getData());" it says RecyclerAdapter (android.content.context, List) in RecyclerAdapter cannot be applied to my package class please help
statement.java
import android.content.Context;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import java.util.ArrayList;
import java.util.List;
import nnnnn.R;
import nnnnnn.RecyclerAdapter;
import nnnnnnnnnnnnn.Landscape;
public class Statements extends Fragment {
Toolbar toolbar;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.statements,container,false);
toolbar = (Toolbar) v.findViewById(R.id.toolbar);
toolbar.setTitle("Statements");
toolbar.inflateMenu(R.menu.menu_main);
setUpRecyclerView();
return v;}
private void setUpRecyclerView() {
RecyclerView recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
RecyclerAdapter adapter = new RecyclerAdapter(this.getActivity(),Landscape.getData());
recyclerView.setAdapter(adapter);
final LinearLayoutManager mLinearLayoutManagerVertical = new LinearLayoutManager(this.getActivity()); // (Context context, int spanCount)
mLinearLayoutManagerVertical.setOrientation(LinearLayoutManager.VERTICAL);
recyclerView.setLayoutManager(mLinearLayoutManagerVertical);
recyclerView.setItemAnimator(new DefaultItemAnimator()); // Even if we dont use it then also our items shows default animation. #Check Docs
}
}
RecyclerAdapter code is below
RecyclerAdapter
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.List;
import xx.xx.xx.xx.xx.R;
import xx.xx.xx.xx.model.Landscape;
public class RecyclerAdapter extends RecyclerView.Adapter<RecyclerAdapter.MyViewHolder> {
private static final String TAG = RecyclerAdapter.class.getSimpleName();
private List<Landscape> mDataList;
private LayoutInflater inflater;
public RecyclerAdapter(Context context, List<Landscape> data) {
this.mDataList = data;
this.inflater = LayoutInflater.from(context);
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
Log.i(TAG, "onCreateViewHolder");
View view = inflater.inflate(R.layout.statementlist, parent, false);
MyViewHolder holder = new MyViewHolder(view);
return holder;
}
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
Log.i(TAG, "onBindViewHolder" + position);
Landscape current = mDataList.get(position);
holder.setData(current, position);
holder.setListeners();
}
#Override
public int getItemCount() {
return mDataList.size();
}
public void removeItem(int position) {
mDataList.remove(position);
notifyItemRemoved(position);
// notifyItemRangeChanged(position, mDataList.size());
// notifyDataSetChanged();
}
public void addItem(int position, Landscape landscape) {
mDataList.add(position, landscape);
notifyItemInserted(position);
// notifyItemRangeChanged(position, mDataList.size());
// notifyDataSetChanged();
}
class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
TextView title;
ImageView imgThumb, imgDelete, imgAdd;
int position;
Landscape current;
public MyViewHolder(View itemView) {
super(itemView);
title = (TextView) itemView.findViewById(R.id.tvTitle);
imgThumb = (ImageView) itemView.findViewById(R.id.img_row);
imgDelete = (ImageView) itemView.findViewById(R.id.img_row_delete);
imgAdd = (ImageView) itemView.findViewById(R.id.img_row_add);
}
public void setData(Landscape current, int position) {
this.title.setText(current.getTitle());
imgThumb.setImageResource(current.getImageID());
this.position = position;
this.current = current;
}
public void setListeners() {
imgDelete.setOnClickListener(MyViewHolder.this);
imgAdd.setOnClickListener(MyViewHolder.this);
imgThumb.setOnClickListener(MyViewHolder.this);
}
#Override
public void onClick(View v) {
// Log.i("onClick before operation", position + " " + mDataList.size());
switch (v.getId()) {
case R.id.img_row_delete:
removeItem(position);
break;
case R.id.img_row_add:
addItem(position, current);
break;
}
// Log.i("onClick after operation", mDataList.size() + " \n\n" + mDataList.toString());
}
}
}
You're passing in "this" for the first argument to RecyclerAdapter. "this" being a Fragment class. The Fragment class does not extend from Context, so it cannot be used as such.
Try "this.getActivity()". This may result in null, so ideally put this within the Fragment subclass's "onActivityCreated" method (instead of the "onCreateView" method)
You need to override OnActivitycreated in order to call getActivity. Call setUpRecyclerView in OnActivitycreated and add getActivity. before findViewById and it will work

Categories

Resources