NotifyDatasetchanged not working. AppCrashes after ButtonOnClick [duplicate] - java

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 2 years ago.
I've been trying to create a button that adds a new Value to my Arraylist (contries) when clicked, but it instead of adding my item(Card) the app simply crashes. I am also using Fragments. Here's my code.
That one is my Class for my FragmentPage
package com.example.barryblack;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
public class FragmentPage extends Fragment {
private RecyclerView.Adapter mAdapter;
private ArrayList countries;
Button btn;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable
Bundle savedInstanceState) {
CreateExampleList();
View view = inflater.inflate(R.layout.page_fragment, container, false);
RecyclerView recyclerView = view.findViewById(R.id.listRecyclerView);
btn = view.findViewById(R.id.button_insert);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
InsertItem();
}
});
recyclerView.setHasFixedSize(true);
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getActivity());
recyclerView.setLayoutManager(layoutManager);
RecyclerView.Adapter adapter = new MyAdapter(countries);
recyclerView.setAdapter(adapter);
return view;
}
public void InsertItem() {
countries.add("Smile");
mAdapter.notifyDataSetChanged();
}
private void CreateExampleList() {
countries = new ArrayList<String>();
countries.add("Eat");
countries.add("Kill");
}
}
This is my CustomAdapter
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> {
private ArrayList<String> cards;
public MyAdapter(ArrayList<String> countries) {
this.cards = countries;
}
#Override
public MyAdapter.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.example_item, viewGroup,
false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(MyAdapter.ViewHolder viewHolder, int i) {
viewHolder.tv_country.setText(cards.get(i));
}
#Override
public int getItemCount() {
return cards.size();
}
public class ViewHolder extends RecyclerView.ViewHolder{
private TextView tv_country;
private Button tv_button;
public ViewHolder(View view) {
super(view);
tv_country = (TextView)view.findViewById(R.id.tv_country);
}
}
}public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> {
private ArrayList<String> cards;
public MyAdapter(ArrayList<String> countries) {
this.cards = countries;
}
#Override
public MyAdapter.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.example_item, viewGroup,
false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(MyAdapter.ViewHolder viewHolder, int i) {
viewHolder.tv_country.setText(cards.get(i));
}
#Override
public int getItemCount() {
return cards.size();
}
public class ViewHolder extends RecyclerView.ViewHolder{
private TextView tv_country;
private Button tv_button;
public ViewHolder(View view) {
super(view);
tv_country = (TextView)view.findViewById(R.id.tv_country);
}
}
}
And my LogcatText
java.lang.NullPointerException: Attempt to invoke virtual method 'void androidx.recyclerview.widget.RecyclerView$Adapter.notifyDataSetChanged()' on a null object reference
at com.example.barryblack.FragmentPage.InsertItem(FragmentPage.java:60)
at com.example.barryblack.FragmentPage$1.onClick(FragmentPage.java:43)

this code private RecyclerView.Adapter mAdapter;
must be private MyAdapter mAdapter;
and this RecyclerView.Adapter adapter = new MyAdapter(countries);
to this MyAdapter mAdapter = new MyAdapter(countries);

Related

Recycler View not showing any data

I am trying to implement recycler View in android but after adding it to the app it is not showing anything. I have searched online yet I am not able to figure out what am I doing wrong.
Also When I declare dashpercent and dashsubject (mentioned in adapter) in class RecyclerViewHolder extends RecyclerView.ViewHolder the on writing :
#Override
public void onBindViewHolder(#NonNull RecyclerView.ViewHolder holder, int position) {
dashboard_recycler_components data = dashlist.get(position);
String sub = data.Subject;
holder.dashpercent.setText(data.percentage);
holder.dashsubject.setText(data.Subject);
}
then dashpercent and dashsubject give an error that they are not declared.
Adapter
package com.example.attendance;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ProgressBar;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
public class RecyclerAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private ArrayList<dashboard_recycler_components> dashlist;
RecyclerAdapter(ArrayList<dashboard_recycler_components> a) {
this.dashlist = a;
}
#NonNull
#Override
public RecyclerView.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from((parent.getContext()));
View view = inflater.inflate(R.layout.attendace_card, parent, false);
return new RecyclerViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull RecyclerView.ViewHolder holder, int position) {
dashboard_recycler_components data = dashlist.get(position);
String sub = data.Subject;
TextView dashpercent = (TextView) holder.itemView.findViewById(R.id.dashPercent);
TextView dashsubject = (TextView) holder.itemView.findViewById(R.id.dashSubject);
ProgressBar dashProgress = (ProgressBar) holder.itemView.findViewById(R.id.recycler_progress);
dashpercent.setText(data.percentage);
dashsubject.setText(data.Subject);
}
#Override
public int getItemCount() {
return dashlist.size();
}
public class RecyclerViewHolder extends RecyclerView.ViewHolder {
RecyclerViewHolder(#NonNull View itemView) {
super(itemView);
}
}
}
dashboadfragment:
package com.example.attendance;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.ListAdapter;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
public class dashboardfragment extends Fragment {
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
ArrayList<dashboard_recycler_components> subList = new ArrayList<>();
dashboard_recycler_components a = new dashboard_recycler_components("DSA",33);
dashboard_recycler_components b = new dashboard_recycler_components("DSA",33);
dashboard_recycler_components c = new dashboard_recycler_components("DSA",33);
dashboard_recycler_components d = new dashboard_recycler_components("DSA",33);
dashboard_recycler_components e = new dashboard_recycler_components("DSA",33);
dashboard_recycler_components f = new dashboard_recycler_components("DSA",33);
dashboard_recycler_components g = new dashboard_recycler_components("DSA",33);
dashboard_recycler_components h = new dashboard_recycler_components("DSA",33);
dashboard_recycler_components i = new dashboard_recycler_components("DSA",33);
dashboard_recycler_components j = new dashboard_recycler_components("DSA",33);
subList.add(a);
subList.add(b);
subList.add(c);
subList.add(d);
subList.add(e);
subList.add(f);
subList.add(g);
subList.add(h);
subList.add(i);
subList.add(j);
View v = inflater.inflate(R.layout.fragment_dashboard,container,false);
RecyclerView recycle = (RecyclerView)v.findViewById(R.id.recycler_view1);
recycle.setLayoutManager(new LinearLayoutManager(getActivity()));
recycle.setAdapter(new RecyclerAdapter(subList));
return v;
}
}
dashbord_recycler_componets:
package com.example.attendance;
public class dashboard_recycler_components {
int percentage;
String Subject;
public dashboard_recycler_components(String a , int b){
this.percentage = b;
this.Subject = a;
}
public int getPercentage() {
return percentage;
}
public String getSubject() {
return Subject;
}
public void setPercentage(int percentage) {
this.percentage = percentage;
}
public void setSubject(String subject) {
this.Subject = subject;
}
}
MainActivity:
package com.example.attendance;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import android.os.Bundle;
import android.view.MenuItem;
import android.widget.ProgressBar;
import com.google.android.material.bottomnavigation.BottomNavigationView;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
BottomNavigationView bottomNav = findViewById(R.id.bottom_nav_bar);
bottomNav.setOnNavigationItemSelectedListener(navListener);
getSupportFragmentManager().beginTransaction().replace(R.id.frame_container,
new homefragment()).commit();
}
private BottomNavigationView.OnNavigationItemSelectedListener navListener = new
BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem menuItem) {
Fragment frag = null;
switch (menuItem.getItemId()) {
case R.id.dashboard:
frag = new dashboardfragment();
break;
case R.id.profile:
frag = new profilefragment();
break;
case R.id.home:
frag = new homefragment();
break;
}
getSupportFragmentManager().beginTransaction().replace(R.id.frame_container,
frag).commit();
return true;
}
};
}
Your percentage in dashboard_recycler_components is an int if you want to assign
your percentage is an int if you want to assign it to your dashpercent you have to first make this int a String such as : dashpercent.setText(String.valueOf(data.percentage));
PS:
You should rename your class object dashboard_recycler_components to dashboardRecyclerComponents and use camelCase instead of snake_case
The Problem is you are trying to get the layout views inside onBindViewHolder and you can't this you can declare your viewes in your custom ViewHolder and get the views inside onBindViewHolder like this ... i think this gonna solve your problem
public class RecyclerAdapter extends RecyclerView.Adapter<RecyclerAdapter.RecyclerViewHolder> {
private ArrayList<dashboard_recycler_components> dashlist;
RecyclerAdapter(ArrayList<dashboard_recycler_components> a) {
this.dashlist = a;
}
#NonNull
#Override
public RecyclerViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from((parent.getContext()));
View view = inflater.inflate(R.layout.attendace_card, parent, false);
return new RecyclerViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull RecyclerViewHolder holder, int position) {
dashboard_recycler_components data = dashlist.get(position);
String sub = data.Subject;
holder.dashpercent.setText(data.percentage);
holder.dashsubject.setText(data.Subject);
}
#Override
public int getItemCount() {
return dashlist.size();
}
public static class RecyclerViewHolder extends RecyclerView.ViewHolder {
TextView dashpercent;
TextView dashsubject;
ProgressBar dashProgress;
RecyclerViewHolder(#NonNull View itemView) {
super(itemView);
dashpercent = itemView.findViewById(R.id.dashPercent);
dashsubject = itemView.findViewById(R.id.dashSubject);
dashProgress = itemView.findViewById(R.id.recycler_progress);
}
}
}

Recycler View not showing my images and categories from Firebase

This is the code for CategoryHolder:
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.example.clothesshop.Interfaces.ItemClickListener;
import com.example.clothesshop.R;
public class CategoriesHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
public TextView categoryName;
public ImageView imageView;
private ItemClickListener itemClickListener;
public CategoriesHolder(#NonNull View itemView) {
super(itemView);
categoryName = (TextView) itemView.findViewById(R.id.category_name);
imageView = (ImageView) itemView.findViewById(R.id.category_image);
itemView.setOnClickListener(this);
}
public void setItemClickListener(ItemClickListener itemClickListener) {
this.itemClickListener = itemClickListener;
}
#Override
public void onClick(View v) {
itemClickListener.onClick(v,getAdapterPosition(),false);
}
}
And this is where i'm trying to bind data from firebase:
recyclerMenu = (RecyclerView) findViewById(R.id.recycler_menu);
recyclerMenu.hasFixedSize();
layoutManager = new LinearLayoutManager(this);
recyclerMenu.setLayoutManager(layoutManager);
FirebaseRecyclerOptions options = new FirebaseRecyclerOptions.Builder<Category> ().setQuery(category, Category.class).build();
adapter = new FirebaseRecyclerAdapter<Category, CategoriesHolder>(options) {
#NonNull
#Override
public CategoriesHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.menu_item, parent, false);
return new CategoriesHolder(view);
}
#Override
protected void onBindViewHolder(#NonNull CategoriesHolder holder, int position, #NonNull Category model) {
holder.categoryName.setText(model.getName());
}
};
recyclerMenu.setAdapter(adapter);
And the screen is not showing anything
How can I resolve this? I used the latest firebase-ui and firebase-database packages.
I'm trying to solve this but it doesn't work. In database, category has 2 fiels(image, which is a link and name of the category).

Retrofit RecyclerView not working in tab layout

I've been trying to implement a recycler view inside a fragment which displays parsed data using the retrofit library. Whenever I run the project the lists don't show and the monitor says "E/RecyclerView: No adapter attached; skipping layout". Here is my code:
MainActivity:
package com.example.ahmed.newsapp
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.support.design.widget.TabLayout;
public class MainActivity extends AppCompatActivity {
private static final String TAG = MainActivity.class.getSimpleName();
private static final int ACTIVITY_NUM = 0;
// TODO - insert your themoviedb.org API KEY here
private final static String API_KEY = "<API KEY CENSORED>";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Find the view pager that will allow the user to swipe between fragments
ViewPager viewPager = (ViewPager) findViewById(R.id.viewpager);
// Create an adapter that knows which fragment should be shown
FragmentAdapter adapter = new FragmentAdapter(getSupportFragmentManager
());
// Set the adapter onto the view pager
viewPager.setAdapter(adapter);
TabLayout ob=(TabLayout) findViewById(R.id.sliding_tabs);
ob.setupWithViewPager(viewPager);
}
}
FragmentAdapter:
package com.example.ahmed.newsapp;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
/**
* Created by ahmed on 3/22/2017.
*/
public class FragmentAdapter extends FragmentPagerAdapter {
private String tabs[]=new String[]{"Home","Family Members","Colors"};
public FragmentAdapter(FragmentManager fm){
super(fm);
}
#Override
public Fragment getItem(int position) {
switch(position){
case 0:
return new HomeActivity();
case 1:
return new HomeActivity();
/* case 2:
return new ColorFragment();*/
}
return null;
}
#Override
public CharSequence getPageTitle(int position) {
return tabs[position];
}
#Override
public int getCount() {
return 2;
}
}
NewsAdapter:
package com.example.ahmed.newsapp;
/**
* Created by ahmed on 27-08-17.
*/
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.LinearLayout;
import android.widget.TextView;
import java.util.List;
public class NewsAdapter extends RecyclerView.Adapter<NewsAdapter.NewsViewHolder> {
private List<News> news;
private int rowLayout;
private Context context;
public static class NewsViewHolder extends RecyclerView.ViewHolder {
LinearLayout moviesLayout;
TextView movieTitle;
TextView data;
TextView movieDescription;
TextView rating;
public NewsViewHolder(View v) {
super(v);
moviesLayout = (LinearLayout) v.findViewById(R.id.movies_layout);
movieTitle = (TextView) v.findViewById(R.id.title);
data = (TextView) v.findViewById(R.id.subtitle);
movieDescription = (TextView) v.findViewById(R.id.description);
rating = (TextView) v.findViewById(R.id.rating);
}
}
public NewsAdapter(List<News> news, Context context) {
this.news = news;
// this.rowLayout = rowLayout;
this.context = context;
}
#Override
public NewsViewHolder onCreateViewHolder(ViewGroup parent,
int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.list_item_news, parent, false);
return new NewsViewHolder(view);
}
#Override
public void onBindViewHolder(NewsViewHolder holder, final int position) {
holder.movieTitle.setText(news.get(position).getTitle());
holder.data.setText(news.get(position).getReleaseDate());
holder.movieDescription.setText(news.get(position).getOverview());
holder.rating.setText(news.get(position).getVoteAverage().toString());
}
#Override
public int getItemCount() {
return news.size();
}
}
HomeActivity:
package com.example.ahmed.newsapp;
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.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
import java.util.List;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import static android.content.ContentValues.TAG;
public class HomeActivity extends Fragment {
RecyclerView recyclerView;
private final static String API_KEY = "<API KEY CENSORED>";
NewsAdapter adapter;
List<News> news,dummy;
View rootview;
public HomeActivity() {
// Required empty public constructor
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
rootview = inflater.inflate(R.layout.activity_home, container, false);
if (API_KEY.isEmpty()) {
Toast.makeText(getContext(), "Please obtain your API KEY first from themoviedb.org", Toast.LENGTH_LONG).show();
return rootview;
}
ApiInterface apiService =
ApiClient.getClient().create(ApiInterface.class);
recyclerView = (RecyclerView) rootview.findViewById(R.id.home_page_recycler_view);
adapter= new NewsAdapter(dummy,getContext());
Call<NewsResponse> call = apiService.getTopRatedMovies(API_KEY);
call.enqueue(new Callback<NewsResponse>() {
#Override
public void onResponse(Call<NewsResponse> call, Response<NewsResponse> response) {
news = response.body().getResults();
adapter.notifyDataSetChanged();
adapter=new NewsAdapter(news,getContext());
recyclerView.setAdapter(adapter);
// adapter.setData(news);
Log.d(TAG, "Number of movies received: " + news.size());
}
#Override
public void onFailure(Call<NewsResponse> call, Throwable t) {
// Log error here since request failed
Log.e(TAG, t.toString());
}
});
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(getContext(), LinearLayoutManager.VERTICAL, false));
return rootview;
}
}
i think the problem is in your FragmentAdapter class
just remove return null; statement from your FragmentAdapter like below code
#Override
public Fragment getItem(int position) {
Fragment fragment=null;
switch(position){
case 0:
fragment= new HomeActivity();
case 1:
fragment= new HomeActivity();
/* case 2:
return new ColorFragment();*/
}
return fragment;
}
change this
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(getContext(), LinearLayoutManager.VERTICAL, false));
recyclerView = (RecyclerView) rootview.findViewById(R.id.home_page_recycler_view);
adapter= new NewsAdapter(dummy,getContext());
You don't need to recreate your adapter when you receive response.
It may looks like:
recyclerView = (RecyclerView) rootview.findViewById(R.id.home_page_recycler_view);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
adapter = new NewsAdapter(null, getActivity());
recyclerView.setAdapter(adapter);
Call<NewsResponse> call = apiService.getTopRatedMovies(API_KEY);
call.enqueue(new Callback<NewsResponse>() {
#Override
public void onResponse(Call<NewsResponse> call, Response<NewsResponse> response) {
news = response.body().getResults();
adapter.setData(news);
Log.d(TAG, "Number of movies received: " + news.size());
}
...
And in NewsAdapter:
...
public void setData(Collection<News> newData) {
news.clear();
news.addAll(newData);
notifyDataSetChanged();
}
#Override
public int getItemCount() {
return news == null ? 0 : news.size();
}
...

How to initialize custom adapter in an Activity

I have a custom pager adapter (PagerIot) that I have successfully implemented using a fragment as shown below
public class SensorIconFragment extends Fragment {
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.layout_listview, container, false);
ButterKnife.bind(this, view);
pagerIot = (PagerIot)container;
I would however like to use the pager adapter in a activity but the problem is I need to know how to initialize the pager in an activity. In a fragment its quite simple because fragments have an onCreateViewMethod where a viewGroup is passed in as a parameter so I can simply say pPagerIot = (PagerIot)container;
In Activity however I cannot simply initialize the PagerIOT because onCreate does not pass in a ViewGroup so does anyone know how I can initialize the adapter in an Activity ?
This is my PagerIOT class below
public class PagerIot extends ViewPager
{
public PagerIot(Context context, AttributeSet attrs)
{
super(context, attrs);
}
public void allowScrollingToTab(int tab)
{
// Set the limit of the number of pages in the page adapter
ManagementTabFragment.SectionsPagerAdapter adapter = (ManagementTabFragment.SectionsPagerAdapter)getAdapter();
adapter.allowScrollingToTab(tab);
}
}
I will also include the managenment tab referenced in the class above
package com.dtect.devicesensorinsight.home.tabs;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.dtect.common.ITabView;
import com.dtect.common.MyFragmentPagerAdapter;
import com.dtect.devicesensorinsight.R;
import com.dtect.devicesensorinsight.events.JumpToManagementTabEvent;
import com.dtect.devicesensorinsight.home.PagerIot;
import com.dtect.devicesensorinsight.home.tabs.management.CostCentreListFragment;
import com.dtect.devicesensorinsight.home.tabs.management.IotTabFragment;
import com.dtect.devicesensorinsight.home.tabs.management.SensorIconFragment;
//import com.dtect.devicesensorinsight.home.tabs.notifications.TenantDetailsFragment;
import com.dtect.devicesensorinsight.home.tabs.management.iot.SensorInformationChildFragment;
import com.dtect.devicesensorinsight.sensors.ItemClickedEvent;
import java.util.Locale;
import butterknife.BindView;
import butterknife.ButterKnife;
import de.greenrobot.event.EventBus;
public class ManagementTabFragment extends Fragment implements ITabView
{
public static final int TAB_USER_LANDINGPAGE = 0;
public static final int TAB_TENANT_SCANQRCODE= 1;
public static final int TAB_TENANT_DETAILS = 2;
public static final int TAB_UOM_SYMBOLS = 3;
public static final int TAB_LOCATIONS = 4;
public static final int TAB_IOT = 5;
#BindView(R.id.managementpager)
PagerIot viewPager;
private SectionsPagerAdapter sectionsPagerAdapter;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
View view = inflater.inflate(R.layout.fragment_management_pages, container, false);
ButterKnife.bind(this, view);
sectionsPagerAdapter = new SectionsPagerAdapter(getChildFragmentManager());
viewPager.setAdapter(sectionsPagerAdapter);
viewPager.setOffscreenPageLimit(5);
return view;
}
#Override
public void onStart() {
super.onStart();
EventBus.getDefault().register(this);
}
#Override
public void onStop() {
super.onStop();
EventBus.getDefault().unregister(this);
}
public void onEvent(JumpToManagementTabEvent tab) {
setSelectedPage(tab.tabIndex);
}
private void setSelectedPage(int index)
{
viewPager.setCurrentItem(index);
}
#Override
public MyFragmentPagerAdapter getAdapter() {
return sectionsPagerAdapter;
}
#Override
public ViewPager getViewPager() {
return viewPager;
}
/**
* A {#link FragmentPagerAdapter} that returns a fragment corresponding to
* one of the sections/tabs/pages.
*/
public class SectionsPagerAdapter extends MyFragmentPagerAdapter {
private int allowScrollingToTabOffset = 0;
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
public void allowScrollingToTab(int tab)
{
this.allowScrollingToTabOffset = tab;
notifyDataSetChanged();
}
#Override
public Fragment getItem(int position) {
switch (position)
{
case TAB_USER_LANDINGPAGE:
return new UserLandingPageFragment();
case TAB_UOM_SYMBOLS:
return new SensorIconFragment();
case TAB_LOCATIONS:
return new CostCentreListFragment();
case TAB_IOT:
return new IotTabFragment();
default:
return null;
}
}
#Override
public int getCount() {
return allowScrollingToTabOffset + 1;
}
#Override
public CharSequence getPageTitle(int position) {
Locale l = Locale.getDefault();
return "" + position;
}
}
}

Implementing onClick in the Recyclerview Adapter

I would like to know how to implement onClick for each item in my
grid (using Recycler View and Card view) to launch a new
activity.Below is my ViewHolder class and the RecyclerView Adapter
Class
This is my RecyclerView Adapter Class
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.nfc.Tag;
import android.nfc.TagLostException;
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.Toast;
import java.util.List;
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewHolders> {
private List<ItemObject> itemList;
private Context context;
public RecyclerViewAdapter(Context context, List<ItemObject> itemList) {
this.itemList = itemList;
this.context = context;
}
#Override
public RecyclerViewHolders onCreateViewHolder(ViewGroup parent, int viewType) {
View layoutView = LayoutInflater.from(parent.getContext()).inflate(R.layout.card_view_list, null);
RecyclerViewHolders rcv = new RecyclerViewHolders(layoutView);
return rcv;
}
#Override
public void onBindViewHolder(RecyclerViewHolders holder, final int position) {
holder.countryName.setText(itemList.get(position).getName());
holder.countryPhoto.setImageResource(itemList.get(position).getPhoto());
holder.countryPhoto.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(view.getContext(),"This is Maps",Toast.LENGTH_SHORT).show();
}
});
}
#Override
public int getItemCount() {
return this.itemList.size();
}
}
//This is my Recycler View Holder Class
import android.content.Intent;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
public class RecyclerViewHolders extends RecyclerView.ViewHolder implements View.OnClickListener {
public TextView countryName;
public ImageView countryPhoto;
public RecyclerViewHolders(View itemView) {
super(itemView);
itemView.setOnClickListener(this);
countryName = (TextView) itemView.findViewById(R.id.country_name);
countryPhoto = (ImageView) itemView.findViewById(R.id.country_photo);
}
#Override
public void onClick(View view) {
Toast.makeText(view.getContext(), "Clicked Country Position = " + getPosition(), Toast.LENGTH_SHORT).show();
}
}
I use Interface as the Callback to handle this case.
First, I create an interface class inside Adapter.
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewHolders> {
private List<ItemObject> itemList;
private Context context;
private ItemClickListener mItemClickListener;
public RecyclerViewAdapter(Context context, List<ItemObject> itemList) {
this.itemList = itemList;
this.context = context;
}
#Override
public RecyclerViewHolders onCreateViewHolder(ViewGroup parent, int viewType) {
View layoutView = LayoutInflater.from(parent.getContext()).inflate(R.layout.card_view_list, null);
RecyclerViewHolders rcv = new RecyclerViewHolders(layoutView);
return rcv;
}
public void addItemClickListener(ItemClickListener listener) {
mItemClickListener = listener;
}
#Override
public void onBindViewHolder(RecyclerViewHolders holder, final int position) {
holder.countryName.setText(itemList.get(position).getName());
holder.countryPhoto.setImageResource(itemList.get(position).getPhoto());
holder.countryPhoto.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (mItemClickListener != null) {
mItemClickListener.onItemClick(position);
}
}
});
}
#Override
public int getItemCount() {
return this.itemList.size();
}
//Define your Interface method here
public interface ItemClickListener {
void onItemClick(int position);
}
}
Then, let's the Activity or Fragment implement that Interface and add the listener.
public class MyFragment extends Fragment
implements RecyclerViewAdapter.ItemClickListener {
private List<ItemObject> mItemList;
...
#Override
public View onCreateView(final LayoutInflater inflater, final ViewGroup container,
final Bundle savedInstanceState) {
...
//Make sure mItemList not NULL
RecyclerViewAdapter adapter = new RecyclerViewAdapter(getContext(), mItemList);
//Add Item Click listener
adapter.addItemClickListener(this);
}
#Override
public void onItemClick(int position) {
Toast.makeText(.getContext(),"Click on item: " + position,Toast.LENGTH_SHORT).show();
}
}
Hope this will help!
your code look like fine, if asking for how to creat intent to open new activity here is whet you should change
it is lazy way not recommended for best pratice
make a static variable in your Mian activty witch is hold a refrance some thing like that
public class MainActivity extends AppCompatActivity
public static Activity activity;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setElevation(0);
activity=this;
}
}
and then inside your click
...
#Override
public void onClick(View v) {
Toast.makeText(.getContext(),"Click on item: " + position,Toast.LENGTH_SHORT).show();
startActivity(new Intent(MainActivity.activity, MyOtherActivity.class));
}
...
I'm not completely clear from your initial post what your issue is, but if all you want to do is implement an OnClickListener in your RecyclerViewAdapter, just add the following:
First, change your class declaration to this:
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewHolders> implements OnClickListener {
Then, add your onClick method to the class, to complete the interface.
#Override
public void onClick(View view) {
Toast.makeText(this.getContext(),"Code to change activity goes here." ,Toast.LENGTH_SHORT).show();
}
Finally, you'll need to set an OnClickListener in your adapter class.
#Override
public void onBindViewHolder(RecyclerViewHolders holder, final int position) {
holder.setOnClickListener(this);
holder.countryName.setText(itemList.get(position).getName());
holder.countryPhoto.setImageResource(itemList.get(position).getPhoto());
holder.countryPhoto.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (mItemClickListener != null) {
mItemClickListener.onItemClick(position);
}
}
});
}
Now, personally I wouldn't do things this way. What I would do instead is add a private inner class to your adapter, like this:
private AdapterOnClickListener implements OnClickListener() {
private String message;
public AdapterOnClickListener (String toast) {
message = toast;
}
public void onClick (View v) {
Toast.makeText(this.getContext(),toast ,Toast.LENGTH_SHORT).show();
}
}
Then in the adapter you call:
#Override
public void onBindViewHolder(RecyclerViewHolders holder, final int position) {
holder.setOnClickListener(new AdapterOnClickListener ("Instead of a string, I can be an intent. Then in your listener, you can call (If I recall correctly) getContext().startActivity(intent), and have an activity.");
holder.countryName.setText(itemList.get(position).getName());
holder.countryPhoto.setImageResource(itemList.get(position).getPhoto());
holder.countryPhoto.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (mItemClickListener != null) {
mItemClickListener.onItemClick(position);
}
}
});
}

Categories