RecyclerView Not Showing Items on Second Click - java

I have a RecyclerView that I am using to display a list that I obtain from making a request to remote api. The list is shown on the first time that the activity appears but when I go back and come back to activity again, the list doesn't show. How can I solve this?
This is the activity that I call the recyclerview.
public class DisplayMessage extends AppCompatActivity {
RecyclerView recyclerView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.language_selection);
recyclerView = (RecyclerView) findViewById(R.id.recylerview);
LanguageAdapter languageAdapter = new LanguageAdapter(this);
recyclerView.setAdapter(languageAdapter);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
recyclerView.setLayoutManager(linearLayoutManager);
}
}
This is the Adapter class.
public class LanguageAdapter extends RecyclerView.Adapter<LanguageAdapter.MyViewHolder> {
ArrayList<Language> languageArrayList;
public LanguageAdapter(Context context) {
this.languageArrayList = new ArrayList<Language>();
RequestQueue queue = Volley.newRequestQueue(context);
String url ="https://api.bounswe2019group9.tk/contents/languages";
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, url, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray data = (JSONArray) response.get("data");
for(int i=0; i<data.length();i++){
Language lang = new Language((String) data.get(i));
languageArrayList.add(lang);
Log.i("api", ""+lang.getLanguageName());
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("language_selection", "Error on request to get language list");
}
});
queue.add(jsonObjectRequest);
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater layoutInflater = LayoutInflater.from(parent.getContext());
View view = layoutInflater.inflate(R.layout.languages, parent, false);
MyViewHolder holder = new MyViewHolder(view);
return holder;
}
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
holder.languageName.setText(languageArrayList.get(position).getLanguageName());
}
#Override
public int getItemCount() {
return languageArrayList.size();
}
class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
public TextView languageName;
public RelativeLayout relativeLayout;
public MyViewHolder(View itemView) {
super(itemView);
this.languageName = (TextView) itemView.findViewById(R.id.language);
this.relativeLayout = (RelativeLayout) itemView.findViewById(R.id.relativeLayout);
}
#Override
public void onClick(View v) {
}
}
}

OnCreate() method gets called only once when activity is created. You have set the adapter with the language list in OnCreate() and that it why it gets set only at the first time. When you reenter on the same screen then OnCreate won't get called again.
You have to set the adapter in the OnResume() method because this method will get called every time when you visit this screen.

In your Activity class, override an onResume method, and inside that also declare the following codes-
LanguageAdapter languageAdapter = new LanguageAdapter(this);
recyclerView.setAdapter(languageAdapter);

This is probably too late. But I had this problem as well. For me, the problem was my data binding. I used a custom delegation function to bind my views after they were inflated.
The problem was solved when I changed my delegation to inflate the view instead of binding the current inflated view.

Related

Data is duplicating when navigate back to previous fragment

I am using navigation component in my app I have 2 fragments one fragments list of items and another shows detail of an item when user clicks on an item in fragments 1 it goes to detail fragment and when I switch back to first fragment then all the listing duplicates again.
Below is my code:
CakeFragment.java
public class CakeFragment extends Fragment {
List<AllCakes> allCakeList = new ArrayList<>();
AllCakesAdapter adapter;
BottomNavigationView navView;
FragmentCakeBinding fragmentCakeBinding;
public CakeFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
fragmentCakeBinding = FragmentCakeBinding.inflate(inflater,container,false);
navView = getActivity().findViewById(R.id.navView);
navView.setVisibility(View.GONE);
getAllCakes();
return fragmentCakeBinding.getRoot();
}
private void getAllCakes(){
Retrofit retrofit = RetrofitClient.getInstance();
ApiService apiService = retrofit.create(ApiService.class);
Call<List<AllCakes>> call = apiService.getAllCake();
call.enqueue(new Callback<List<AllCakes>>() {
#Override
public void onResponse(Call<List<AllCakes>> call, Response<List<AllCakes>> response) {
fragmentCakeBinding.cakeProgress.setVisibility(View.INVISIBLE);
fragmentCakeBinding.allCakeRecycler.setHasFixedSize(true);
fragmentCakeBinding.allCakeRecycler.setLayoutManager(new LinearLayoutManager(getActivity()));
allCakeList.addAll(response.body());
adapter = new AllCakesAdapter(getActivity(),allCakeList);
fragmentCakeBinding.allCakeRecycler.setAdapter(adapter);
}
#Override
public void onFailure(Call<List<AllCakes>> call, Throwable t) {
fragmentCakeBinding.cakeProgress.setVisibility(View.INVISIBLE);
TastyToast.makeText(getActivity(),t.getMessage(),TastyToast.LENGTH_SHORT,TastyToast.ERROR).show();
}
});
}
}
AllCakesAdapter.java
public class AllCakesAdapter extends RecyclerView.Adapter<AllCakesAdapter.ViewHolder> {
Context context;
List<AllCakes> allCakeList;
public AllCakesAdapter(Context context, List<AllCakes> allCakeList) {
this.context = context;
this.allCakeList = allCakeList;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.allcakes_row,parent,false);
return new ViewHolder(v);
}
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, int position) {
AllCakes model = allCakeList.get(position);
Glide.with(context).load(model.getImgurl()).into(holder.allCakeImg);
holder.allCakeName.setText(model.getName());
holder.cakeDisPrice.setPaintFlags(holder.cakeDisPrice.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
holder.moreCake.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
NavController navController = Navigation.findNavController((Activity) context,R.id.fragment);
navController.navigate(R.id.cakeDetailFragment);
}
});
}
#Override
public int getItemCount() {
return allCakeList.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
ImageView allCakeImg;
Button moreCake;
TextView allCakeName;
public ViewHolder(#NonNull View itemView) {
super(itemView);
allCakeImg = itemView.findViewById(R.id.allCakeImg);
moreCake = itemView.findViewById(R.id.moreCake);
allCakeName = itemView.findViewById(R.id.allCakeName);
}
}
}
CakeDetailFragment.java
public class CakeDetailFragment extends Fragment {
FragmentCakeDetailBinding fragmentCakeDetailBinding;
public CakeDetailFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
fragmentCakeDetailBinding = FragmentCakeDetailBinding.inflate(inflater,container,false);
return fragmentCakeDetailBinding.getRoot();
}
}
Why is this happening?
private void getAllCakes(){
...
allCakeList.addAll(response.body());
adapter = new AllCakesAdapter(getActivity(),allCakeList);
fragmentCakeBinding.allCakeRecycler.setAdapter(adapter);
}
...
you're calling:
allCakeList.addAll(response.body());
every time without clearing your list out.
you have to clear that list:
allCakeList.clear();
allCakeList.addAll(response.body());
this is something you can easily determine yourself by just putting a breakpoint on your allCakeList to see what's inside it, if you haven't ever done this before, you should consider trying it out
Try the following and see if it solves your issue
CakeFragment.java
allCakeList.clear();
allCakeList.addAll(response.body());
//rest of the logic remains same

How to call onRewardedVideoAdLoaded in onBindViewHolder

I want to use admob with recyclerview but there is a problem. I need to hide some elements that are belong to viewholder. I need to hide the imageview in which position the ImageView belongs. When i click holder.btnReklamIzle the picture in that position must be hid in onRewardedVideoAdLoaded method. How can i transmit the position to onRewardedVideoAdLoaded method?
public View onCreateView(#NonNull LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
View root = inflater.inflate(R.layout.fragment_kuponlar, container, false);
mRewardedVideoAd = MobileAds.getRewardedVideoAdInstance(KuponlarFragment.this.getActivity());
mRewardedVideoAd.setRewardedVideoAdListener(this);
tahminlerRecyclerView = root.findViewById(R.id.tahminlerRecyclerView);
linearLayoutManager = new LinearLayoutManager(this.getActivity());
tahminlerRecyclerView.setLayoutManager(linearLayoutManager);
tahminlerRecyclerView.setHasFixedSize(true);
loadRewardedVideoAd();
fetch();
return root;
}
private void loadRewardedVideoAd() {
mRewardedVideoAd.loadAd(getString(R.string.admob_ads_id),
new AdRequest.Builder().build());
}
private void fetch() {
Query query = FirebaseDatabase.getInstance()
.getReference()
.child("tahminler");
FirebaseRecyclerOptions<Mac> options =
new FirebaseRecyclerOptions.Builder<Mac>()
.setQuery(query, new SnapshotParser<Mac>() {
#NonNull
#Override
public Mac parseSnapshot(#NonNull DataSnapshot snapshot) {
return new Mac((double)snapshot.child("oran").getValue(),
snapshot.child("tahmin").getValue().toString(),
);
}
})
.build();
adapter = new FirebaseRecyclerAdapter<Mac, ViewHolder>(options) {
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.tahmin_tasarim_recyclerview, parent, false);
return new ViewHolder(view);
}
#Override
protected void onBindViewHolder(final ViewHolder holder, final int position, Mac mac) {
holder.btnReklamIzle.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mRewardedVideoAd.isLoaded()) {
mRewardedVideoAd.show();
}
}});
}
};
tahminlerRecyclerView.setAdapter(adapter);
}
#Override
public void onRewardedVideoAdLoaded() {
}
public class ViewHolder extends RecyclerView.ViewHolder {
public ImageView image;
public ViewHolder(View itemView) {
super(itemView);
image = itemView.findViewById(R.id.image);
}
}
onRewardedVideoAdLoaded is a callback method for an asynchronous operation hence you cannot pass values to it as arguments but use referenced variables.
For your case do the following:
Firstly
Create a global variable to hold the list of views to hide
ArrayList<View> views_to_hide = new ArrayList<>();
Secondly
Create a helper function to hide the views
function hideViews(ArrayList<View> views){
for(View v : views) v.setVisibility(View.GONE);
}
Thirdly
Inside onBindViewHolder Add to the list the views you want to hide under your button onClick
public void onClick(View v) {
//...
if (mRewardedVideoAd.isLoaded()) {
mRewardedVideoAd.show();
// Ads already shown you may want to manually hide other images here
}else{
// We only need to add to list when ads not loaded
// We also want to make sure we don't add same view to the list twice
if(!views_to_hide.contains(holder.image))
views_to_hide.add(holder.image);
}});
//...
Finally
Call your helper function inside onRewardedVideoAdLoaded
#Override
public void onRewardedVideoAdLoaded() {
//This hides the views that was added to the list before now
hideViews(views_to_hide);
}

How to dismiss a dialog fragment from a recyclerview adapter

A silly question but I am new to Android and I’ve spent a few hours looking around but can’t find the answer.
I have a dialog fragment with a recyclerview in it. I want the dialog to close when the user clicks a recyclerview item. How do I call dismiss() from the listener in recyclerview adapter?
I've tried a listener for the recyclerview in the dialog fragment but it does nothing. please help.
This is the dialog fragment. At the bottom onClick dismisses it:
public class EvMySchedDlg extends DialogFragment implements View.OnClickListener {
View view;
String eventId;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
view = inflater.inflate(R.layout.event_my_sched, container, false);
ImageView closeButton = view.findViewById(R.id.closeButton3);
closeButton.setOnClickListener(this);
final TextView eventNameBox = view.findViewById(R.id.eventNameBox);
eventNameBox.setOnClickListener(this);
TextView coNameBox = view.findViewById(R.id.coNameBox);
Bundle extraData = getArguments();
eventId = extraData.getString("eventId");
String coName = extraData.getString("coName");
String eventName = extraData.getString("eventName");
coNameBox.setText(coName);
eventNameBox.setText(eventName);
//get list of days from server
String userId = ((DrawerActivity)getContext()).getUserData("userId");
final String[] cred = new String[]{"user_id", userId, "event_id", eventId};
VolleyCalls.postRequest(this.getContext(), "getEventDays", cred, new VolleyCalls.ServerReply() {
#Override
public void onSuccess(String theReply){
final List<EvMySchedData> dayList = new ArrayList<>();
EvMySchedAdapter tAdapter = new EvMySchedAdapter(dayList);
RecyclerView recyclerView = view.findViewById(R.id.schedRecycler);
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(recyclerView.getContext());
recyclerView.setLayoutManager(mLayoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.setAdapter(tAdapter);
tAdapter.emptyRecycler();
try {
JSONObject jsonServerReply = new JSONObject(theReply);
int evCount = jsonServerReply.getInt("recCount");
EvMySchedData thisLine;
if (evCount > 0) {
JSONObject cRec =null;
for (int thisRec=0; thisRec<evCount; thisRec++ ) {
cRec = jsonServerReply.getJSONObject(String.valueOf(thisRec));
thisLine = new EvMySchedData(cRec.getString("day_date"), cRec.getString("day_times"), cRec.getString("role"), cRec.getString("room"), view.getContext());
dayList.add(thisLine);
}
}
} catch (Exception e) {
}
}
public void onError(String error) {
}
});
return view;
} // end onCreateView
public void onClick(View v) {
this.dismiss();
}
}
The recyclerview has the picture of an eye on each line. I want to load a new fragment and close the dialog fragment when the eye is clickd. This is the adapter code:
public class EvMySchedAdapter extends RecyclerView.Adapter<EvMySchedAdapter.EventViewHolder> {
private List<EvMySchedData> dayList;
public EvMySchedAdapter(List<EvMySchedData> dayList) {
this.dayList = dayList;
}
#Override
public EvMySchedAdapter.EventViewHolder onCreateViewHolder(final ViewGroup parent, int viewType) {
final View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.event_my_sched_row, parent, false);
ImageView eye = itemView.findViewById(R.id.dayOverviewButton);
try {
eye.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Load a new fragment
//dismiss the dialog
}
});
} catch (Exception e) {
}
return new EvMySchedAdapter.EventViewHolder(itemView);
}
#Override
public void onBindViewHolder(EvMySchedAdapter.EventViewHolder holder, int position) {
holder.dayDateBox.setText(dayList.get(position).getDayDate());
holder.dayTimeBox.setText(dayList.get(position).getDayTime());
holder.dayRoleBox.setText(dayList.get(position).getDayRole());
holder.dayRoomBox.setText(dayList.get(position).getDayRoom());
} // end onBindViewHolder
#Override
public int getItemCount() {
return dayList.size();
}
public class EventViewHolder extends RecyclerView.ViewHolder {
public TextView dayDateBox;
public TextView dayTimeBox;
public TextView dayRoleBox;
public TextView dayRoomBox;
public Context context;
public EventViewHolder(View view) {
super(view);
dayDateBox = view.findViewById(R.id.dateBox);
dayTimeBox = view.findViewById(R.id.timeBox);
dayRoleBox = view.findViewById(R.id.roleBox);
dayRoomBox = view.findViewById(R.id.roomBox);
}
}
public void emptyRecycler() {
final int size = dayList.size();
dayList.clear();
notifyItemRangeRemoved(0, size);
}
}
Thanks
Add to the adapter a constructor that receive DialogFragment and save it as a field.
When you create the Adapter do new EvMySchedAdapter(dayList, EvMySchedDlg.this);
Inside the onClick call dialgFragment.dismiss();
for Kotlin Users
class SomeAdapter(private val dialog: BottomSheetDialog):RecyclerView.Adapter<SomeAdapter.ViewHolder>()
holder.itemView.setOnClickListener{
dialog.dismiss()
}

showing RecyclerView on fragment with data from Firebase

I'm having a problem with making a RecycleView in a fragment with data from Firebase. I expect the app to show the RecycleView after I clicked on a button to change from one fragment to the RecycleView fragment, but it does change the showed fragment but it does not show anything.
I know there are plenty of questions like this but I don't seem to find the correct solution to this problem.
I've made everything needed for a Firebase RecyclerView, and also tried to build it inside an activity instead fragment and it did work, but not with the fragment.
I've tried to initialize the adapter and recyclerview inside the onCreateView method, onActivityCreated, and onViewCreated method and none of them seem to be working.
Here's my fragment code:
private KidAdapter adapter;
private RecyclerView recyclerView;
Button button;
View view;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
view = inflater.inflate(R.layout.uangsaku_menu_fragment, container, false);
button = view.findViewById(R.id.btn_add);
button.setOnClickListener(this);
recyclerView = view.findViewById(R.id.recyclerView);
recyclerView.setHasFixedSize(true);
setUpRecyclerView();
return view;
}
#Override
public void onClick(View v) {
if(v.getId() == R.id.btn_add){
Intent intent = new Intent(getActivity(), Register.class);
startActivity(intent);
}
}
public void setUpRecyclerView(){
Query query = FirebaseDatabase.getInstance().getReference("kids");
FirebaseRecyclerOptions<kidData> options = new FirebaseRecyclerOptions.Builder<kidData>()
.setQuery(query, kidData.class)
.build();
adapter = new KidAdapter(options);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getContext(), LinearLayoutManager.HORIZONTAL, false);
recyclerView.setLayoutManager(linearLayoutManager);
recyclerView.setAdapter(adapter);
}
#Override
public void onStart() {
super.onStart();
if (adapter != null) {
adapter.startListening();
}
}
#Override
public void onStop() {
super.onStop();
if (adapter != null) {
adapter.stopListening();
}
}
}
The adapter class
public class KidAdapter extends FirebaseRecyclerAdapter<kidData, KidAdapter.KidViewHolder> {
public KidAdapter(#NonNull FirebaseRecyclerOptions<kidData> options) {
super(options);
}
#Override
protected void onBindViewHolder(#NonNull KidViewHolder holder, int position, #NonNull kidData model) {
holder.nama.setText(model.getKidName());
holder.balance.setText(model.getKidBalance());
holder.limit.setText("Limit: "+model.getKidLimit());
holder.spending.setText("Spending xxx.xxx");
}
#NonNull
#Override
public KidViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.kids_card,
viewGroup, false);
return new KidViewHolder(v);
}
public class KidViewHolder extends RecyclerView.ViewHolder {
TextView nama, balance, limit, spending;
public KidViewHolder(#NonNull View itemView) {
super(itemView);
nama = itemView.findViewById(R.id.tv_nama);
balance = itemView.findViewById(R.id.tv_balance);
limit = itemView.findViewById(R.id.tv_dailylimit);
spending = itemView.findViewById(R.id.tv_dailyspending);
}
}
}
The kidData model class
public class kidData {
String kidName, kidEmail, kidDoB, kidLimit, kidBalance;
public kidData(){
}
public kidData(String kidName, String kidEmail, String kidDoB, String kidLimit, String kidBalance) {
this.kidName = kidName;
this.kidEmail = kidEmail;
this.kidDoB = kidDoB;
this.kidLimit = kidLimit;
this.kidBalance = kidBalance;
}
public String getKidName() {
return kidName;
}
public String getKidEmail() {
return kidEmail;
}
public String getKidDoB() {
return kidDoB;
}
public String getKidLimit() {
return kidLimit;
}
public String getKidBalance() {
return kidBalance;
}
}
The problem in your code is the use of the following line of code:
recyclerView.setHasFixedSize(true);
And this is because when using the latest version of Firebase-UI library, there is no need to set the size of the RecyclerView as fixed. The solution for solving this problem is to simply remove/comment the above line of code. That's it!

add Onclick on adapter for each item to open new different activity

I have Adapter in my project and few fragments where I populate fragments with celebrity names and date of birth as it is given in below image
I will like to call a different url to launch for each item
For First Item
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.stackoverflow.com")));
For Second Item
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.youtube.com")));
and so on
Below is my Adapter Class
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> {
private List<Model> mDataset;
private ImageLoader mImageLoader;
// Provide a reference to the views for each data item
// Complex data items may need more than one view per item, and
// you provide access to all the views for a data item in a view holder
public static class ViewHolder extends RecyclerView.ViewHolder {
// each data item is just a string in this case
public TextView nameText;
public TextView phoneText;
public NetworkImageView image;
#SuppressLint("WrongViewCast")
public ViewHolder(View v) {
super(v);
nameText = v.findViewById(R.id.name_text);
phoneText = v.findViewById(R.id.phone_text);
image = v.findViewById(R.id.imgAvatar);
image.setDefaultImageResId(R.mipmap.ic_launcher);
v.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(v.getContext(),"Position: "+getAdapterPosition(), Toast.LENGTH_SHORT).show();
}
});
}
}
// Provide a suitable constructor (depends on the kind of dataset)
public MyAdapter(List<Model> myDataset, Context mCOntext) {
Log.d("TEST",myDataset.get(0).getName());
mDataset = myDataset;
mImageLoader = MySingleton.getInstance(mCOntext).getImageLoader();
}
// Create new views (invoked by the layout manager)
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent,
int viewType) {
// create a new view
View v = LayoutInflater.from(parent.getContext())
.inflate(R.layout.card_view, parent, false);
// set the view's size, margins, paddings and layout parameters
ViewHolder vh = new ViewHolder(v);
return vh;
}
public interface ItemClickListener {
void onItemClick(View view, int position);
}
// Replace the contents of a view (invoked by the layout manager)
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
// - get element from your dataset at this position
// - replace the contents of the view with that element
//holder.mTextView.setText(mDataset.get(position).getName());
Log.d("TEST","Printing Names onBindView Holder"+mDataset.get(position).getName());
holder.nameText.setText(mDataset.get(position).getName());
holder.phoneText.setText(mDataset.get(position).getPhone());
holder.image.setImageUrl(mDataset.get(position).getImage(),mImageLoader);
}
// Return the size of your dataset (invoked by the layout manager)
#Override
public int getItemCount() {
return mDataset.size();
}
}
and my Fragment is
public class english extends Fragment implements Response.Listener , Response.ErrorListener {
View view;
RecyclerView mRecyclerView;
private RecyclerView.LayoutManager mLayoutManager;
private Context context;
private List<Model> contactList = new ArrayList<>();
private String url ="https://api.androidhive.info/json/contacts.json";
Button btn;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
view = inflater.inflate(R.layout.home_fragment,container,false);
context = getContext();
mLayoutManager = new GridLayoutManager(context,2);
mRecyclerView = (RecyclerView)view.findViewById(R.id.my_recycler_view);
mRecyclerView.setLayoutManager(mLayoutManager);
mRecyclerView.setHasFixedSize(true);
mRecyclerView.setLayoutManager(mLayoutManager);
getContactList();
return view;
}
private void getContactList(){
Log.d("TEST","Getting Contact list");
Controller.getInstance(context).makeNetworkCalls(Request.Method.GET,url,this,this);
}
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "Error: " + error.getMessage());
Toast.makeText(context, "Error: " + error.getMessage(), Toast.LENGTH_SHORT).show();
}
#Override
public void onResponse(Object response) {
Log.d("TEST","Got The response" +response);
if (response == null) {
Toast.makeText(context, "Couldn't fetch the contacts! Pleas try again.", Toast.LENGTH_LONG).show();
return;
}
List<Model> items = new Gson().fromJson(response.toString(), new TypeToken<List<Model>>(){}.getType());
contactList.addAll(items);
MyAdapter rcAdapter = new MyAdapter(contactList,context);
mRecyclerView.setAdapter(rcAdapter);
}
}
Please Help.
its Simple
First Create URL Array
in The Adapter Classs
ArrayList<String> UrlsToTran=new ArrayList<>();
in The Adapter Class Constructor
MyAdapter(Context mContext)
{
//Assing Context
//Assign The Urls
UrlsToTran.add("www.stackoverflow.com");
UrlsToTran.add("www.facebook.com");
//And Add More Values As U need
}
Then Add OnClick Listener
public void onBindViewHolder(ViewHolder holder, int position) {
// - get element from your dataset at this position
// - replace the contents of the view with that element
//holder.mTextView.setText(mDataset.get(position).getName());
Log.d("TEST","Printing Names onBindView
Holder"+mDataset.get(position).getName());
holder.nameText.setText(mDataset.get(position).getName());
holder.phoneText.setText(mDataset.get(position).getPhone());
holder.image.setImageUrl(mDataset.get(position).getImage(),mImageLoader);
holder.image.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
context.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(UrlsToTran.get(position).toString())));
}
});
}
First, for every item in your adapter create an OnClickListener like this:
holder.image.setOnClickListener(v->{
});
Now Create an interface between the adapter and the fragment/activity that shows the list
public interface ModelListener {
void onModelClicked(Model model);
}
In your activity/fragment listen to an item click and send the intent
new ModelListener(){
public void onModelClicked(Model model){
startActivity(new Intent(.., model.getUrl()));
}
}

Categories