how to Add urlimage to AdapterViewPager from MainActivity - AndroidX - java

I want to add the URLimage to AdapterViewPager from the MainActivity in AndroidX but I am not sure how to do this.
This is my AdapterViewPager.java
public class AdapterViewPagerHot extends PagerAdapter {
private Context mContext;
private LayoutInflater layoutInflater;
/*private Integer[] images = {R.drawable.cat_mermaid_cartoon_grumpy_cat_94004_1280x720,R.drawable.catnrobot,R.drawable.kleptocats,R.drawable.magiccat,R.drawable.flyingcat};*/
public String image_url[] = new String[]{
"https://i.chzbgr.com/full/8803531264/hD42E57C6/"
};
public AdapterViewPagerHot(Context context) {
this.mContext = context;
}
#Override
public int getCount() {
return image_url.length;
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == object;
}
public View vi;
#Override
public Object instantiateItem(ViewGroup container, final int position) {
layoutInflater = (LayoutInflater) this.mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
vi = layoutInflater.inflate(R.layout.item_viewpagerdisplay, null);
final Context sContext = mContext;
ImageView imageView = vi.findViewById(R.id.imageView);
final ImageView ICONHotViewPagerSaving = vi.findViewById(R.id.ICON_HotViewPagerSaving);
/*imageView.setImageResource(images[position]);*/
Glide.with(sContext).load(image_url[position]).into(imageView);
vi.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(sContext, "Slide" + (position+1) + "Clicked", Toast.LENGTH_SHORT).show();
}
});
final Boolean[] boollatestnewssaving = {false};
ICONHotViewPagerSaving.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (boollatestnewssaving[0] == true){
Toast.makeText(v.getContext(), "Turn Off Saved News ", Toast.LENGTH_SHORT).show();
ICONHotViewPagerSaving.setImageResource(R.drawable.saved_off);
boollatestnewssaving[0] = false;
/*updateSavedNewsSaving("update_newssaving", id, false);*/
} else if(boollatestnewssaving[0] == false) {
Toast.makeText(v.getContext(), "Turn On Saved News ", Toast.LENGTH_SHORT).show();
ICONHotViewPagerSaving.setImageResource(R.drawable.saved_on);
boollatestnewssaving[0] = true;
/*updateSavedNewsSaving("update_newssaving", id, true);*/
}
}
});
ViewPager vp = (ViewPager) container;
vp.addView(vi, 0);
return vi;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
ViewPager vp = (ViewPager) container;
View view = (View) object;
vp.removeView(view);
}
}
And this is my MainActivity.java
//ViewPager
public class ViewPagerTask extends TimerTask {
#Override
public void run() {
Activity activity = getActivity();
if (activity != null) {
activity.runOnUiThread(new Runnable() {
#Override
public void run() {
if(viewPager.getCurrentItem() < viewPager.getAdapter().getCount()-1){
viewPager.setCurrentItem(viewPager.getCurrentItem()+1);
} else {
viewPager.setCurrentItem(0);
}
}
});
}
}
}
I am not sure how to add the URLimage to AdapterViewPager from MainActivity in AndroidX? How do I solve this problem? Thanks you in advance.
//UPDATED//
AdapterViewPagerHot adapterViewPagerHotX = new AdapterViewPagerHot(getActivity());
adapterViewPagerHotX.setUrls(new String[]{"https://i.chzbgr.com/full/8803531264/hD42E57C6/"});
AdapterViewPager.java
public class AdapterViewPagerHot extends PagerAdapter {
private Context mContext;
private LayoutInflater layoutInflater;
/*private Integer[] images = {R.drawable.cat_mermaid_cartoon_grumpy_cat_94004_1280x720,R.drawable.catnrobot,R.drawable.kleptocats,R.drawable.magiccat,R.drawable.flyingcat};*/
public String image_url[];
public AdapterViewPagerHot(Context context) {
this.mContext = context;
}
public void setUrls(String[] list){
this.image_url = list;
}
#Override
public int getCount() {
return image_url.length;
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == object;
}
public View vi;
#Override
public Object instantiateItem(ViewGroup container, final int position) {
layoutInflater = (LayoutInflater) this.mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
vi = layoutInflater.inflate(R.layout.item_viewpagerdisplay, null);
final Context sContext = mContext;
ImageView imageView = vi.findViewById(R.id.imageView);
final ImageView ICONHotViewPagerSaving = vi.findViewById(R.id.ICON_HotViewPagerSaving);
/*imageView.setImageResource(images[position]);*/
Glide.with(sContext).load(image_url[position]).into(imageView);
vi.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(sContext, "Slide" + (position+1) + "Clicked", Toast.LENGTH_SHORT).show();
}
});
final Boolean[] boollatestnewssaving = {false};
ICONHotViewPagerSaving.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (boollatestnewssaving[0] == true){
Toast.makeText(v.getContext(), "Turn Off Saved News ", Toast.LENGTH_SHORT).show();
ICONHotViewPagerSaving.setImageResource(R.drawable.saved_off);
boollatestnewssaving[0] = false;
/*updateSavedNewsSaving("update_newssaving", id, false);*/
} else if(boollatestnewssaving[0] == false) {
Toast.makeText(v.getContext(), "Turn On Saved News ", Toast.LENGTH_SHORT).show();
ICONHotViewPagerSaving.setImageResource(R.drawable.saved_on);
boollatestnewssaving[0] = true;
/*updateSavedNewsSaving("update_newssaving", id, true);*/
}
}
});
ViewPager vp = (ViewPager) container;
vp.addView(vi, 0);
return vi;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
ViewPager vp = (ViewPager) container;
View view = (View) object;
vp.removeView(view);
}
}
Got an error
java.lang.NullPointerException: Attempt to invoke virtual method 'void com.indofun.android.indojoy.Adapters.Adapter_ViewPagerHot.AdapterViewPagerHot.setUrls(java.lang.String[])' on a null object reference
at com.indofun.android.indojoy.Support.TabHotFragment.onCreateView(TabHotFragment.java:117)
//UPDATED2//
AdapterViewPager.java
public class AdapterViewPagerHot extends PagerAdapter {
private Context mContext;
private LayoutInflater layoutInflater;
/*private Integer[] images = {R.drawable.cat_mermaid_cartoon_grumpy_cat_94004_1280x720,R.drawable.catnrobot,R.drawable.kleptocats,R.drawable.magiccat,R.drawable.flyingcat};*/
public String image_url[] = new String[]{
"https://i.chzbgr.com/full/8803531264/hD42E57C6/"
};
public AdapterViewPagerHot(Context context) {
this.mContext = context;
}
#Override
public int getCount() {
return image_url.length;
}
public void setUrls(String[] list){
this.image_url = list;
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == object;
}
public View vi;
#Override
public Object instantiateItem(ViewGroup container, final int position) {
layoutInflater = (LayoutInflater) this.mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
vi = layoutInflater.inflate(R.layout.item_viewpagerdisplay, null);
final Context sContext = mContext;
ImageView imageView = vi.findViewById(R.id.imageView);
final ImageView ICONHotViewPagerSaving = vi.findViewById(R.id.ICON_HotViewPagerSaving);
/*imageView.setImageResource(images[position]);*/
Glide.with(sContext).load(image_url[position]).into(imageView);
vi.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(sContext, "Slide" + (position+1) + "Clicked", Toast.LENGTH_SHORT).show();
}
});
final Boolean[] boollatestnewssaving = {false};
ICONHotViewPagerSaving.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (boollatestnewssaving[0] == true){
Toast.makeText(v.getContext(), "Turn Off Saved News ", Toast.LENGTH_SHORT).show();
ICONHotViewPagerSaving.setImageResource(R.drawable.saved_off);
boollatestnewssaving[0] = false;
/*updateSavedNewsSaving("update_newssaving", id, false);*/
} else if(boollatestnewssaving[0] == false) {
Toast.makeText(v.getContext(), "Turn On Saved News ", Toast.LENGTH_SHORT).show();
ICONHotViewPagerSaving.setImageResource(R.drawable.saved_on);
boollatestnewssaving[0] = true;
/*updateSavedNewsSaving("update_newssaving", id, true);*/
}
}
});
ViewPager vp = (ViewPager) container;
vp.addView(vi, 0);
return vi;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
ViewPager vp = (ViewPager) container;
View view = (View) object;
vp.removeView(view);
}
}
//TabHotActivity.java
public class TabHotFragment extends Fragment {
//SetupMainActivity
public static MainActivity mainActivity_;
//ADS GOOGLE Initialize Ads Banner
private AdView mAdView;
//AutoSlide
/*FlipperLayout flipper;*/
//ViewPager
ViewPager viewPager;
LinearLayout sliderDotspanel;
private int dotscount;
private ImageView[] dots;
AdapterViewPagerHot adapterViewPagerHot;
//1
ArrayList<ModelSectionHotTrendingNews> modelSectionHotTrendingNews = new ArrayList<ModelSectionHotTrendingNews>();
AdapterSectionHotTrendingNews adapterSectionHotTrendingNews;
//2
ArrayList<ModelSectionHotLatestNews> modelSectionHotLatestNews = new ArrayList<ModelSectionHotLatestNews>();
AdapterSectionHotLatestNews adapterSectionHotLatestNews;
//3
ArrayList<ModelSectionHotFollowing> modelSectionHotFollowings = new ArrayList<ModelSectionHotFollowing>();
AdapterSectionHotFollowing adapterSectionHotFollowing;
//ModelData
List<ModelSingleHotTrendingNews> modelSingleHotTrendingNews;
List<ModelSingleHotLatestNews> modelSingleHotLatestNews;
List<ModelSingleHotFollowing> modelSingleHotFollowings;
//EVENT BUS
#Subscribe(threadMode = ThreadMode.MAIN)
public void onMessageEvent(MainActivity.EventStoredHighlight event) {
getHighlightMainActivity(event.SendTotalThread, event.SendDummyID, event.SendDummyTitle, event.SendDummyPublishTime, event.SendDummyImageOri, event.SendDummyShortDescription);
}
#Subscribe(threadMode = ThreadMode.MAIN)
public void onMessageEvent(MainActivity.EventStoredTrending event) {
getTrendingMainActivity(event.SendTotalThread, event.SendDummyID, event.SendDummyTitle, event.SendDummyPublishTime, event.SendDummyImageOri, event.SendDummyShortDescription);
}
#Subscribe(threadMode = ThreadMode.MAIN)
public void onMessageEvent(MainActivity.EventStoredLatest event) {
getLatestMainActivity(event.SendTotalThread, event.SendDummyID, event.SendDummyTitle, event.SendDummyPublishTime, event.SendDummyImageOri, event.SendDummyShortDescription);
}
public void getHighlightMainActivity(int ReceivedTotalThread, int ReceivedDummyID, String ReceivedDummyTitle, String ReceivedDummyPublishTime, String ReceivedDummyImageOri, String ReceivedDummyShortDescription){
Toast.makeText(getActivity(), "IniHighlightXTotalThread="+ReceivedTotalThread+", DummyID="+ReceivedDummyID+", DummyTitle="+ReceivedDummyTitle+", DummyPublishTime="+ReceivedDummyPublishTime+", DummyImageOri="+ReceivedDummyImageOri+", DummyShortDescription"+ReceivedDummyShortDescription, Toast.LENGTH_LONG).show();
AdapterViewPagerHot adapterViewPagerHot = new AdapterViewPagerHot(getActivity());
}
public void getTrendingMainActivity(int ReceivedTotalThread, int ReceivedDummyID, String ReceivedDummyTitle, String ReceivedDummyPublishTime, String ReceivedDummyImageOri, String ReceivedDummyShortDescription){
Toast.makeText(getActivity(), "IniTrendingXTotalThread="+ReceivedTotalThread+", DummyID="+ReceivedDummyID+", DummyTitle="+ReceivedDummyTitle+", DummyPublishTime="+ReceivedDummyPublishTime+", DummyImageOri="+ReceivedDummyImageOri+", DummyShortDescription"+ReceivedDummyShortDescription, Toast.LENGTH_LONG).show();
AdapterViewPagerHot adapterViewPagerHot = new AdapterViewPagerHot(getActivity());
}
public void getLatestMainActivity(int ReceivedTotalThread, int ReceivedDummyID, String ReceivedDummyTitle, String ReceivedDummyPublishTime, String ReceivedDummyImageOri, String ReceivedDummyShortDescription){
Toast.makeText(getActivity(), "IniLatestXTotalThread="+ReceivedTotalThread+", DummyID="+ReceivedDummyID+", DummyTitle="+ReceivedDummyTitle+", DummyPublishTime="+ReceivedDummyPublishTime+", DummyImageOri="+ReceivedDummyImageOri+", DummyShortDescription"+ReceivedDummyShortDescription, Toast.LENGTH_LONG).show();
AdapterViewPagerHot adapterViewPagerHot = new AdapterViewPagerHot(getActivity());
}
View v;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
v = inflater.inflate(R.layout.fragment_tabhot, container, false);
//Clear Model that Created before When Fragment Opened Again
modelSectionHotLatestNews.clear();
modelSectionHotTrendingNews.clear();
modelSectionHotFollowings.clear();
/*setContentView(R.layout.activity_main);*/
String[] strArray = new String[]{"https://scx1.b-cdn.net/csz/news/800/2019/1-nasastessmis.jpg"};
adapterViewPagerHot.setUrls(strArray);
/*//AA
//Autoslide
flipper=v.findViewById(R.id.flipper);
setLayout();*/
//ViewPager
viewPager = (ViewPager) v.findViewById(R.id.viewPager);
sliderDotspanel = (LinearLayout) v.findViewById(R.id.SliderDots);
adapterViewPagerHot = new AdapterViewPagerHot(getActivity());
viewPager.setAdapter(adapterViewPagerHot);
dotscount = adapterViewPagerHot.getCount();
dots = new ImageView[dotscount];
for(int i = 0; i < dotscount; i++){
dots[i] = new ImageView(getActivity());
dots[i].setImageDrawable(ContextCompat.getDrawable(getActivity(), R.drawable.nonactive_dot));
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
params.setMargins(8, 0, 8, 0);
sliderDotspanel.addView(dots[i], params);
}
dots[0].setImageDrawable(ContextCompat.getDrawable(getActivity(), R.drawable.active_dot));
viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
for(int i = 0; i< dotscount; i++){
dots[i].setImageResource(R.drawable.nonactive_dot);
}
dots[position].setImageResource(R.drawable.active_dot);
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
Timer timer = new Timer();
//This is going to start after 2 second and will repeat on every 8 seconds time interval.
timer.scheduleAtFixedRate(new ViewPagerTask(), 5000, 8000);
//1
createDummyData1();
RecyclerView RecyclerViewSingleHotTrendingNews = v.findViewById(R.id.RecyclerView_Single_HotTrendingNews);
RecyclerViewSingleHotTrendingNews.setHasFixedSize(true);
adapterSectionHotTrendingNews = new AdapterSectionHotTrendingNews(getActivity(), modelSectionHotTrendingNews);
RecyclerViewSingleHotTrendingNews.setLayoutManager(new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false));
RecyclerViewSingleHotTrendingNews.setAdapter(adapterSectionHotTrendingNews);
//Optimized
RecyclerViewSingleHotTrendingNews.setHasFixedSize(true);
RecyclerViewSingleHotTrendingNews.setItemViewCacheSize(20);
//2
createDummyData2();
RecyclerView RecyclerViewSingleHotLatestNews = v.findViewById(R.id.RecyclerView_Single_HotLatestNews);
RecyclerViewSingleHotLatestNews.setHasFixedSize(true);
adapterSectionHotLatestNews = new AdapterSectionHotLatestNews(getActivity(), modelSectionHotLatestNews);
RecyclerViewSingleHotLatestNews.setLayoutManager(new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false));
RecyclerViewSingleHotLatestNews.setAdapter(adapterSectionHotLatestNews);
//Optimized
RecyclerViewSingleHotLatestNews.setHasFixedSize(true);
RecyclerViewSingleHotLatestNews.setItemViewCacheSize(20);
//3
createDummyData3();
RecyclerView RecyclerViewSingleHotFollowing = v.findViewById(R.id.RecyclerView_Single_HotFollowing);
RecyclerViewSingleHotFollowing.setHasFixedSize(true);
adapterSectionHotFollowing = new AdapterSectionHotFollowing(getActivity(), modelSectionHotFollowings);
RecyclerViewSingleHotFollowing.setLayoutManager(new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false));
RecyclerViewSingleHotFollowing.setAdapter(adapterSectionHotFollowing);
//Optimized
RecyclerViewSingleHotFollowing.setHasFixedSize(true);
RecyclerViewSingleHotFollowing.setItemViewCacheSize(20);
String y = getString(R.string.AdmobID_Core);
//ADS GOOGLE Kode Inti
MobileAds.initialize(getActivity(), getString(R.string.AdmobID_Core));
mAdView = v.findViewById(R.id.adView);
AdRequest adRequest = new AdRequest.Builder().build();
/*AdRequest adRequestBanner = new AdRequest.Builder()
.addTestDevice("2019091717123202457")
.build();*/
mAdView.loadAd(adRequest);
mAdView.setAdListener(new AdListener() {
#Override
public void onAdLoaded() {
Toast.makeText(getActivity(),"RKAd Loaded",Toast.LENGTH_SHORT).show();
// Code to be executed when an ad finishes loading.
}
#Override
public void onAdFailedToLoad(int errorCode) {
Toast.makeText(getActivity(),"Ad Failed to load / Doesn't get Ads Right Now",Toast.LENGTH_SHORT).show();
// Code to be executed when an ad request fails.
}
#Override
public void onAdOpened() {
Toast.makeText(getActivity(),"Ad Opened",Toast.LENGTH_SHORT).show();
// Code to be executed when an ad opens an overlay that
// covers the screen.
}
#Override
public void onAdLeftApplication() {
Toast.makeText(getActivity(),"Ad Left Application",Toast.LENGTH_SHORT).show();
// Code to be executed when the user has left the app.
}
#Override
public void onAdClosed() {
Toast.makeText(getActivity(),"RKAd Closed",Toast.LENGTH_SHORT).show();
// Code to be executed when when the user is about to return
// to the app after tapping on an ad.
}
});
//INI COBA HIT HIGHLIGHT
//SetDataProfile
Button BTNHighlight;
BTNHighlight = v.findViewById(R.id.BTN_Highlight);
BTNHighlight.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (mainActivity_ != null) {
mainActivity_.rncryptorALLDEWA("Highlight");
}
}
});
//INI COBA HIT TRENDING
//SetDataProfile
Button BTNTrending;
BTNTrending = v.findViewById(R.id.BTN_Trending);
BTNTrending.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (mainActivity_ != null) {
mainActivity_.rncryptorALLDEWA("Trending");
}
}
});
//INI COBA HIT LATEST
//SetDataProfile
Button BTNLatest;
BTNLatest = v.findViewById(R.id.BTN_Latest);
BTNLatest.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (mainActivity_ != null) {
mainActivity_.rncryptorALLDEWA("Latest");
}
}
});
/* ViewPager vp = v.findViewById(R.id.ViewPager);
vp.addView(vi, 0);
final AdapterViewPagerHot adapterViewPagerHot = new AdapterViewPagerHot(getActivity());
adapterViewPagerHot.vi.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(getActivity(), "Slide" + (adapterViewPagerHot.getCount()+1) + "Clicked", Toast.LENGTH_SHORT).show();
}
});*/
return v;
}
/*//Autoslide
private void setLayout(){
String url[] = new String[]{
"https://i.chzbgr.com/full/8803531264/hD42E57C6/",
"https://i.pinimg.com/originals/d2/fc/5a/d2fc5ab22b9b9d13320b3a8be48625ad.jpg",
"https://i.ytimg.com/vi/5rOtNmdKgsE/maxresdefault.jpg"
};
for(int i=0; i<url.length; i++){
FlipperView view = new FlipperView(getActivity().getBaseContext());
view.setImageUrl(url[i])
.setDescription("Gambar"+ (i+1));
flipper.addFlipperView(view);
view.setOnFlipperClickListener(new FlipperView.OnFlipperClickListener() {
#Override
public void onFlipperClick(FlipperView flipperView) {
Toast.makeText(getActivity(), ""+(flipper.getCurrentPagePosition()+1), Toast.LENGTH_SHORT).show();
}
});
}
}*/
//ViewPager
public class ViewPagerTask extends TimerTask {
#Override
public void run() {
Activity activity = getActivity();
if (activity != null) {
activity.runOnUiThread(new Runnable() {
#Override
public void run() {
if(viewPager.getCurrentItem() < viewPager.getAdapter().getCount()-1){
viewPager.setCurrentItem(viewPager.getCurrentItem()+1);
} else {
viewPager.setCurrentItem(0);
}
}
});
}
}
}
/*public void createDummyData() {
for (int i = 1; i <= 5; i++) {
SectionDataModel dm = new SectionDataModel();
dm.setHeaderTitle("Section " + i);
ArrayList<SingleItemModel> singleItem = new ArrayList<SingleItemModel>();
for (int j = 0; j <= 7; j++) {
singleItem.add(new SingleItemModel("Item " + j, "URL " + j));
}
dm.setAllItemsInSection(singleItem);
allSampleData.add(dm);
}
}*/
public void createDummyData1() {
ModelSectionHotTrendingNews modelSectionHotTrendingNewsX = new ModelSectionHotTrendingNews();
modelSectionHotTrendingNewsX.setHeaderTitle("TRENDING NEWS");
ArrayList<ModelSingleHotTrendingNews> modelSingleHotTrendingNews = new ArrayList<ModelSingleHotTrendingNews>();
modelSingleHotTrendingNews.add(new ModelSingleHotTrendingNews(1, "20 Mei 2019", "Citing personal differences with his human co-hosts, Watson announced it would be leaving the show last Friday.", R.drawable.magiccat, false, "x53535", "No Error"));
modelSingleHotTrendingNews.add(new ModelSingleHotTrendingNews(2, "21 Mei 2019", "They developed superpowers after years of drinking from a lead-poisoned water supply. But just having incredible abilities doesn't make them superheroes. Not yet.", R.drawable.cat_mermaid_cartoon_grumpy_cat_94004_1280x720, false, "x53535", "No Error"));
modelSingleHotTrendingNews.add(new ModelSingleHotTrendingNews(3, "22 Mei 2019", "Facing increased competition from niche restaurants targeting millennials, the Echo Park Chipotle announced today it would become the nation’s first “Rat Cafe,”", R.drawable.kleptocats, false, "x53535", "No Error"));
modelSingleHotTrendingNews.add(new ModelSingleHotTrendingNews(4, "23 Mei 2019", "The world rejoiced today as The Apprentice's Donald J. Trump brokered a deal with all nations that would create everlasting peace and prospetiy", R.drawable.catnrobot, false, "x53535", "No Error"));
modelSingleHotTrendingNews.add(new ModelSingleHotTrendingNews(5, "24 Mei 2019", "Portsmouth, Australia. Alcohol Quality Inspectorate (AQI) was alarmed after Harry Taylor (23), reported a reportedly poisoned alcohol batch", R.drawable.flyingcat, false, "x53535", "No Error"));
modelSingleHotTrendingNews.add(new ModelSingleHotTrendingNews(6, "25 Mei 2019", "A popular local beer produce was almost forced to stop bottling beer in their branch in Portsmouth", R.drawable.bubblesthecat, false, "x53535", "No Error"));
modelSingleHotTrendingNews.add(new ModelSingleHotTrendingNews(7, "26 Mei 2019", "The man went to a house party with his friends and did not waive from drinking alcohol. After drinking one beer", R.drawable.catnrobot, false, "x53535", "No Error"));
modelSectionHotTrendingNewsX.setAllItemsInSection(modelSingleHotTrendingNews);
modelSectionHotTrendingNews.add(modelSectionHotTrendingNewsX);
}
modelSectionHotLatestNewsX.setAllItemsInSection(modelSingleHotLatestNews);
modelSectionHotLatestNews.add(modelSectionHotLatestNewsX);
}
//EVENTBUS
#Override
public void onStart() {
super.onStart();
EventBus.getDefault().register(this);
}
#Override
public void onStop() {
EventBus.getDefault().unregister(this);
super.onStop();
}
}
Error
java.lang.NullPointerException: Attempt to invoke virtual method 'void com.indofun.android.indojoy.Adapters.Adapter_ViewPagerHot.AdapterViewPagerHot.setUrls(java.lang.String[])' on a null object reference
at com.indofun.android.indojoy.Support.TabHotFragment.onCreateView(TabHotFragment.java:131)
at androidx.fragment.app.Fragment.performCreateView(Fragment.java:2600)
at androidx.fragment.app.FragmentManagerImpl.moveToState(FragmentManagerImpl.java:881)
at

you can create a method for that in your adapter
public class AdapterViewPagerHot extends PagerAdapter {
private String [] urlList;
...
public void setUrls(String[] list){
this.urlList = list;
}
...
}
you can call this method on your adapter instance in your activity:
viewPager.setUrls(/*your URL list*/);

I put setImageUrl inside Adapter because it will be executed first if I try to make another function it will crash
public AdapterViewPagerHot(Context context, String[] list) {
this.mContext = context;
this.image_url = list;
}

Related

How can make other button disable when one is clicked android studio?

I have a scenario where I have 5 ImageView and when one ImageView is clicked i want to set other 4 ImageView as Disabled. Please help to get logic for that.
My Logic for this : when 1 image is click set other 4 imageView as disable but imageView.setClickable(false) is not working.
This Attached Image is a dialog box that appears when users wants to edit something from recycler view. Recycler view contains data like : "Amount", "Item name", "Price", "Expense Type" and expense type image is set to On corresponding to "Expense Type".
I am stuck in this moment. Please help me out to solve this.
I have attached my scenario images Please check it out.
Here's my code for this
public class MyAdapter extends FirebaseRecyclerAdapter<ExpenseModel, MyAdapter.MyViewHolder> {
Context context;
private int lastPosition = -1;
private String whichCategorySelected = "";
private int calImgClick = 0;
private int groceryClick = 0;
private int bikeClick = 0;
private int rentClick = 0;
private int foodsClick = 0;
private int beerClick = 0;
public MyAdapter(#NonNull FirebaseRecyclerOptions<ExpenseModel> options, Context context) {
super(options);
this.context = context;
}
#SuppressLint("SetTextI18n")
#Override
protected void onBindViewHolder(#NonNull MyViewHolder holder, #SuppressLint("RecyclerView") int position, #NonNull ExpenseModel model) {
holder.expenseItem.setText(model.getDescription());
holder.expenseAmount.setText("Rs. " + model.getAmount());
holder.expenseDate.setText(model.getTime());
String expType = model.getExType();
switch (expType) {
case "Beer":
holder.category.setBackgroundResource(R.drawable.beer);
break;
case "Grocery":
holder.category.setBackgroundResource(R.drawable.grocery);
break;
case "Bike":
holder.category.setBackgroundResource(R.drawable.bike);
break;
case "Rent":
holder.category.setBackgroundResource(R.drawable.rent);
break;
default:
holder.category.setBackgroundResource(R.drawable.fd);
break;
}
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
showPopMenuOnItemClicked(view, holder.getLayoutPosition(), model.getDescription(), model.getAmount(), model.getTime(), model.getExType());
}
});
}
private void showPopMenuOnItemClicked(View v, int pos, String getExpTitle, String getExpAmt, String getDate, String whichCatSelected) {
PopupMenu popupMenu = new PopupMenu(context, v);
popupMenu.getMenu().add("Edit");
popupMenu.getMenu().add("Delete");
popupMenu.getMenu().add("Delete All");
popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem menuItem) {
if (menuItem.getTitle().equals("Edit")) {
showUpdateDialogBox(v, getExpTitle, getExpAmt, getDate, whichCatSelected);
} else if (menuItem.getTitle().equals("Delete")) {
FirebaseReference.expenseReference(context)
.child(String.valueOf(getRef(pos).getKey()))
.removeValue()
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
Toast.makeText(context, "Deleted", Toast.LENGTH_SHORT).show();
}
}
});
} else {
Toast.makeText(context.getApplicationContext(), "Delete everything", Toast.LENGTH_SHORT).show();
}
return true;
}
});
popupMenu.show();
}
#SuppressLint("ClickableViewAccessibility")
private void showUpdateDialogBox(View v, String getExpTitle, String getExpAmt, String getDate, String whichCatSelected) {
DialogPlus dialog = DialogPlus.newDialog(context)
.setContentHolder(new ViewHolder(R.layout.update_expense_layout))
.setExpanded(false)
.setOnDismissListener(new OnDismissListener() {
#Override
public void onDismiss(DialogPlus dialog) {
onDismissSetClickCountToZero();
Utility.hideKeyboard(context, v);
}
})
.create();
View myView = dialog.getHolderView();
TextView update_expense_date = myView.findViewById(R.id.update_expense_date);
EditText update_expense_title = myView.findViewById(R.id.update_expense_title);
EditText update_expense_amount = myView.findViewById(R.id.update_expense_amount);
ImageView update_calendarImg = myView.findViewById(R.id.update_calendar);
Button update_button = myView.findViewById(R.id.update_btn);
LinearLayout linearLayout = myView.findViewById(R.id.update_linearCalenderLayout);
linearLayout.setVisibility(View.GONE);
CalendarView calendarView = myView.findViewById(R.id.update_calenderView);
LinearLayout categoryLayout = myView.findViewById(R.id.update_categoryIconsLayout);
TextView categoryTextView = myView.findViewById(R.id.update_selectCategory_heading);
update_expense_title.setText(getExpTitle);
update_expense_amount.setText(getExpAmt);
update_expense_date.setText(getDate);
ImageView beer = myView.findViewById(R.id.update_beer);
ImageView bike = myView.findViewById(R.id.update_bike);
ImageView grocery = myView.findViewById(R.id.update_grocery);
ImageView foods = myView.findViewById(R.id.update_foods);
ImageView rent = myView.findViewById(R.id.update_rent);
TextView desc_grocery = myView.findViewById(R.id.update_desc_grocery);
TextView desc_bike = myView.findViewById(R.id.update_desc_bike);
TextView desc_beer = myView.findViewById(R.id.update_desc_beer);
TextView desc_foods = myView.findViewById(R.id.update_desc_foods);
TextView desc_rent = myView.findViewById(R.id.update_desc_rent);
setIconVisible(whichCatSelected, bike, grocery, foods, beer, rent,
desc_bike, desc_grocery, desc_foods, desc_beer, desc_rent);
setWhichCategorySelected(whichCatSelected);
Toast.makeText(context, "Default select = " + getWhichCategorySelected() + " click = " + rentClick, Toast.LENGTH_SHORT).show();
update_calendarImg.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
calImgClick++;
if (calImgClick >= 2) {
linearLayout.setVisibility(View.GONE);
categoryLayout.setVisibility(View.VISIBLE);
categoryTextView.setVisibility(View.VISIBLE);
calImgClick = 0;
} else {
linearLayout.setVisibility(View.VISIBLE);
categoryLayout.setVisibility(View.GONE);
categoryTextView.setVisibility(View.GONE);
}
}
});
rent.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (getWhichCategorySelected().equals("") || getWhichCategorySelected().equals("Rent")){
rentClick ++;
if (rentClick >= 2) {
setWhichCategorySelected("");
rent.setBackgroundResource(R.drawable.rent_off);
desc_rent.setVisibility(View.GONE);
grocery.setClickable(true);
bike.setClickable(true);
foods.setClickable(true);
beer.setClickable(true);
rentClick = 0;
} else {
setWhichCategorySelected("Rent");
rent.setBackgroundResource(R.drawable.rent);
desc_rent.setVisibility(View.VISIBLE);
grocery.setClickable(false);
bike.setClickable(false);
foods.setClickable(false);
beer.setClickable(false);
}
}else {
Toast.makeText(context, "Category is selected " + getWhichCategorySelected(), Toast.LENGTH_SHORT).show();
}
Toast.makeText(context, "whichCategorySelected = " + getWhichCategorySelected(), Toast.LENGTH_SHORT).show();
}
});
grocery.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (getWhichCategorySelected().equals("") || getWhichCategorySelected().equals("Grocery")){
groceryClick ++;
if (groceryClick >= 2) {
setWhichCategorySelected("");
grocery.setBackgroundResource(R.drawable.grocery_off);
desc_grocery.setVisibility(View.GONE);
rent.setClickable(true);
bike.setClickable(true);
foods.setClickable(true);
beer.setClickable(true);
rentClick = 0;
} else {
setWhichCategorySelected("Grocery");
grocery.setBackgroundResource(R.drawable.grocery);
desc_grocery.setVisibility(View.VISIBLE);
rent.setClickable(false);
bike.setClickable(false);
foods.setClickable(false);
beer.setClickable(false);
}
}else {
Toast.makeText(context, "Category is selected " + getWhichCategorySelected(), Toast.LENGTH_SHORT).show();
}
Toast.makeText(context, "whichCategorySelected = " + getWhichCategorySelected(), Toast.LENGTH_SHORT).show();
}
});
update_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
updateChildren(update_expense_amount, update_expense_title, update_expense_date, whichCatSelected);
}
});
dialog.show();
}
#NonNull
#Override
public MyViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_view, parent, false);
return new MyViewHolder(v);
}
public static class MyViewHolder extends RecyclerView.ViewHolder {
TextView expenseItem, expenseAmount, expenseDate;
ImageView category;
public MyViewHolder(#NonNull View itemView) {
super(itemView);
expenseItem = itemView.findViewById(R.id.recyclerItemView);
expenseAmount = itemView.findViewById(R.id.recyclerAmountView);
expenseDate = itemView.findViewById(R.id.recyclerDateView);
category = itemView.findViewById(R.id.recyclerCategory);
}
}

get context after returning from adapter to fragment

I am using contextual action bar in my fragment("UnitsFragment.java") to delete and edit items of recyclerview. But when I come back from recyclerview adapter class("UnitsRv.java"). The context seems to be null. I tried returning context from adapter and it worked for function "prepareSelection". However for "onActionItemClicked" under ActionMode.callback, I need to get context so that I can use alertdialog for editing the items.
The "requireContext()" throws this error: Fragment UnitsFragment{e3a36c8 (b4957397-055a-4b1c-8af2-fee89a3e9b35)} not attached to a context.
Here are my codes.
UnitsFragment.java
public class UnitsFragment extends Fragment {
private static final String TAG = "UnitsFragment";
private RecyclerView recyclerView;
private RecyclerView.Adapter mAdapter;
private RecyclerView.LayoutManager layoutManager;
ArrayList<UnitsList> unitsLists = new ArrayList<>();
Activity mcontext = getActivity();
Context dcontext;
ActionMode actionMode;
public static ArrayList<UnitsList> selectionList = new ArrayList<>();
public static boolean isInActionMode = false;
List<String> list = DatabaseClient.getInstance(getContext())
.getUserDatabase()
.getUnitDao().findUnitNameList();
public UnitsFragment() {
}
private ActionMode.Callback actionModeCallback = new ActionMode.Callback() {
#Override
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
mode.getMenuInflater().inflate(R.menu.menu_item_action, menu);
return true;
}
#Override
public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
return false;
}
#Override
public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_item_edit:
if (selectionList.size() == 1) {
final EditText editText = new EditText(requireContext());
new AlertDialog.Builder(requireContext())
.setTitle("Rename unit name").setView(editText)
.setPositiveButton("Rename", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
UnitsList unitsList = selectionList.get(0);
unitsList.setUnit_name(editText.getText().toString().trim());
isInActionMode = false;
((UnitsRv) mAdapter).changeDataItem(getCheckedLastPosition(), unitsList);
actionMode.finish();
selectionList.clear();
}
})
.create()
.show();
Toast.makeText(getContext(), "Edit", Toast.LENGTH_SHORT).show();
mode.finish();
return true;
}
case R.id.menu_item_delete:
isInActionMode = false;
((UnitsRv) mAdapter).removeData(selectionList);
Toast.makeText(getContext(), "Delete", Toast.LENGTH_SHORT).show();
actionMode.finish();
selectionList.clear();
return true;
default:
return false;
}
}
#Override
public void onDestroyActionMode(ActionMode mode) {
actionMode = null;
}
};
private int getCheckedLastPosition() {
ArrayList<UnitsList> dataSet = UnitsRv.getDataSet();
for (int i = 0; i < dataSet.size(); i++) {
if (dataSet.get(i).equals(selectionList.get(0))) {
return i;
}
}
return 0;
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_units, container, false);
setHasOptionsMenu(true);
dcontext = rootView.getContext();
Log.d(TAG, "onCreateView1: " + dcontext);
recyclerView = rootView.findViewById(R.id.rv_units);
recyclerView.setHasFixedSize(true);
recyclerView.addItemDecoration(new DividerItemDecoration(getContext(),
DividerItemDecoration.HORIZONTAL));
recyclerView.addItemDecoration(new DividerItemDecoration(getContext(),
DividerItemDecoration.VERTICAL));
layoutManager = new GridLayoutManager(getContext(), 2);
recyclerView.setLayoutManager(layoutManager);
for (String string : list) {
unitsLists.add(new UnitsList(string));
}
Log.d(TAG, "onCreateView: " + getContext());
mAdapter = new UnitsRv(mcontext,unitsLists);
recyclerView.setAdapter(mAdapter);
return rootView;
}
#Override
public void onCreateOptionsMenu(#NonNull Menu menu, #NonNull MenuInflater inflater) {
inflater.inflate(R.menu.add, menu);
super.onCreateOptionsMenu(menu, inflater);
}
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_item_new:
final View customLayout = getLayoutInflater().inflate(R.layout.add_unit_dialog, null);
final EditText edt_unit_name = customLayout.findViewById(R.id.edt_new_unit_name);
final AlertDialog dialog = new AlertDialog.Builder(getContext())
.setView(customLayout)
.setTitle("Unit name")
.setPositiveButton(android.R.string.ok, null) //Set to null. We override the onclick
.setNegativeButton(android.R.string.cancel, null)
.create();
dialog.setOnShowListener(new DialogInterface.OnShowListener() {
#Override
public void onShow(DialogInterface dialogInterface) {
Button ok_btn = dialog.getButton(AlertDialog.BUTTON_POSITIVE);
Button cancel_btn = dialog.getButton(AlertDialog.BUTTON_NEGATIVE);
ok_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String unit_name = edt_unit_name.getText().toString().trim();
if (!TextUtils.isEmpty(unit_name)) {
String old_unit_name = DatabaseClient.getInstance(getContext())
.getUserDatabase()
.getUnitDao()
.findByUnitName(unit_name);
if (old_unit_name == null) {
DatabaseClient.getInstance(getContext())
.getUserDatabase()
.getUnitDao()
.insertUnits(new UnitsList(unit_name));
unitsLists.add(new UnitsList(unit_name));
dialog.dismiss();
} else {
edt_unit_name.setError("Unit already exists");
}
} else {
edt_unit_name.setError("Can't be empty");
}
}
});
cancel_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
dialog.dismiss();
}
});
}
});
dialog.show();
return true;
}
return super.onOptionsItemSelected(item);
}
public void prepareSelection(Context context,int position) {
if(actionMode == null) {
isInActionMode = true;
for (String string : list) {
unitsLists.add(new UnitsList(string));
}
mAdapter = new UnitsRv(context, unitsLists);
Log.d(TAG, "prepareSelection: " + mAdapter);
Log.d(TAG, "prepareSelection1: " + dcontext);
mcontext = (Activity)context;
actionMode = mcontext.startActionMode(actionModeCallback);
mAdapter.notifyDataSetChanged();
if (!selectionList.contains(unitsLists.get(position))) {
selectionList.add(unitsLists.get(position));
}
updateViewCounter();
}
}
private void updateViewCounter() {
int counter = selectionList.size();
if (counter == 1) {
actionMode.setTitle(counter + "item selected");
} else {
actionMode.setTitle(counter + "items selected");
}
}
}
This is my Adapter class.
UnitsRv.java
public class UnitsRv extends RecyclerView.Adapter<UnitsRv.ViewHolder> {
private static final String TAG = "UnitsRv";
private static ArrayList<UnitsList> munitsLists = new ArrayList<>();
UnitsFragment unitsFragment = new UnitsFragment();
Context mcontext;
public UnitsRv(Context context,ArrayList<UnitsList> unitsLists) {
mcontext = context;
munitsLists = unitsLists;
}
class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener, View.OnLongClickListener {
TextView unit_name;
public ViewHolder(View v) {
super(v);
unit_name = v.findViewById(R.id.unit_name);
v.setOnLongClickListener(this);
}
#Override
public void onClick(View view) {
if (UnitsFragment.isInActionMode){
unitsFragment.prepareSelection(mcontext,getAdapterPosition());
notifyItemChanged(getAdapterPosition());
}
}
#Override
public boolean onLongClick(View view) {
Log.d(TAG, "onLongClick: " + getAdapterPosition());
unitsFragment.prepareSelection(view.getContext(),getAdapterPosition());
return true;
}
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.units_item, parent, false);
return new ViewHolder(itemView);
}
#Override
public void onBindViewHolder(#NonNull final ViewHolder holder, final int position) {
holder.unit_name.setText(munitsLists.get(position).getUnit_name());
if (UnitsFragment.isInActionMode){
if (UnitsFragment.selectionList.contains(munitsLists.get(position))){
holder.itemView.setBackgroundResource(R.color.colorSelected);
}
}
}
#Override
public int getItemCount() {
return munitsLists.size();
}
public static ArrayList<UnitsList> getDataSet() {
return munitsLists;
}
public void changeDataItem(int position, UnitsList unitsList) {
munitsLists.set(position, unitsList);
notifyDataSetChanged();
}
public void removeData(ArrayList<UnitsList> list) {
for (UnitsList unitsList : list) {
munitsLists.remove(unitsList);
}
notifyDataSetChanged();
}
}
First, you should not create instance of your UnitsFragment inside your adapter.
You can use EventBus to communicate between Activities, Fragments, Adapters, etc.
Or You can do your task using interface. like below.
Create an interface like this
public interface AdapterCallback {
void prepareSelection(Context context,int position);
}
In your UnitsFragment implement the above interface. like the following
public class UnitsFragment extends Fragment implements AdapterCallback{
// your other codes
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_units, container, false);
setHasOptionsMenu(true);
// .... your other codes
Log.d(TAG, "onCreateView: " + getContext());
// modify below line like this
mAdapter = new UnitsRv(mcontext, unitsLists, this); // here you have to pass an extra parameter that will implement your callback method from adapter.
recyclerView.setAdapter(mAdapter);
return rootView;
}
// ... you other codes
#Override
public void prepareSelection(Context context,int position) {
if(actionMode == null) {
isInActionMode = true;
for (String string : list) {
unitsLists.add(new UnitsList(string));
}
mAdapter = new UnitsRv(context, unitsLists,this); // add this as parameter.
Log.d(TAG, "prepareSelection: " + mAdapter);
Log.d(TAG, "prepareSelection1: " + dcontext);
mcontext = (Activity)context;
actionMode = mcontext.startActionMode(actionModeCallback);
mAdapter.notifyDataSetChanged();
if (!selectionList.contains(unitsLists.get(position))) {
selectionList.add(unitsLists.get(position));
}
updateViewCounter();
}
}
// other codes
}
Now, inside your Adapter you need to add an extra argument in constructor of UnitsRv and call your interface method from adapter ussing mAdapterCallback.
public class UnitsRv extends RecyclerView.Adapter<UnitsRv.ViewHolder> {
private static final String TAG = "UnitsRv";
private static ArrayList<UnitsList> munitsLists = new ArrayList<>();
UnitsFragment unitsFragment = new UnitsFragment(); // remove this line
private AdapterCallback mAdapterCallback; // add this line
Context mcontext;
public UnitsRv(Context context,ArrayList<UnitsList> unitsLists, AdapterCallback callback) {
mcontext = context;
munitsLists = unitsLists;
this.mAdapterCallback = callback; // add this line
}
class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener, View.OnLongClickListener {
TextView unit_name;
public ViewHolder(View v) {
super(v);
unit_name = v.findViewById(R.id.unit_name);
v.setOnLongClickListener(this);
}
#Override
public void onClick(View view) {
if (UnitsFragment.isInActionMode){
mAdapterCallback.prepareSelection(mcontext,getAdapterPosition()); // modify this line
notifyItemChanged(getAdapterPosition());
}
}
#Override
public boolean onLongClick(View view) {
Log.d(TAG, "onLongClick: " + getAdapterPosition());
mAdapterCallback.prepareSelection(view.getContext(),getAdapterPosition()); // modify this line
return true;
}
}
// your other codes....
}
You should check for your fragment is attached or not with isAdded()
place if(!isAdded()) return in your onActionItemClicked. and replace requireContext() with getContext() because requireContext() always throws IllegalStateException if fragment is not attached.
override onAttach method to save context in your fragment.
#Override
public void onAttach(Context context) {
super.onAttach(context);
this.context= context;
}
Hope this helps.

How to make "See All Item" button to pass data from RecyclerView to Another RecyclerView fragment - AndroidX

Question
I want to make the "See All Item" button to pass data from RecyclerView to Another RecyclerView fragment
it looks like play store that has the "More" button to see all item in another fragment
AdapterSectionHotTrendingNews.java
public class AdapterSectionHotTrendingNews extends RecyclerView.Adapter{
private Context mContext;
private ArrayList<ModelSectionHotTrendingNews> modelSectionHotTrendingNews;
public AdapterSectionHotTrendingNews(Context mContext, ArrayList<ModelSectionHotTrendingNews> modelSectionHotTrendingNews) {
this.mContext = mContext;
this.modelSectionHotTrendingNews = modelSectionHotTrendingNews;
}
#Override
public SectionHotTrendingNewsViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_section_hottrendingnews, null);
return new SectionHotTrendingNewsViewHolder(v);
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
SectionHotTrendingNewsViewHolder sectionHotTrendingNewsViewHolder = (SectionHotTrendingNewsViewHolder) holder;
ModelSectionHotTrendingNews modelSectionHotTrendingNewsX = modelSectionHotTrendingNews.get(position);
//Set
sectionHotTrendingNewsViewHolder.TVSectionTitle.setText(modelSectionHotTrendingNewsX.getHeaderTitle());
ArrayList singleSectionItems = modelSectionHotTrendingNewsX.getAllItemsInSection();
/*AdapterSingleHotLatestNews.RecyclerViewClickListener listenerLatestNews;
listenerLatestNews = new AdapterSingleHotLatestNews.RecyclerViewClickListener() {
#Override
public void onRowHotLatestNewsClick(View view, int position) {
}
#Override
public void onIconHotLatestNewsClick(View view, int position) {
}
};*/
AdapterSingleHotTrendingNews itemListDataAdapter = new AdapterSingleHotTrendingNews(mContext, singleSectionItems);
/*itemRowHolder.recycler_view_list.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
int action = event.getAction();
switch (action) {
case MotionEvent.ACTION_DOWN:
// Disallow ScrollView to intercept touch events.
v.getParent().requestDisallowInterceptTouchEvent(true);
break;
case MotionEvent.ACTION_UP:
//Allow ScrollView to intercept touch events once again.
v.getParent().requestDisallowInterceptTouchEvent(false);
break;
}
// Handle RecyclerView touch events.
v.onTouchEvent(event);
return true;
}
});*/
final String sectionTitle = modelSectionHotTrendingNewsX.getHeaderTitle();
sectionHotTrendingNewsViewHolder.BTNHotTrendingNewsMore.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(v.getContext(), "click event on more, "+sectionTitle, Toast.LENGTH_SHORT).show();
}
});
/*Glide.with(mContext)
.load(feedItem.getImageURL())
.diskCacheStrategy(DiskCacheStrategy.ALL)
.centerCrop()
.error(R.drawable.bg)
.into(feedListRowHolder.thumbView);*/
//SetRecyclerView
sectionHotTrendingNewsViewHolder.RecyclerViewSectionHotTrendingNews.setHasFixedSize(true);
sectionHotTrendingNewsViewHolder.RecyclerViewSectionHotTrendingNews.setLayoutManager(new LinearLayoutManager(mContext, LinearLayoutManager.HORIZONTAL, false));
sectionHotTrendingNewsViewHolder.RecyclerViewSectionHotTrendingNews.setAdapter(itemListDataAdapter);
sectionHotTrendingNewsViewHolder.RecyclerViewSectionHotTrendingNews.setNestedScrollingEnabled(false);
}
#Override
public int getItemCount() {
int itemCount = modelSectionHotTrendingNews.size();
return itemCount;
}
public class SectionHotTrendingNewsViewHolder extends RecyclerView.ViewHolder {
protected TextView TVSectionTitle;
protected ImageView BTNHotTrendingNewsMore;
protected RecyclerView RecyclerViewSectionHotTrendingNews;
public SectionHotTrendingNewsViewHolder(View itemView) {
super(itemView);
TVSectionTitle = (TextView) itemView.findViewById(R.id.TV_SectionTitle);
BTNHotTrendingNewsMore= (ImageView) itemView.findViewById(R.id.BTN_HotTrendingNewsMore);
RecyclerViewSectionHotTrendingNews = (RecyclerView) itemView.findViewById(R.id.RecyclerView_Section_HotTrendingNews);
}
}
}
AdapterSingleHotTrendingNews.java
public class AdapterSingleHotTrendingNews extends RecyclerView.Adapter{
private Context mContext;
private ArrayList<ModelSingleHotTrendingNews> modelSingleHotTrendingNews;
public AdapterSingleHotTrendingNews(Context mContext, ArrayList<ModelSingleHotTrendingNews> modelSingleHotTrendingNews) {
this.mContext = mContext;
this.modelSingleHotTrendingNews = modelSingleHotTrendingNews;
}
//Container
#Override
public SingleHotTrendingNewsViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.item_single_hottrendingnews, null);
return new SingleHotTrendingNewsViewHolder(v);
}
//Fill Container with Model Setter Getter
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, final int position) {
final SingleHotTrendingNewsViewHolder singleHotTrendingNewsViewHolder = (SingleHotTrendingNewsViewHolder) holder;
final ModelSingleHotTrendingNews modelSingleHotTrendingNewsX = modelSingleHotTrendingNews.get(position);
//Set
singleHotTrendingNewsViewHolder.TVGameDate.setText(modelSingleHotTrendingNewsX.getGamedate());
singleHotTrendingNewsViewHolder.TVGameDescription.setText(modelSingleHotTrendingNewsX.getGamedescription());
singleHotTrendingNewsViewHolder.IMGGameImage.setImageResource(modelSingleHotTrendingNewsX.getGameimage());
singleHotTrendingNewsViewHolder.ICONHotTrendingNewsSaving.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final Boolean booltrendingnewssaving = modelSingleHotTrendingNewsX.getTrendingnewssaving();
final int id = modelSingleHotTrendingNewsX.getId();
if (booltrendingnewssaving == true){
Toast.makeText(v.getContext(), "Turn Off Saved News " + id, Toast.LENGTH_SHORT).show();
singleHotTrendingNewsViewHolder.ICONHotTrendingNewsSaving.setImageResource(R.drawable.saved_off);
modelSingleHotTrendingNewsX.setTrendingnewssaving(false);
/*updateSavedNewsSaving("update_newssaving", id, false);*/
} else if(booltrendingnewssaving == false) {
Toast.makeText(v.getContext(), "Turn On Saved News " + id, Toast.LENGTH_SHORT).show();
singleHotTrendingNewsViewHolder.ICONHotTrendingNewsSaving.setImageResource(R.drawable.saved_on);
modelSingleHotTrendingNewsX.setTrendingnewssaving(true);
/*updateSavedNewsSaving("update_newssaving", id, true);*/
}
}
});
/* Glide.with(mContext)
.load(feedItem.getImageURL())
.diskCacheStrategy(DiskCacheStrategy.ALL)
.centerCrop()
.error(R.drawable.bg)
.into(feedListRowHolder.thumbView);*/
singleHotTrendingNewsViewHolder.ROWHotTrendingNewsContainer.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(v.getContext(), modelSingleHotTrendingNews.get(position).getGamedescription(), Toast.LENGTH_SHORT).show();
//Passing Data to GameDescriptionActivity
Intent intent = new Intent(mContext, GameDetailActivity.class);
intent.putExtra("ImagePKG", modelSingleHotTrendingNews.get(position).getGameimage());
intent.putExtra("NamePKG", modelSingleHotTrendingNews.get(position).getGamedate());
intent.putExtra("UrlPKG", modelSingleHotTrendingNews.get(position).getId());
intent.putExtra("DescriptionPKG", modelSingleHotTrendingNews.get(position).getGamedescription());
mContext.startActivity(intent);
}
});
}
#Override
public int getItemCount() {
int itemCount = modelSingleHotTrendingNews.size();
return itemCount;
}
public class SingleHotTrendingNewsViewHolder extends RecyclerView.ViewHolder{
TextView TVGameDate;
TextView TVGameDescription;
ImageView IMGGameImage;
ImageView ICONHotTrendingNewsSaving;
private RelativeLayout ROWHotTrendingNewsContainer;
public SingleHotTrendingNewsViewHolder(View itemView) {
super(itemView);
TVGameDate = itemView.findViewById(R.id.TV_GameDate);
TVGameDescription = itemView.findViewById(R.id.TV_GameDescription);
IMGGameImage = itemView.findViewById(R.id.IMG_GameImage);
ICONHotTrendingNewsSaving = itemView.findViewById(R.id.ICON_HotTrendingNewsSaving);
ROWHotTrendingNewsContainer = itemView.findViewById(R.id.ROW_HotTrendingNewsContainer);
}
}
ModelSectionHotTrendingNews.java
public class ModelSectionHotTrendingNews {
private String headerTitle;
private ArrayList<ModelSingleHotTrendingNews> allItemsInSection;
public ModelSectionHotTrendingNews() {
}
public String getHeaderTitle() {
return headerTitle;
}
public void setHeaderTitle(String headerTitle) {
this.headerTitle = headerTitle;
}
public ArrayList<ModelSingleHotTrendingNews> getAllItemsInSection() {
return allItemsInSection;
}
public void setAllItemsInSection(ArrayList<ModelSingleHotTrendingNews> allItemsInSection) {
this.allItemsInSection = allItemsInSection;
}
}
ModelSingleHotTrendingNews.java
public class ModelSingleHotTrendingNews {
private int id;
private String gamedate;
private String gamedescription;
private int gameimage;
private Boolean trendingnewssaving;
private String value;
private String message;
public ModelSingleHotTrendingNews(int id, String gamedate, String gamedescription, int gameimage, Boolean trendingnewssaving, String value, String message) {
this.id = id;
this.gamedate = gamedate;
this.gamedescription = gamedescription;
this.gameimage = gameimage;
this.trendingnewssaving = trendingnewssaving;
this.value = value;
this.message = message;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getGamedate() {
return gamedate;
}
public void setGamedate(String gamedate) {
this.gamedate = gamedate;
}
public String getGamedescription() {
return gamedescription;
}
public void setGamedescription(String gamedescription) {
this.gamedescription = gamedescription;
}
public int getGameimage() {
return gameimage;
}
public void setGameimage(int gameimage) {
this.gameimage = gameimage;
}
public Boolean getTrendingnewssaving() {
return trendingnewssaving;
}
public void setTrendingnewssaving(Boolean trendingnewssaving) {
this.trendingnewssaving = trendingnewssaving;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
FragmentFunction
public void createDummyData1() {
ModelSectionHotTrendingNews modelSectionHotTrendingNewsX = new ModelSectionHotTrendingNews();
modelSectionHotTrendingNewsX.setHeaderTitle("TRENDING NEWS");
ArrayList<ModelSingleHotTrendingNews> modelSingleHotTrendingNews = new ArrayList<ModelSingleHotTrendingNews>();
modelSingleHotTrendingNews.add(new ModelSingleHotTrendingNews(1, "20 Mei 2019", "sdfjiaOIJdosjfsjdfjsoid", R.drawable.kleptocats, false, "x53535", "No Error"));
modelSingleHotTrendingNews.add(new ModelSingleHotTrendingNews(2, "21 Mei 2019", "sdfjiaOIJdosjfsjdfjsoid", R.drawable.kleptocats, false, "x53535", "No Error"));
modelSingleHotTrendingNews.add(new ModelSingleHotTrendingNews(3, "22 Mei 2019", "sdfjiaOIJdosjfsjdfjsoid", R.drawable.kleptocats, false, "x53535", "No Error"));
modelSingleHotTrendingNews.add(new ModelSingleHotTrendingNews(4, "23 Mei 2019", "sdfjiaOIJdosjfsjdfjsoid", R.drawable.kleptocats, false, "x53535", "No Error"));
modelSingleHotTrendingNews.add(new ModelSingleHotTrendingNews(5, "24 Mei 2019", "sdfjiaOIJdosjfsjdfjsoid", R.drawable.kleptocats, false, "x53535", "No Error"));
modelSingleHotTrendingNews.add(new ModelSingleHotTrendingNews(6, "25 Mei 2019", "sdfjiaOIJdosjfsjdfjsoid", R.drawable.kleptocats, false, "x53535", "No Error"));
modelSingleHotTrendingNews.add(new ModelSingleHotTrendingNews(7, "26 Mei 2019", "sdfjiaOIJdosjfsjdfjsoid", R.drawable.kleptocats, false, "x53535", "No Error"));
modelSectionHotTrendingNewsX.setAllItemsInSection(modelSingleHotTrendingNews);
modelSectionHotTrendingNews.add(modelSectionHotTrendingNewsX);
}
//UPDATED
I Added this on SectionAdapterTabHot.java
I use same model but different RecyclerView and Adapter like: RecyclerViewMoreSection/SingleTabHot and Section/SingleMoreAdapterTabHot.java
final String sectionTitle = modelSectionHotTrendingNewsX.getHeaderTitle();
sectionHotTrendingNewsViewHolder.BTNHotTrendingNewsMore.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(v.getContext(), "click event on more, "+sectionTitle, Toast.LENGTH_SHORT).show();
sectionHotTrendingNewsViewHolder.RecyclerViewMoreSectionHotTrendingNews.setAdapter( new AdapterMoreSingleHotTrendingNews(v.getContext(), modelSectionHotTrendingNews.get(position).getAllItemsInSection()));
Intent intent = new Intent(mContext, TabMoreHotActivity.class);
mContext.startActivity(intent);
}
});
//SectionAdapterViewHolder
public class SectionHotTrendingNewsViewHolder extends RecyclerView.ViewHolder {
protected TextView TVSectionTitle;
protected ImageView BTNHotTrendingNewsMore;
protected RecyclerView RecyclerViewSectionHotTrendingNews;
protected RecyclerView RecyclerViewMoreSectionHotTrendingNews;
public SectionHotTrendingNewsViewHolder(View itemView) {
super(itemView);
TVSectionTitle = (TextView) itemView.findViewById(R.id.TV_SectionTitle);
BTNHotTrendingNewsMore= (ImageView) itemView.findViewById(R.id.BTN_HotTrendingNewsMore);
RecyclerViewSectionHotTrendingNews = (RecyclerView) itemView.findViewById(R.id.RecyclerView_Section_HotTrendingNews);
RecyclerViewMoreSectionHotTrendingNews = (RecyclerView) itemView.findViewById(R.id.RecyclerViewMore_Section_HotTrendingNews);
}
}
//This is the problem I want to Access RecyclerViewMoreHotTrendingNews in itemmore_hot but it doesn't founded in item_hot
#Override
public SectionHotTrendingNewsViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_section_hottrendingnews, null);
return new SectionHotTrendingNewsViewHolder(v);
}
//This is TabMoreHotActivity.java
public class TabMoreHotActivity extends AppCompatActivity {
//1
ArrayList<ModelSectionHotTrendingNews> modelSectionHotTrendingNews = new ArrayList<ModelSectionHotTrendingNews>();
AdapterMoreSectionHotTrendingNews adapterMoreSectionHotTrendingNews;
//ModelData
List<ModelSingleHotTrendingNews> modelSingleHotTrendingNews;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragmentmore_tabhot);
//1
RecyclerView RecyclerViewMoreSingleHotTrendingNews = findViewById(R.id.RecyclerViewMore_Single_HotTrendingNews);
RecyclerViewMoreSingleHotTrendingNews.setHasFixedSize(true);
adapterMoreSectionHotTrendingNews = new AdapterMoreSectionHotTrendingNews(this, modelSectionHotTrendingNews);
RecyclerViewMoreSingleHotTrendingNews.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
RecyclerViewMoreSingleHotTrendingNews.setAdapter(adapterMoreSectionHotTrendingNews);
//Optimized
RecyclerViewMoreSingleHotTrendingNews.setHasFixedSize(true);
RecyclerViewMoreSingleHotTrendingNews.setItemViewCacheSize(20);
}
}
//But I got This error when I click "See All Item" button
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.indofun.android.indojoy, PID: 11456
java.lang.NullPointerException: Attempt to invoke virtual method 'void androidx.recyclerview.widget.RecyclerView.setAdapter(androidx.recyclerview.widget.RecyclerView$Adapter)' on a null object reference
at com.indofun.android.indojoy.Adapters.Adapter_HotTrendingNews.AdapterSectionHotTrendingNews$1.onClick(AdapterSectionHotTrendingNews.java:88)
at android.view.View.performClick(View.java:6891)
at android.view.View$PerformClick.run(View.java:26083)
at android.os.Handler.handleCallback(Handler.java:789)
at android.os.Handler.dispatchMessage(Handler.java:98)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6938)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:327)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1374)
From First Adapter onClick, call second adapter and update RecyclerView
sectionHotTrendingNewsViewHolder.BTNHotTrendingNewsMore.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
sectionHotTrendingNewsViewHolder.RecyclerViewSectionHotTrendingNews.setAdapter( new AdapterSingleHotTrendingNews(v.getContext(), modelSectionHotTrendingNews.get(position).getAllItemsInSection()))
}
});
Or if you want to show this More News in another activity. Then do this:
Make ModelSingleHotTrendingNews class Serializable like this:
public class ModelSingleHotTrendingNews implements Serializable {
...
}
Change onClick
sectionHotTrendingNewsViewHolder.BTNHotTrendingNewsMore.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(mContext, TabMoreHotActivity.class);
Intent().putExtra("MoreNews", modelSectionHotTrendingNews.get(position).getAllItemsInSection())
mContext.startActivity(intent);
}
});
In TabMoreHotActivity use ArrayList instead of ArrayList<ModelSectionHotTrendingNews>
hope this will help you. You made your code mess :(
You can create listeners in the Recyclers parent.
When some data from one recycler will be changed, trigger your listener in the current adapter after that your parent receives it and will trigger some updating method in the second recycler adapter.
But for sure it will be better if you provide some code or more detailed description.

Fail to solve E/RecyclerView: No adapter attached; skipping layout

When back to previous activity or I get out the app is closed and show this error:
E/RecyclerView: No adapter attached; skipping layout
Within a asycntask in his method onPostExecute I declare a recycleview and RecyclerView.LayoutManager but no have idea what it's wrong. I need your help to solve this problem. Below is my code:
#Override
public void onPostExecute(List<Modules> result) {
if (pDialog.isShowing()){
RecyclerView.LayoutManager Manager =new LinearLayoutManager(DepartureModule.this);
RecyclerView.Adapter adapter = new ModuleAdapter(result);
RecyclerView RVODetails = (RecyclerView) findViewById(R.id.RVODetails);
RVODetails.setLayoutManager(Manager);
RVODetails.setAdapter(adapter);
pDialog.dismiss();
}
and this is my adapter class:
public class ModuleViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
ItemClickListener itemClickListener;
public final ImageButton Actions;
public final ImageView Image;
public final TextView ModuleCode;
public final TextView ModuleDescription;
public final TextView ModuleDate;
public String ModuleIds;
public ModuleViewHolder(View itemView) {
super(itemView);
Image = (ImageView)itemView.findViewById(R.id.logo);
Actions = (ImageButton)itemView.findViewById(R.id.Actions);
//TitleModuleCode = (TextView)itemView.findViewById(R.id.TitleModuleCode);
ModuleCode = (TextView)itemView.findViewById(R.id.ModuleCode);
//TitleModuleDescription = (TextView)itemView.findViewById(R.id.TitleModuleDescription);
ModuleDescription = (TextView)itemView.findViewById(R.id.ModuleDescription);
ModuleDate = (TextView)itemView.findViewById(R.id.ModuleDate);
itemView.setOnClickListener(this);
}
#Override
public void onClick(View view) {
this.itemClickListener.OnItemClick(view,getLayoutPosition());
// Toast.makeText(view.getContext(), "POS" + getLayoutPosition()
// , Toast.LENGTH_LONG).show();
}
public void setItemClickListener(ItemClickListener ItemClick){
this.itemClickListener = ItemClick;
}
}
public ModuleAdapter(List<Modules> Items){
this.Items = Items;
}
#Override
public int getItemCount() {
return Items.size();
}
#Override
public ModuleViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext())
.inflate(R.layout.layout_cardview,viewGroup,false);
return new ModuleViewHolder(view);
}
#Override
public void onBindViewHolder(final ModuleViewHolder ViewHolder, final int position) {
context = ViewHolder.itemView.getContext();
Typeface typeface = Typeface.createFromAsset(context.getAssets(),
"fonts/CaviarDreams.ttf");
ViewHolder.Image.setImageResource(Items.get(position).getImages());
ViewHolder.Actions.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
ShowPopupMenu(ViewHolder.Actions,position,ViewHolder);
}
});
ViewHolder.ModuleCode.setText(Items.get(position).getModule());
ViewHolder.ModuleCode.setTypeface(typeface); ViewHolder.ModuleDescription.setText(Items.get(position).getDescription());
ViewHolder.ModuleDescription.setTypeface(typeface);
ViewHolder.ModuleDate.setText(Items.get(position).getDate());
ViewHolder.ModuleDate.setTypeface(typeface);
ViewHolder.ModuleIds = Items.get(position).getModuleIds();
ViewHolder.setItemClickListener(new ItemClickListener() {
#Override
public void OnItemClick(View view, int Pos) {
//Toast.makeText(context, "POSITION :" + Pos, Toast.LENGTH_SHORT).show();
}
});
}
private void ShowPopupMenu (final View view, final int position,final ModuleViewHolder holder){
menu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem item) {
switch (item.getItemId()){
case R.id.action_modify:
final Connection connectionupdate = new Connection(context,Connection.DATABASE_NAME,null,
Connection.DATABASE_VERSION);
final SQLiteDatabase dbUpdate = connectionupdate.getWritableDatabase();
Typeface typeface = Typeface.createFromAsset(context.getAssets(),"fonts/CaviarDreams.ttf");
AlertDialog.Builder ModifyModule = new AlertDialog.Builder(context);
LayoutInflater modifyinflater = (LayoutInflater)context.getSystemService
(Context.LAYOUT_INFLATER_SERVICE);
final View viewmodify = modifyinflater.inflate(R.layout.layout_custom_dialog_create_modules,null);
TILM = (TextInputLayout)viewmodify.findViewById(R.id.TILM);
TILM.setTypeface(typeface);
TILD = (TextInputLayout)viewmodify.findViewById(R.id.TILD);
TILD.setTypeface(typeface);
ModuleCodeE = (EditText)viewmodify.findViewById(R.id.ModuleCode);
ModuleCodeE.setTypeface(typeface);
ModuleDescE = (EditText)viewmodify.findViewById(R.id.ModuleDesc);
ModuleDescE.setTypeface(typeface);
ModuleCodeE.setText(Items.get(position).getModule());
ModuleDescE.setText(Items.get(position).getDescription());
final String Id = Items.get(position).getModuleIds();
ModifyModule.setView(viewmodify);
ModifyModule.setIcon(R.drawable.logomini);
ModifyModule.setTitle("Construmuebles FM");
ModifyModule.setMessage(" Modifica los valores en los siguientes campos :");
ModifyModule.setPositiveButton("Actualizar", new DialogInterface.OnClickListener(){
#Override
public void onClick(DialogInterface dialogInterface, int i) {
ContentValues VUpdate = new ContentValues();
VUpdate.put(Database.CamposModuloDetails.KEY_MODULE_CODE,ModuleCodeE.getText().toString()); VUpdate.put(Database.CamposModuloDetails.KEY_MODULE_DESC,ModuleDescE.getText().toString());
long IdUpdate = dbUpdate.update(Database.MODULE_DETAILS_TABLE,VUpdate,Database.CamposModuloDetails
.KEY_MODULE_DETAILS_ID + " = ?",new String []{Id});
new UpdateCardView(context,IdUpdate).execute();
dialogInterface.dismiss();
}
});
ModifyModule.setNegativeButton("Cancelar", new DialogInterface
.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.dismiss();
}
});
ModifyModule.show();
return true;
case R.id.action_delete:
new DeleteCardView(context,holder,position).execute();
return true;
}
return false;
}
});
menu.show();
}
class DeleteCardView extends AsyncTask<Void,Void,Long>{
private ProgressDialog pDialog;
ModuleViewHolder holder;
int position;
public DeleteCardView(Context context,ModuleViewHolder holder,int position) {
pDialog = new ProgressDialog(context);
this.holder = holder;
this.position = position;
}
#Override
protected void onPreExecute() {
pDialog.setMessage(" Eliminado registro...");
pDialog.show();
}
#Override
protected Long doInBackground(Void... voids) {
String ModuleIdCardView = holder.ModuleIds;
Connection connection = new Connection(context, Connection.DATABASE_NAME, null,
Connection.DATABASE_VERSION);
long i = connection.DeleteByIdCardView(ModuleIdCardView);
if (i != 0) {
return i;
} else {
return i;
}
}
#Override
protected void onPostExecute(Long Result) {
if (pDialog.isShowing()){
pDialog.dismiss();
Items.remove(position);
notifyItemRemoved(position);
notifyItemRangeChanged(position,Items.size());
if (Items.size()==0){ /**viewPager.setCurrentItem(0);**/ }
}
}
}
}
Rearrange your code as follows
recyclerView = (RecyclerView) findViewById(R.id.RVODetails);
mAdapter = new ModuleAdapter(result);
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext());
recyclerView.setLayoutManager(mLayoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.setAdapter(mAdapter);
}

how to use getItematposition() in recyclerview adapter as ListView

I have a RecyclerViewAdapter which fill my List with StoreName,image etc, I had model for listitems.ok, I'm migrating from a ListView to recylerview. i want to click on any item and get that items data(like Store name) and intent to another activity, now problem is that when i click on item it give wrong storename. but when i was using onItemclickListener that provide correct input. i will show u..
This my RecyclerViewAdapter.
public class MyRecyclerViewAdapter extends RecyclerView.Adapter<MyRecyclerViewAdapter.DataObjectHolder> {
private static String LOG_TAG = "MyRecyclerViewAdapter";
private List<StoresItem> mDataset;
private static MyClickListener myClickListener;
Context context;
Bitmap xx;
public MyRecyclerViewAdapter(Context context, List<StoresItem> myDataset)
{
mDataset = myDataset;
}
public static class DataObjectHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
TextView txtStoreName,txtDeliveryTime;
ImageView storeImg;
RatingBar ratingBar;
public DataObjectHolder(View itemView)
{
super(itemView);
txtStoreName = (TextView) itemView.findViewById(R.id.txtStoreName);
txtDeliveryTime = (TextView) itemView.findViewById(R.id.txtDeliveryTime);
storeImg = (ImageView) itemView.findViewById(R.id.storeImg);
ratingBar=(RatingBar)itemView.findViewById(R.id.ratingBar);
Log.i(LOG_TAG, "Adding Listener");
itemView.setOnClickListener(this);
}
#Override
public void onClick(View v)
{
myClickListener.onItemClick(getLayoutPosition(), v);
}
}
public void setOnItemClickListener(MyClickListener myClickListener)
{
this.myClickListener = myClickListener;
}
#Override
public DataObjectHolder onCreateViewHolder(ViewGroup parent, int viewType)
{
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.storelist, parent, false);
DataObjectHolder dataObjectHolder = new DataObjectHolder(view);
return dataObjectHolder;
}
#Override
public void onBindViewHolder(DataObjectHolder holder, int position)
{
ImageView storeImg;
holder.txtStoreName.setText(mDataset.get(position).gettxtStoreName().toString());
holder.txtDeliveryTime.setText(mDataset.get(position).gettxtDeliveryTime().toString());
holder.ratingBar.setFocusable(false);
int loader = R.drawable.image;
String url = mDataset.get(position).getstoreImg().toString();
ImageLoader imgLoader = new ImageLoader(context);
imgLoader.DisplayImage(url,loader,holder.storeImg);
}
public void addItem(StoresItem dataObj, int index) {
mDataset.add(dataObj);
notifyItemInserted(index);
}
public void deleteItem(int index) {
mDataset.remove(index);
notifyItemRemoved(index);
}
#Override
public int getItemCount() {
return mDataset.size();
}
public interface MyClickListener
{
public void onItemClick(int position, View v);
}
public Object getItem(int position)
{
return mDataset.get(position);
}
#Override
public long getItemId(int position)
{
return mDataset.indexOf(getItem(position));
}
#Override
public int getItemViewType(int position)
{
return super.getItemViewType(position);
}
}
This is my StoreModel.
public class StoresItem
{
private String txtStoreName, txtDeliveryTime, storeImg;
public StoresItem(String txtStoreName, String txtDeliveryTime,String storeImg)
{
this.txtStoreName = txtStoreName;
this.txtDeliveryTime = txtDeliveryTime;
this.storeImg = storeImg;
}
public String gettxtStoreName()
{
return txtStoreName;
}
public void settxtStoreName(String txtStoreName)
{
this.txtStoreName = txtStoreName;
}
public String gettxtDeliveryTime()
{
return txtDeliveryTime;
}
public void settxtDeliveryTime(String txtDeliveryTime)
{
this.txtDeliveryTime = txtDeliveryTime;
}
public String getstoreImg()
{
return storeImg;
}
public void setstoreImg(String storeImg)
{
this.storeImg = storeImg;
}
}
And this is my Fragment where i using onclickListner.
public class RecylerFragment extends Fragment
{
ListView storeListView;
List<StoresItem> storesItem;
StoresListAdaptor adapter;
String selectedStore;
private RecyclerView mRecyclerView;
private RecyclerView.Adapter mAdapter;
private RecyclerView.LayoutManager mLayoutManager;
public static final String[] storeNameGrocery = new String[]
{
"Value Store", "Grocery Mart", "Wild Water-Sadar Bazar", "Store99","Coco-Buzz", "Wild Water - Sector 46"
};
public static final String[] storeNameFresh = new String[]
{
"Mother's Love", "The Flower Shop", "Flower N Emotions"
};
public static final String[] storeNameElectronics = new String[]
{
"Molife-Sheetla Mata Road", "Apple Store- Shona Road", "Vandana Communication", "Samsung Store","JMD Mobile - Sector 14", "Sterling - Gurgaon"
};
public static final String[] storeNameVegetable = new String[]
{
"Fortune Store", "Best Food - Mega Mall", "Sadar Bazar", "MTR Store","Coco-Buzz"
};
public static final String[] deliveryTime = new String[]
{
"20min", "10min", "9min", "15min","30min", "1hr","20min","20min", "10min", "9min", "15min","30min", "1hr","20min" };
private static final String KEY_POSITION="position";
public static final String[] iconsUrl = new String[]
{
"http://icons.iconarchive.com/icons/femfoyou/angry-birds/96/angry-bird-icon.png",
"http://icons.iconarchive.com/icons/rokey/the-blacy/96/grimace-icon.png",
"http://wcdn1.dataknet.com/static/resources/icons/set106/fec007de.png",
"http://cdn4.aptoide.com/imgs/7/6/e/76e0376928b8393227a150fbed5d6b4a_icon_96x96.png",
"http://vaivocabulary.com/vai/images/android.png",
"http://cdn4.aptoide.com/imgs/7/6/e/76e0376928b8393227a150fbed5d6b4a_icon_96x96.png",
"http://vaivocabulary.com/vai/images/android.png",
"http://wcdn1.dataknet.com/static/resources/icons/set106/fec007de.png",
};
public RecylerFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
View rootView = inflater.inflate(R.layout.activity_recycler_view, container, false);
Bundle bundle = this.getArguments();
String myString = bundle.getString("page_position");
mRecyclerView = (RecyclerView) rootView.findViewById(R.id.my_recycler_view);
mRecyclerView.setHasFixedSize(true);
mLayoutManager = new LinearLayoutManager(getActivity());
mRecyclerView.setLayoutManager(mLayoutManager);
RecyclerView.ItemDecoration itemDecoration = new DividerItemDecoration(getActivity(), LinearLayoutManager.VERTICAL);
mRecyclerView.addItemDecoration(itemDecoration);
// Code to Add an item with default animation
//((MyRecyclerViewAdapter) mAdapter).addItem(obj, index);
// Code to remove an item with default animation
//((MyRecyclerViewAdapter) mAdapter).deleteItem(index);
storesItem = new ArrayList<StoresItem>();
if(myString.equals("999")) {
for (int i = 0; i < storeNameGrocery.length; i++) {
StoresItem item = new StoresItem(storeNameGrocery[i], "Delivery Time " + deliveryTime[i],iconsUrl[i]);
storesItem.add(item);
}
}
else if(myString.equals("888")) {
for (int i = 0; i < storeNameFresh.length; i++) {
StoresItem item = new StoresItem(storeNameFresh[i], "Delivery Time " + deliveryTime[i], iconsUrl[i]);
storesItem.add(item);
}
}
else if(myString.equals("777")) {
for (int i = 0; i < storeNameElectronics.length; i++) {
StoresItem item = new StoresItem(storeNameElectronics[i], "Delivery Time " + deliveryTime[i], iconsUrl[i]);
storesItem.add(item);
}
}
else if(myString.equals("666")) {
for (int i = 0; i < storeNameVegetable.length; i++) {
StoresItem item = new StoresItem(storeNameVegetable[i], "Delivery Time " + deliveryTime[i], iconsUrl[i]);
storesItem.add(item);
}
}
mAdapter = new MyRecyclerViewAdapter(getActivity(), storesItem);
mRecyclerView.setAdapter(mAdapter);
return rootView;
}
**#Override
public void onResume() {
super.onResume();
((MyRecyclerViewAdapter) mAdapter).setOnItemClickListener(new MyRecyclerViewAdapter.MyClickListener()
{
#Override
public void onItemClick(int position, View v)
{
System.out.println(" Clicked on Item " + position);
StoresItem storesItems = (StoresItem) ((MyRecyclerViewAdapter) mAdapter).getItem(position);
Bundle args = new Bundle();
Intent in = new Intent(getActivity(), ProductActivity.class);
args.putString("SelectedStoreName", storesItems.gettxtStoreName().toString());
in.putExtras(args);
startActivity(in);
}
});
}**
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
}
#Override
public void onDetach() {
super.onDetach();
}
}
okk...there is something wrong with recyclerviews-onItemclicklister because listviews - onItemCLicklistner()
provide Adapterview and i can simply get Item by using parent.getItematposition(position) like this.
storeListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
StoresItem storesItems = (StoresItem) parent.getItemAtPosition(position);
Bundle args = new Bundle();
Intent in = new Intent(getActivity(), ProductActivity.class);
args.putString("SelectedStoreName", storesItems.gettxtStoreName().toString());
in.putExtras(args);
startActivity(in);
}
});
Can Any one tell me whats the reason why getWrong StoreName.??
You are using myClickListener.onItemClick(getLayoutPosition(), v); you have to use myClickListener.onItemClick(getAdapterPosition(), v);

Categories

Resources