Old position of adapter OnClick RecyclerView - android

I am trying to change the data from the recycleview when i am applying a filter. Everything works as should but when i click on the new adapter's items i get the old adapter's items. The example describes what happens.
Adapter items : x , y , z
After filter adapter items : x , z
When i click filtered item z it opens y
DataFilters are just a return of filtered or not of an array and homeFragment.companyFilters is called from inside a class that manages spinner selection again nothing more to show. I think thats all.
HomeFragment
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.home_layout, null);
mSwipeRefreshLayout = (SwipeRefreshLayout) rootView.findViewById(R.id.home_refresh);
fab = (FloatingActionButton) rootView.findViewById(R.id.fabhome);
sheet = (View) rootView.findViewById(R.id.sheethome);
overlay = (View) rootView.findViewById(R.id.overlayhome);
mRecyclerView = (RecyclerView) rootView.findViewById(R.id.home_recycler_view);
context = container.getContext();
mRecyclerView.setHasFixedSize(false);
mLayoutManager = new LinearLayoutManager(getActivity());
mRecyclerView.setLayoutManager(mLayoutManager);
mHomeAdapter = new RecyclerViewHomeAdapter(dataFilters.getAllHomeDataSet());
PreCachingLayoutManager layoutManager = new PreCachingLayoutManager(getActivity());
layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
layoutManager.setSmoothScrollbarEnabled(true);
mRecyclerView.setLayoutManager(layoutManager);
mRecyclerView.setAdapter(mHomeAdapter);
mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
mHomeAdapter = new RecyclerViewHomeAdapter(dataFilters.getAllHomeDataSet());
mRecyclerView.setAdapter(mHomeAdapter);
mSwipeRefreshLayout.setRefreshing(false);
}
});
fab.setOnClickListener(this);
overlay.setOnClickListener(this);
sheet.setOnClickListener(this);
addItemsOnCompanySpinner();
spinnerCompany.setOnItemSelectedListener(new HomeSpinnerHandler(this));
return rootView;
}
#Override
public void onResume() {
super.onResume();
((RecyclerViewHomeAdapter) mHomeAdapter).setOnItemClickListener(new RecyclerViewHomeAdapter.MyClickListener() {
#Override
public void onItemClick(int position, View v) {
String ObjectType = dataFilters.getAllHomeDataSet().get(position).homeObjectType;
if (ObjectType.contains("Product")) {
((MainActivity) getActivity()).onProductItemClick(dataFilters.getAllHomeDataSet().get(position).homeObjectID);
} else {
((MainActivity) getActivity()).onPostItemClick(dataFilters.getAllHomeDataSet().get(position).homeObjectID);
}
}
});
}
#Override
public void onClick(View v) {
if (fab.getVisibility() == View.VISIBLE) {
FabTransformation.with(fab).setOverlay(overlay).transformTo(sheet);
}
if (fab.getVisibility() != View.VISIBLE) {
FabTransformation.with(fab).setOverlay(overlay).transformFrom(sheet);
}
}
public void addItemsOnCompanySpinner() {
spinnerCompany = (MaterialSpinner) rootView.findViewById(R.id.spinnercompany);
List<String> list = new ArrayList<String>();
for (companyListCounter = 0;companyListCounter<companies.size();companyListCounter++){
list.add(companies.get(companyListCounter).getCompanyName());
}
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(context,
android.R.layout.simple_spinner_item, list);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerCompany.setAdapter(dataAdapter);
spinnerCompany.setHint("Επιλέξτε Εταιρεία");
}
public void companyFilter(String companyFilter) {
FabTransformation.with(fab).setOverlay(overlay).transformFrom(sheet);
addItemsOnCompanySpinner();
mHomeAdapter = new RecyclerViewHomeAdapter(dataFilters.getHomeCompanyDataSet(companyFilter));
mRecyclerView.setAdapter(mHomeAdapter);
}
public void updateView(){
mHomeAdapter = new RecyclerViewHomeAdapter(dataFilters.getAllHomeDataSet());
mRecyclerView.setAdapter(mHomeAdapter);
}
RecyclerViewHomeAdapter
public class RecyclerViewHomeAdapter extends RecyclerView.Adapter<RecyclerViewHomeAdapter.HomeDataObjectHolder> {
private ArrayList<HomeObject> mDataset;
private static MyClickListener myClickListener;
public static class HomeDataObjectHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
TextView label;
TextView company;
TextView description;
ImageView imageDrawable;
CardView cardview;
public HomeDataObjectHolder(View itemView) {
super(itemView);
label = (TextView) itemView.findViewById(R.id.homelabel);
company = (TextView) itemView.findViewById(R.id.homecompany);
description = (TextView) itemView.findViewById(R.id.homedescr);
imageDrawable = (ImageView) itemView.findViewById(R.id.homeimage);
cardview = (CardView) itemView.findViewById(R.id.cardview);
itemView.setOnClickListener(this);
}
#Override
public void onClick(View v) {
myClickListener.onItemClick(getAdapterPosition(), v);
}
}
public void setOnItemClickListener(MyClickListener myClickListener) {
this.myClickListener = myClickListener;
}
public RecyclerViewHomeAdapter(ArrayList<HomeObject> myDataset) {
mDataset = myDataset;
}
#Override
public HomeDataObjectHolder onCreateViewHolder(ViewGroup parent,
int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.recyclerview_home_item, parent, false);
HomeDataObjectHolder dataObjectHolder = new HomeDataObjectHolder(view);
return dataObjectHolder;
}
#Override
public void onBindViewHolder(HomeDataObjectHolder holder, int position) {
holder.label.setText(mDataset.get(position).getLabel());
holder.company.setText(mDataset.get(position).getCompany());
holder.description.setText(mDataset.get(position).getTextDescr());
if (Arrays.asList(postTypeRef).contains(mDataset.get(position).getLabel().replace("Είδος Ενημέρωσης : \r\n",""))){
Picasso.with(MyApp.applicationContext).load(mDataset.get(position)
.imageIDFetch()).into(holder.imageDrawable);
}
else{
Picasso.with(MyApp.applicationContext).load(MyApp.imageURL+mDataset.get(position)
.getImageCached()).into(holder.imageDrawable);
}
}
#Override
public int getItemCount() {
return mDataset.size();
}
public interface MyClickListener {
public void onItemClick(int position, View v);
}}
Inside MainActivity i have two function so i can open another fragment from fragment.
public void onProductItemClick(int id) {
Fragment productFragment = new ProductItemFragment();
Bundle bundle = new Bundle();
bundle.putInt("id", id);
productFragment.setArguments(bundle);
android.support.v4.app.FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.containerView, productFragment);
transaction.addToBackStack(null);
transaction.commit();
}
public void onPostItemClick(int id) {
Fragment postFragment = new NewsItemFragment();
Bundle bundle = new Bundle();
bundle.putInt("id", id);
postFragment.setArguments(bundle);
android.support.v4.app.FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.containerView, postFragment);
transaction.addToBackStack(null);
transaction.commit();
}

Related

Onclick listner not triggering in fragment page adapter

I'm trying to display all contacts from phone to recyclerView when a user presses any item it should do some work. I have a list of contacts in a fragment which is inside a fragment page adapter when ever I click in the recyclerView item onClicklistener is not executing
I have used same code in a previous app but onclicklisteners are triggering
public class ListOfContacts extends Fragment implements OnContactListener {
private static final String TAG = "ListOfContacts";
ArrayList<ContactModel> arrayList = new ArrayList<>();
RecyclerView mRecyclerview;
ListOfContactsRAdapter listOfContactsRAdapter;
Cursor cursor;
public static ListOfContacts getInstance(ArrayList<ContactModel> arrayList) {
ListOfContacts listOfContacts = new ListOfContacts();
Bundle bundle = new Bundle();
bundle.putParcelableArrayList("listofcontacts", arrayList);
listOfContacts.setArguments(bundle);
return listOfContacts;
}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_list_of_contacts, container, false);
mRecyclerview = view.findViewById(R.id.loc_r_view);
listOfContactsRAdapter = new ListOfContactsRAdapter(getActivity(), this, arrayList);
mRecyclerview.setLayoutManager(new LinearLayoutManager(getActivity()));
mRecyclerview.setAdapter(listOfContactsRAdapter);
mRecyclerview.addItemDecoration(new DividerItemDecoration(mRecyclerview.getContext(), DividerItemDecoration.VERTICAL));
mRecyclerview.setHasFixedSize(true);
return view;
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
arrayList.addAll(Objects.requireNonNull(getArguments().<ContactModel>getParcelableArrayList("listofcontacts")));
Log.d(TAG, "contact recived " + arrayList.get(0).getContactName());
} else {
if (getArguments().getStringArrayList("listofcontacts") != null)
arrayList.addAll(getArguments().<ContactModel>getParcelableArrayList("listofcontacts"));
}
}
}
#Override
public void onDueListener(int position) {
Log.d(TAG, "onDueListener: ");
ContactModel contactModel = new ContactModel();
contactModel.setContactName(arrayList.get(position).getContactName());
contactModel.setContactNumberp(arrayList.get(position).getContactNumberp());
contactModel.setState(true);
Intent intent = new Intent(getActivity(), AddDue.class);
intent.putExtra("userDetails", contactModel);
startActivity(intent);
}
}
public ListOfContactsRAdapter(Context context, OnContactListener a, ArrayList<ContactModel> arrayList) {
Log.d(TAG, "ListOfContactsRAdapter: +" + arrayList.size());
ContactListener = a;
this.arrayList = new ArrayList<>();
if (arrayList != null)
this.arrayList.addAll(arrayList);
mContext = context;
}
#NonNull
#Override
public CustomViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.loc_r_container, viewGroup, false);
customViewHolder = new CustomViewHolder(view, ContactListener);
return customViewHolder;
}
#Override
public void onBindViewHolder(#NonNull CustomViewHolder customViewHolder, int i) {
customViewHolder.contactName.setText(arrayList.get(i).getContactName());
customViewHolder.contactNumber.setText(arrayList.get(i).getContactNumberp());
customViewHolder.contactDp.setText(String.valueOf(arrayList.get(i).getContactName().charAt(0)));
}
#Override
public int getItemCount() {
Log.d(TAG, "getItemCount: ");
return arrayList.size();
}
static class CustomViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
OnContactListener Listener;
TextView contactName;
TextView contactNumber;
TextView contactDp;
Button button;
LinearLayout linearLayout;
CustomViewHolder(#NonNull View itemView, OnContactListener mOnContactListener) {
super(itemView);
contactName = itemView.findViewById(R.id.contact_name);
contactNumber = itemView.findViewById(R.id.contact_number);
button = itemView.findViewById(R.id.action);
contactDp = itemView.findViewById(R.id.contactDp);
linearLayout = itemView.findViewById(R.id.container);
linearLayout.setOnClickListener(this);
Listener = mOnContactListener;
button.setOnClickListener(this);
}
#Override
public void onClick(View v) {
Log.d(TAG, "onClick: ");
Listener.onDueListener(getAdapterPosition());
}
}
}
What i did is create an Interface in your RecyclerView Adapter:
public interface OnClickItem { // create an interface
void onClickItem(int position); // create callback function
}
Then in OnBindViewHolder:
customViewHolder.(yourView).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ContactListener.onClickItem(customViewHolder.getAdapterPosition());
}
});
In your Fragment:
public class ListOfContacts extends Fragment implements ListOfContactsRAdapter.OnClickItem { ...
Implement the method:
#Override
public void onClickItem(int position) {
...
}

How to create an interface between a fragment and an adapter

I have been able to create an interface in the adapter to communicate with the fragment.
This is the adapter code
public class AgroInfoAdapter extends RecyclerView.Adapter<AgroInfoAdapter.ViewHolder> {
private Context mContext;
ArrayList<JsonObject> extensionItem = new ArrayList<>();
public Typeface tf;
public AgroInfoAdapter.AgroInfoAdapterListener listener;
public AgroInfoAdapter(Context context, ArrayList<JsonObject> extensionItem) {
this.extensionItem = extensionItem;
this.mContext = context;
this.tf = Typeface.createFromAsset(context.getAssets(), "FiraSans-Light.ttf");
}
#Override
public AgroInfoAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemLayoutView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.list_crop_info, null);
AgroInfoAdapter.ViewHolder viewHolder = new AgroInfoAdapter.ViewHolder(itemLayoutView);
return viewHolder;
}
public static class ViewHolder extends RecyclerView.ViewHolder {
#BindView(R.id.header)
public TextView header;
#BindView(R.id.body)
public TextView body;
#BindView(R.id.thumbnail)
public ImageView thumbnail;
#BindView(R.id.button)
public Button button;
#BindView(R.id.downloadProgressView)
DownloadProgressView downloadProgressView;
#BindView(R.id.row)
public LinearLayout row;
public ViewHolder(View itemLayoutView) {
super(itemLayoutView);
ButterKnife.bind(this, itemLayoutView);
}
}
#Override
public void onBindViewHolder(AgroInfoAdapter.ViewHolder viewHolder, final int position) {
try {
JsonObject sl = extensionItem.get(position);
viewHolder.header.setText(sl.get("title").getAsString());
if ((sl.get("title").getAsString()).equals("Land preparation")) {
viewHolder.button.setVisibility(View.VISIBLE);
}
Glide.with(mContext).load(CONFIG.IMAGE_URL+ sl.get("photo_url").getAsString())
.thumbnail(0.5f)
.apply(new RequestOptions()
.diskCacheStrategy(DiskCacheStrategy.ALL)
.fallback(R.drawable.fallback)
.placeholder(R.drawable.progress_animation)
.error(R.drawable.fallback)
)
.into(viewHolder.thumbnail);
String description="";
for (JsonElement e:sl.get("description").getAsJsonArray()){
if(!e.getAsString().trim().isEmpty() && CharMatcher.javaUpperCase().or(CharMatcher.javaLetter().negate()).matchesAllOf(e.getAsString().trim())) {
SpannableString s1 = new SpannableString(e.getAsString());
s1.setSpan(new BulletSpan(20), 1, e.getAsString().length(), 0);
description +=s1 + "\n\n";
}else if(!e.getAsString().trim().isEmpty()) {
SpannableString s1 = new SpannableString(e.getAsString());
s1.setSpan(new BulletSpan(20), 1, e.getAsString().length(), 0);
description +=s1 + "\n\n";;
viewHolder.body.setText(description);
viewHolder.body.setTypeface(tf);
}
}
} catch (Exception e) {
}
applyClickEvents(viewHolder, position);
}
public interface AgroInfoAdapterListener {
void onCartRowClicked(View view, DownloadProgressView downloadProgressView, int position);
}
private void applyClickEvents(final AgroInfoAdapter.ViewHolder holder, final int position) {
holder.button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
listener.onCartRowClicked(view, holder.downloadProgressView, position);
}
});
}
#Override
public int getItemCount() {
return extensionItem.size();
}
}
This is the frgament which I was connecting to the adapter
AgroInfoAdapter adapter;
#BindView(R.id.rv)
RelativeLayout _RecyclerViewLayout;
#BindView(R.id.empty_rv)
RelativeLayout _EmptyRecyclerViewLayout;
#BindView(R.id.recycler_desc)
RecyclerView recyclerView;
Toolbar mToolbar;
#BindView(R.id.progress_bar)
ProgressBar progressBar;
#BindView(R.id.rv_layout) RelativeLayout relativeLayout;
ArrayList<JsonObject> ins = new ArrayList<>();
AgroInfoActivity.OnCropperSpinnerSelectedListener listener;
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
listener = new AgroInfoActivity.OnCropperSpinnerSelectedListener() {
#Override
public void onItemSelected(String pos) {
new LongOperation().execute(pos);
}
};
((AgroInfoActivity)getActivity()).addCropperSpinnerSelectedListener(listener);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_ext_land, container, false);
ButterKnife.bind(this,view);
RecyclerView.LayoutManager mLayoutManager = new GridLayoutManager(getActivity(), 1);
recyclerView.setLayoutManager(mLayoutManager);
recyclerView.addItemDecoration(new GridSpacingItemDecoration(1, dpToPx(10), true));
recyclerView.setItemAnimator(new DefaultItemAnimator());
adapter = new AgroInfoAdapter(getActivity(), ins);
recyclerView.setAdapter(adapter);
return view;
}
#Override
public void onResume() {
new LongOperation().execute(((AgroInfoActivity)getActivity()).cropsSpinner.getSelectedItem().toString());
super.onResume();
}
private class LongOperation extends AsyncTask<String, Void, ArrayList<JsonObject>> {
#Override
protected ArrayList<JsonObject> doInBackground(String... params) {
try {
couchdbCropInfo = new CouchdbCropInfo(getActivity());
return couchdbCropInfo.allCropInfo(params[0],TYPE);
} catch (CouchbaseLiteException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(ArrayList<JsonObject> result) {
ins.addAll(result);
adapter.notifyDataSetChanged();
if (ins.isEmpty()) {
_RecyclerViewLayout.setVisibility(View.GONE);
_EmptyRecyclerViewLayout.setVisibility(View.VISIBLE);
} else {
_RecyclerViewLayout.setVisibility(View.VISIBLE);
_EmptyRecyclerViewLayout.setVisibility(View.GONE);
}
relativeLayout.setVisibility(View.VISIBLE);
progressBar.setVisibility(View.GONE);
}
#Override
protected void onPreExecute() {
relativeLayout.setVisibility(View.GONE);
progressBar.setVisibility(View.VISIBLE);
ins.clear();
}
#Override
protected void onProgressUpdate(Void... values) {}
}
#Override
public void onCartRowClicked(View view, DownloadProgressView downloadProgressView, int position) {
Bundle bundle = new Bundle();
FragmentTransaction fragmentTransaction = getActivity()
.getFragmentManager()
.beginTransaction();
Fragment fragmentB = new PostFragment();
fragmentB.setArguments(bundle);
fragmentTransaction.replace(R.id.parent, fragmentB);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
}
}
Basically what I am trying to achieve is I want to call a fragment when I click the button. The activity is a tablaout with about 5 fragments.
When I click the button. What brings about this and how best can I solve it or could have done it? Thanks in advance.
In place where you declare adapter or in the constructor of adapter, initiate the listener.
In the fragment side,
class Test extends Fragment {
AdapterClass adapter = new AdapterClass();
adapter.setListner(..)
view.setAdapter(adapter);
#Override
public void onCartRowClicked(View view, DownloadProgressView downloadProgressView, int position) {
}
}
In Adapter class
class AdapterClass {
private AgroInfoAdapterListener listner;
public setListner(AgroInfoAdapterListener listner) {
this.listner = listner;
}
public interface AgroInfoAdapterListener {
void onCartRowClicked(View view, DownloadProgressView downloadProgressView, int position);
}
private void applyClickEvents(final AgroInfoAdapter.ViewHolder holder, final int position) {
holder.button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
}
});
}
}

How to move from one fragment to another fragment on click of a RecyclerView item

I want to click an item on the RecyclerView (on a list fragment) and then go to the detail fragment with some data of the item.
I already knew how to use intent in activity, but I cannot find example to do with RecyclerView item.
//In first Activity
Intent intent = new Intent();
intent.setClass(this,SecondActivity.class);
Bundle bundle = new Bundle();
bundle.putDouble("height",height);
bundle.putString("sex",sex);
intent.putExtras(bundle);
startActivity(intent);
//In second Activity
Bundle bundle1=this.getIntent().getExtras();
String sex=bundle1.getString("sex");
double height=bundle1.getDouble("height");
I am stuck in Adapter. Can anyone explain to me step by step?
Thanks!
My adapter code
public class GPAAdapter extends RecyclerView.Adapter<GPAAdapter.ViewHolder> {
private List<GPAModel> mGPAList;
class ViewHolder extends RecyclerView.ViewHolder {
TextView lessonNameText;
TextView lessonCodeText;
TextView teacherNameText;
TextView semesterNameText;
View listView;
public ViewHolder(View gpaItemView) {
super(gpaItemView);
lessonNameText = (TextView) gpaItemView.findViewById(R.id.gpa_lessonName);
lessonCodeText = (TextView) gpaItemView.findViewById(R.id.gpa_lessonCode);
teacherNameText = (TextView) gpaItemView.findViewById(R.id.gpa_teacherName);
semesterNameText = (TextView) gpaItemView.findViewById(R.id.gpa_semesterName);
listView = gpaItemView;
}
}
public GPAAdapter(List<GPAModel> dataList) {
mGPAList = dataList;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.gpa_item, parent, false);
final ViewHolder holder = new ViewHolder(view);
return holder;
}
public void setData(List<GPAModel> viewData) {
mGPAList.clear();
mGPAList.addAll(viewData);
notifyDataSetChanged();
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
GPAModel data = mGPAList.get(position);
holder.setIsRecyclable(true);
holder.lessonNameText.setText(data.getLessonName());
holder.lessonCodeText.setText(data.getLessonCode());
holder.teacherNameText.setText(data.getTeacherName());
holder.semesterNameText.setText(data.getSemesterName());
//save position in itemView with TAG
holder.itemView.setTag(position);
}
#Override
public int getItemCount() {
return mGPAList.size();
}
//define interface
public static interface OnItemClickListener {
void onItemClick(View view , int position);
}
private OnItemClickListener mOnItemClickListener = null;
//Alert: method does not override method from its superclass
#Override
public void onClick(View v) {
if (mOnItemClickListener != null) {
//getTag of position
mOnItemClickListener.onItemClick(v,(int)v.getTag());
}
}
public void setOnItemClickListener(OnItemClickListener listener) {
this.mOnItemClickListener = listener;
}
}
My list fragment
private FragmentManager manager;
private FragmentTransaction ft;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View gpaView = inflater.inflate(R.layout.fragment_gpa, container, false);
RecyclerView gpaRecyclerView = (RecyclerView) gpaView.findViewById(R.id.gpa_list);
LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
gpaRecyclerView.setLayoutManager(layoutManager);
GPAAdapter adapter = new GPAAdapter(getData());
gpaRecyclerView.setAdapter(adapter);
return gpaView;
//how use .setArguments(bundle) in fragment?
super.onCreate(savedInstanceState);
manager = getFragmentManager();
GPAAdapter.setOnItemClickListener(new OnItemClickListener(){
#Override
public void onItemClick(View view , int position){
Toast.makeText(MainActivity.this, data[position], 600).show();
}
});
}
private List<GPAModel> getData() {
}
You can replace a fragment using FragmentTransaction in onItemClick in your List Fragment
final FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.replace(R.id.details, new NewFragmentToReplace(), "NewFragmentTag");
ft.commit();
Call getFragmentManager on Recycler.Adapter is a bit hard for me. So I here choose send click message to a new Activity (for detail show).
Hope my code can help somebody.
My adapter code
public class GPAAdapter extends RecyclerView.Adapter<GPAAdapter.ViewHolder> {
private ArrayList<GPAModel> mGPAList;
Context context;
class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
TextView lessonNameText;
TextView lessonCodeText;
TextView teacherNameText;
TextView semesterNameText;
View listView;
ArrayList<GPAModel> list = new ArrayList<GPAModel>();
Context ctx;
public ViewHolder(View gpaItemView, Context myCtx, ArrayList<GPAModel> myList) {
super(gpaItemView);
gpaItemView.setOnClickListener(this);
this.list = myList;
this.ctx = myCtx;
lessonNameText = (TextView) gpaItemView.findViewById(R.id.gpa_lessonName);
lessonCodeText = (TextView) gpaItemView.findViewById(R.id.gpa_lessonCode);
teacherNameText = (TextView) gpaItemView.findViewById(R.id.gpa_teacherName);
semesterNameText = (TextView) gpaItemView.findViewById(R.id.gpa_semesterName);
listView = gpaItemView;
}
#Override
public void onClick(View view) {
int position = getAdapterPosition();
GPAModel sendGPA = this.list.get(position);
Intent intent = new Intent(this.ctx, GPADetail.class);
intent.putExtra("lessonName", sendGPA.getLessonName());
intent.putExtra("lessonCode", sendGPA.getLessonCode());
intent.putExtra("creditPoint", sendGPA.getCreditPoint());
intent.putExtra("teacherName", sendGPA.getTeacherName());
intent.putExtra("semesterName", sendGPA.getSemesterName());
intent.putExtra("totalStudentNumber", sendGPA.getTotalStudentNumber());
//
ArrayList<String> scoreValue = new ArrayList<String>();
scoreValue = sendGPA.getScoreValue();
intent.putExtra("scoreValue", scoreValue);
//
ArrayList<Float> studentCount = new ArrayList<Float>();
studentCount = sendGPA.getStudentCount();
intent.putExtra("studentCount",studentCount);
this.ctx.startActivity(intent);
}
}
public GPAAdapter(ArrayList<GPAModel> myList, Context myContext) {
this.mGPAList = myList;
this.context = myContext;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.gpa_item, parent, false);
final ViewHolder holder = new ViewHolder(view, context, mGPAList);
return holder;
}
public void setData(List<GPAModel> viewData) {
mGPAList.clear();
mGPAList.addAll(viewData);
notifyDataSetChanged();
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
GPAModel data = mGPAList.get(position);
holder.setIsRecyclable(true);
holder.lessonNameText.setText(data.getLessonName());
holder.lessonCodeText.setText(data.getLessonCode());
holder.teacherNameText.setText(data.getTeacherName());
holder.semesterNameText.setText(data.getSemesterName());
}
#Override
public int getItemCount() {
return mGPAList.size();
}
}
My list fragment
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View gpaView = inflater.inflate(R.layout.fragment_gpa, container, false);
RecyclerView gpaRecyclerView = (RecyclerView) gpaView.findViewById(R.id.gpa_list);
LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
gpaRecyclerView.setLayoutManager(layoutManager);
GPAAdapter adapter = new GPAAdapter(getData());
gpaRecyclerView.setAdapter(adapter);
return gpaView;
}
private List<GPAModel> getData() {
}
Then upcast context to AppCompatActivity like this and get the getSupportFragmentManager
FragmentTransaction transaction =((AppCompatActivity) context).getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.frame_container, new CartLayout()); // Add your fragment class
transaction.addToBackStack(null);
transaction.commit();

RecyclerView not refreshing onClick

The RecyclerView is getting refreshed fine when I call for it in the main activity, but when I use a FloatingActionButton it no longer works, and it is not giving any errors as to why.
The onCreate method from the MainActivity
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
//Initially get the events
dh.getEvents();
//Initially setting the list fragment
EventListFragment eventListFragment = new EventListFragment();
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.frame, eventListFragment, "list_fragment");
fragmentTransaction.commit();
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
dh.getEvents();
}
});
}
This is the getEvents() method from the DataHandaling class
public void getEvents() {
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url(enviroClass.url() + "/api/events/" + 7)
.build();
client.newCall(request)
.enqueue(new Callback() {
#Override
public void onFailure(Call call, IOException e) {
e.printStackTrace();
}
#Override
public void onResponse(Call call, Response response) throws IOException {
try {
JSONObject eventObject = new JSONObject(response.body().string());
JSONArray eventJsonArray = eventObject.getJSONArray("events");
for (int i = 0; i<eventJsonArray.length(); i++) {
eventObject = eventJsonArray.getJSONObject(i);
eventObject = eventObject.getJSONObject("event");
eventArray.add(new Event(eventObject.getString("name"), eventObject.getString("address"), eventObject.getString("image"), "100", eventObject.getString("description"), eventObject.getString("start_date"), eventObject.getString("end_date"), eventObject.getInt("id")));
}
EventListAdapter adapter = new EventListAdapter(eventArray, null);
adapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
}
});
}
UPDATE
This is the RecyclerAdapter that is being used
public class EventListAdapter extends RecyclerView.Adapter<EventListAdapter.ViewHolder> {
DataHandaling dh = new DataHandaling();
private static ArrayList<Event> mValues;
private OnListFragmentInteractionListener mListener = null;
public EventListAdapter(ArrayList<Event> items, OnListFragmentInteractionListener listener) {
if (items != null) {
mValues = items;
}
if (listener != null ) {
mListener = listener;
}
}
public void swap(ArrayList<Event> eventArray) {
mValues.clear();
mValues.addAll(eventArray);
notifyDataSetChanged();
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.fragment_item, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(final ViewHolder holder, final int position) {
holder.mItem = mValues.get(position);
holder.mIdView.setText(mValues.get(position).getStarTime());
holder.mContentView.setText(mValues.get(position).getName());
Picasso.with(getApplicationContext()).load(mValues.get(position).getImage()).into(holder.mImageView);
holder.mView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (null != mListener) {
// Notify the active callbacks interface (the activity, if the
// fragment is attached to one) that an item has been selected.
mListener.onListFragmentInteraction(position);
}
}
});
}
#Override
public int getItemCount() {
return mValues.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
public final View mView;
public final TextView mIdView;
public final TextView mContentView;
public final ImageView mImageView;
public Event mItem;
public ViewHolder(View view) {
super(view);
mView = view;
mIdView = (TextView) view.findViewById(R.id.id);
mContentView = (TextView) view.findViewById(R.id.content);
mImageView = (ImageView) view.findViewById(R.id.eventImage);
}
#Override
public String toString() {
return super.toString() + " '" + mContentView.getText() + "'";
}
}
}
This is the Fragment onCreateView, where the adapter is set
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_item_list, container, false);
// Set the adapter
if (view instanceof RecyclerView) {
Context context = view.getContext();
RecyclerView recyclerView = (RecyclerView) view;
if (mColumnCount <= 1) {
recyclerView.setLayoutManager(new LinearLayoutManager(context));
} else {
recyclerView.setLayoutManager(new GridLayoutManager(context, mColumnCount));
}
recyclerView.setAdapter(new EventListAdapter(dh.getEventArray(), mListener));
}
return view;
}
If you create a new adapter, you need to set it in the RecyclerView
EventListAdapter adapter = new EventListAdapter(eventArray, null);
myRecyclerView.setAdapter(adapter)
The class DataHandling should have access to RecyclerView
Or you could use the previous created adapter :
In fragment, change :
recyclerView.setAdapter(new EventListAdapter(dh.getEventArray(), mListener));
by
mAdapter = new EventListAdapter(dh.getEventArray(), mListener)
recyclerView.setAdapter(mAdapter);
In getEvents() :
mAdapter.swap(eventArray);
It means that DataHandling class should have access to mAdapter, you could pass it in contructor, or you should move getEvents() to Fragment and delete DataHandling class

I want to set this icon like if the user wants to mark this chapter as it will read tapper this icon, so it will chancher to another icon

I want to set this icon like if the user wants to mark this chapter as it will read tapper this icon, so it will chancher to another icon.
image that described my work
my files:
SeptCoursAdapter.java
public class SeptCoursAdapter extends RecyclerView.Adapter<SeptCoursAdapter.MyViewHolder> {
private Context mContext;
private List<ItemSeptCours> chapList;
public class MyViewHolder extends RecyclerView.ViewHolder {
public TextView chapitreTitle;
public TextView nbHeures;
public ImageView pecLue;
public MyViewHolder(View view) {
super(view);
chapitreTitle = (TextView) view.findViewById(R.id.chapitre_title);
nbHeures = (TextView) view.findViewById(R.id.nb_heure);
pecLue = (ImageView) view.findViewById(R.id.image_lue);
}
}
public SeptCoursAdapter(Context mContext, List<ItemSeptCours> chapList) {
this.mContext = mContext;
this.chapList = chapList;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.card_item_7_cours, parent, false);
return new MyViewHolder(itemView);
}
#Override
public void onBindViewHolder(final MyViewHolder holder, int position) {
ItemSeptCours itemSeptCours = chapList.get(position);
holder.chapitreTitle.setText(itemSeptCours.getChapitreTitle());
holder.nbHeures.setText(itemSeptCours.getNbHeures());
Glide.with(mContext).load(itemSeptCours.getPecLue()).into(holder.pecLue);
holder.pecLue.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(holder.pecLue.getVisibility()== View.VISIBLE)
holder.pecLue.setVisibility(View.INVISIBLE);
}
});
}
#Override
public int getItemCount() {
return chapList.size();
}
}
CoursSeptFragment.java
public class CoursSeptBaseFragment extends Fragment {
#Nullable
private RecyclerView recyclerView;
private RecyclerView.Adapter adapter;
private List<ItemSeptCours> chapList;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.cours_sept_base_fragment, container, false);
recyclerView = (RecyclerView) view.findViewById(R.id.recyclerView_sept);
chapList = new ArrayList<>();
adapter = new SeptCoursAdapter(view.getContext(), chapList);
if (recyclerView != null) {
recyclerView.setHasFixedSize(true);
}
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(view.getContext());
recyclerView.setLayoutManager(mLayoutManager);
recyclerView.setAdapter(adapter);
prepareChapitre();
return view;
}
private void prepareChapitre() {
int[] luePecTab = new int[]{
R.drawable.ic_visibility_black_18dp_blue,
R.drawable.ic_visibility_off_black_18dp_blue};
ItemSeptCours a = new ItemSeptCours("Chap 1: Ordinateur et systèmes d'exploitation", "4 séances", luePecTab[0]);
chapList.add(a);
a = new ItemSeptCours("Chap 2: Exploitations de logiciels", "4 séances", luePecTab[0]);
chapList.add(a);
a = new ItemSeptCours("Chap 3: L'Internet : Le web", "4 séances", luePecTab[0]);
chapList.add(a);
a = new ItemSeptCours("Un mini projet", "6 séances", luePecTab[0]);
chapList.add(a);
adapter.notifyDataSetChanged();
}
}
I think you are almost there. (assuming pecLue is your little eye image)
Pseudo code:
holder.pecLue.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//if(holder.pecLue.getVisibility()== View.VISIBLE)
// holder.pecLue.setVisibility(View.INVISIBLE);
if(conditionIfChapterIsMarked){
holder.pecLue.setImageResource(R.drawable.pec_lue_icon_unmarked);
//unmarkChapterLogic()
}else{
holder.pecLue.setImageResource(R.drawable.pec_lue_icon_marked);
//markChapterLogic()
}
}
});

Categories

Resources