Related
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;
}
I have a relative layout which contains a viewpager to enable to me swipe images fetched from my web service.The fetched images are then stored in a ArrayList which contains a HashMap. I've logged the fetching part of from web service and the log indicates that I am indeed fetching different images. However, whenever I'm swiping from image to image, the viewpager displays the same image which is always the last image saved. I've logged the ArrayList of images in the Pager Adapter and it seems that I am getting the correct arraylist size but I'm getting the same bitmap in all sizes.
This is my PagerAdapter class:
public class ImageAdapter extends PagerAdapter {
private LayoutInflater layoutInflater;
private Context context;
private ArrayList<HashMap<String, Object>> images;
public ImageAdapter(Context context, ArrayList<HashMap<String, Object>> images) {
this.context = context;
this.images = images;
layoutInflater = LayoutInflater.from(context);
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
layoutInflater = (LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = layoutInflater.inflate(R.layout.view_pager_image_video, null);
RelativeLayout rlAttach = (RelativeLayout) view.findViewById(R.id.rl_attach);
ImageView imgAttach = (ImageView) view.findViewById(R.id.img_attach);
VideoView vvAttach = (VideoView) view.findViewById(R.id.vv_attach);
LinearLayout llOverlay = (LinearLayout) view.findViewById(R.id.ll_video_overlay);
ProgressBar pBar = (ProgressBar) view.findViewById(R.id.pBar);
LinearLayout llUnsupportFile = (LinearLayout) view.findViewById(R.id.ll_unsupport_file);
Log.d(TAG, "image: " + images.size() + " " + images);
Bitmap image = (Bitmap) images.get(position).get("image");
image = CommonUtilities.checkBitmapRotation(bmp);
imgAttach.setVisibility(View.VISIBLE);
vvAttach.setVisibility(View.GONE);
llOverlay.setVisibility(View.GONE);
llUnsupportFile.setVisibility(View.GONE);
imgAttach.setImageBitmap(image);
pBar.setVisibility(View.GONE);
setPreviewClick(imgAttach, position, rlAttach);
container.addView(view);
return view;
}
#Override
public int getCount() {
return images.size();
}
#Override
public boolean isViewFromObject(View view, Object obj) {
return view == obj;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
View view = (View) object;
container.removeView(view);
}
}
This is where I set the adapter and set notifidydatasetchange:
if (galleryList.size() > 0) {
llNoGallery.setVisibility(View.GONE);
rlHasGallery.setVisibility(View.VISIBLE);
pbGallery.setVisibility(View.GONE);
vpGallery.setVisibility(View.VISIBLE);
tvPageCount.setVisibility(View.VISIBLE);
mImageAdapter = new ImageAdapter(getActivity(), galleryList);
for (HashMap getList : galleryList) {
Log.d(TAG, "onMe: " + getList.toString());
}
vpGallery.setAdapter(mImageAdapter);
vpGallery.addOnPageChangeListener(viewPagerPageChangeListener);
vpGallery.setOffscreenPageLimit(galleryList.size());
mImageAdapter.notifyDataSetChanged();
tvPageCount.setText("1/" + galleryList.size());
} else {
rlHasGallery.setVisibility(View.GONE);
llNoGallery.setVisibility(View.VISIBLE);
}
This is the function to save the images fetched to the arraylist:
private void saveImagesToArrayList(String photo) {
bmp = null;
if (!photo.isEmpty()) {
bmp = imageLoader.loadImageSync(photo);
// tmp hashmap for single image
HashMap<String, Object> hmImage = new HashMap<String, Object>();
// adding each child node to HashMap key => value
hmImage.put("image", bmp);
galleryList.add(hmImage);
// tmp hashmap for single image
HashMap<String, Object> hmImageInString = new HashMap<String, Object>();
// adding each child node to HashMap key => value
hmImageInString.put("image", photo);
galleryListInString.add(hmImageInString);
}
}
This is my ViewPagerChangeListener which shows the position of the image swipped to :
ViewPager.OnPageChangeListener viewPagerPageChangeListener = new ViewPager.OnPageChangeListener() {
#Override
public void onPageSelected(int position) {
tvPageCount.setText(position + 1 + "/" + (galleryList.size()));
}
#Override
public void onPageScrolled(int pos, float arg1, int arg2) {
}
#Override
public void onPageScrollStateChanged(int state) {
}
};
Here I have the setPreviewClick method to open up the image in full screen via intent. The images show here are correct here which displays different images on swipe.
private void setPreviewClick(View view, int imagePosition, RelativeLayout rlAttach) {
final int mPosition = imagePosition;
rlAttach.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
intentViewActivity(mPosition);
}
});
ImageView mImg = (ImageView) view;
mImg.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
intentViewActivity(mPosition);
}
});
}
The intentViewActivity method is as follows:
public void intentViewActivity(int position) {
Intent intent = new Intent(getActivity(), ViewImageViewPagerActivity.class);
intent.putExtra("images", galleryListInString);
intent.putExtra("image_position", position);
getActivity().startActivity(intent);
}
The one of the parameter of the intentViewActivity method is the ViewImageViewPagerActivity which is this:
package com.epicamera.vms.i_neighbour.activity;
public class ViewImageViewPagerActivity extends AppCompatActivity {
private String TAG = "ViewImageViewPagerActivity";
Toolbar toolbar;
private View temp_view;
private VideoView vv;
private TextView toolbar_title;
private ViewPager insideViewPager;
private MyViewPagerAdapter myViewPagerAdapter;
ArrayList<HashMap<String, Object>> imageList = new ArrayList<>();
Bitmap bmp = null;
ImageLoader imageLoader = ImageLoader.getInstance(); // Get singleton instance
private String username, companyname, usertype, companylogo, userid, token, userphoto, usergender;
private String android_id;
private String regId;
private Bitmap attachment = null;
private int imagePosition = 0, actualPosition = 0;
private int onPageScrollPosition = 0;
private boolean isVideo = false;
private Handler fileCheckerHandler = new Handler();
private Runnable fileCheckerRunnable = null;
private Uri uri;
// AsyncTask
AsyncTask<Void, Void, Boolean> task;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_image_video_viewpager);
CommonUtilities.toggleRotationAdvance(this);
toolbar = (Toolbar) findViewById(R.id.toolbar);
toolbar_title = (TextView) findViewById(R.id.toolbar_title);
setSupportActionBar(toolbar);
getSupportActionBar().setHomeAsUpIndicator(R.drawable.ic_action_back);
// enable ActionBar app icon to behave as action to toggle nav drawer
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
//remove the tittle
getSupportActionBar().setDisplayShowTitleEnabled(false);
SessionManager session = new SessionManager(this.getApplicationContext());
// get user data from session
HashMap<String, String> user = session.getUserDetails();
// session id
username = user.get(SessionManager.KEY_USERNAME);
// user id
companyname = user.get(SessionManager.KEY_COMPANYNAME);
// company id
usertype = user.get(SessionManager.KEY_USERTYPE);
// company id
companylogo = user.get(SessionManager.KEY_COMPANYLOGO);
// user id
userid = user.get(SessionManager.KEY_USERID);
// session token
token = user.get(SessionManager.KEY_TOKEN);
// session user photo
userphoto = user.get(SessionManager.KEY_USERPHOTO);
usergender = user.get(SessionManager.KEY_USERGENDER);
android_id = Settings.Secure.getString(getContentResolver(),
Settings.Secure.ANDROID_ID);
insideViewPager = (ViewPager) findViewById(R.id.inside_view_pager);
imageList = (ArrayList<HashMap<String,Object>>) getIntent().getExtras().getSerializable("images");
imagePosition = getIntent().getExtras().getInt("image_position");
actualPosition = imagePosition;
myViewPagerAdapter = new MyViewPagerAdapter(ViewImageViewPagerActivity.this, imageList);
insideViewPager.setAdapter(myViewPagerAdapter);
insideViewPager.addOnPageChangeListener(viewPagerPageChangeListener);
insideViewPager.setOffscreenPageLimit(imageList.size());
insideViewPager.setCurrentItem(actualPosition, false);
myViewPagerAdapter.notifyDataSetChanged();
toolbar_title.setText(actualPosition + 1 + " / " + (imageList.size()));
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// return super.onCreateOptionsMenu(menu);
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.view_image_menu, menu);
return true;
}
/* Called whenever we call invalidateOptionsMenu() */
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
return super.onPrepareOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
Log.d(TAG, "id: " + item.getItemId());
switch (item.getItemId()) {
case android.R.id.home:
onBackPressed();
return true;
case R.id.action_savetogallery:
String[] count = toolbar_title.getText().toString().split("/");
int value = Integer.parseInt(count[0].trim()) - 1;
HashMap<String, String> child = new HashMap<>();
child.put("image", (String) imageList.get(value).get("image"));
saveToGallery(child, "File");
return true;
default:
return super.onOptionsItemSelected(item);
}
}
#Override
public void onBackPressed() {
super.onBackPressed();
}
#Override
protected void onPause() {
super.onPause();
}
#Override
protected void onResume() {
super.onResume();
}
public void saveToGallery(HashMap<String, String> item, final String type) {
//take the current position
final String select_document_link = item.get("image");
final String select_document_name = item.get("image");
final String selected_document = select_document_name.substring(select_document_name.lastIndexOf('/') + 1, select_document_name.length());
final String document_download_path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM + "/i-Neighbour").getPath() + File.separator + selected_document;
final File file = new File(document_download_path);
Log.d(TAG, "path: " + document_download_path + " " + select_document_link);
// Check is the file is exist
// if (file.exists()) {
// //Open the file if exist
// openFile(file);
// } else {
//Download and open the file, if does not exist
try {
Toast.makeText(ViewImageViewPagerActivity.this, "Downloading...", Toast.LENGTH_SHORT).show();
// final ProgressDialog progDailog = ProgressDialog.show(this,
// this.getResources().getString(R.string.txt_title_downloading),
// this.getResources().getString(R.string.txt_document_downloading), true);
new Thread() {
public void run() {
try {
//Download the document
final DownloadManager downloadManager;
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM + "/i-Neighbour").mkdirs();
downloadManager = (DownloadManager) ViewImageViewPagerActivity.this.getSystemService(Context.DOWNLOAD_SERVICE);
// have to replace space to %20
String url = select_document_link.replace(" ", "%20");
Uri uri = Uri.parse(url);
DownloadManager.Request request = new DownloadManager.Request(uri)
.setTitle(selected_document)
.setDestinationInExternalPublicDir(Environment.DIRECTORY_DCIM + "/i-Neighbour",
selected_document)
.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
downloadManager.enqueue(request);
//ADDED LOOP HERE UNTIL FILE DOWNLOAD IS COMPLETE
fileCheckerRunnable = new Runnable() {
public void run() {
DownloadManager.Query query = new DownloadManager.Query();
query.setFilterByStatus(DownloadManager.STATUS_FAILED | DownloadManager.STATUS_PAUSED | DownloadManager.STATUS_SUCCESSFUL | DownloadManager.STATUS_RUNNING | DownloadManager.STATUS_PENDING);
Cursor cursor = downloadManager.query(query);
if (cursor.moveToFirst()) {
int status = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_STATUS));
switch (status) {
case DownloadManager.STATUS_PAUSED:
//download is waiting to retry or resume
fileCheckerHandler.postDelayed(this, 1000);
break;
case DownloadManager.STATUS_PENDING:
//download is waiting to start
fileCheckerHandler.postDelayed(this, 1000);
break;
case DownloadManager.STATUS_RUNNING:
//download is currently running
fileCheckerHandler.postDelayed(this, 1000);
break;
case DownloadManager.STATUS_SUCCESSFUL:
//download has successfully completed
//Open the document
// openFile(file);
Toast.makeText(ViewImageViewPagerActivity.this, type + " saved to Gallery->i-
Neighbour", Toast.LENGTH_SHORT).show();
// progDailog.dismiss();
//STOP REPEATING TASK
fileCheckerHandler.removeCallbacks(fileCheckerRunnable);
break;
case DownloadManager.STATUS_FAILED:
//download has failed (and will not be retried)
// progDailog.dismiss();
//STOP REPEATING TASK
fileCheckerHandler.removeCallbacks(fileCheckerRunnable);
break;
}
}
}
};
fileCheckerHandler.postDelayed(fileCheckerRunnable, 1000);
} catch (Exception e) {
Log.d(TAG, "Error: " + e);
}
}
}.start();
} catch (Exception e) {
Log.e("ERROR", "Error -> " + e.getMessage());
}
}
// outside viewpager change listener
ViewPager.OnPageChangeListener viewPagerPageChangeListener = new ViewPager.OnPageChangeListener() {
#Override
public void onPageSelected(int position) {
toolbar_title.setText(position + 1 + " / " + (imageList.size()));
onPageScrollPosition = position;
Log.d(TAG, "onpagescrollposition: " + onPageScrollPosition);
}
#Override
public void onPageScrolled(int pos, float arg1, int arg2) {
}
#Override
public void onPageScrollStateChanged(int state) {
}
};
/**
* View pager adapter
*/
public class MyViewPagerAdapter extends PagerAdapter {
private LayoutInflater layoutInflater;
private Context context;
private ArrayList<HashMap<String, Object>> images;
public MyViewPagerAdapter(Context context, ArrayList<HashMap<String, Object>> images) {
this.context = context;
this.images = images;
layoutInflater = LayoutInflater.from(context);
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
layoutInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = layoutInflater.inflate(R.layout.view_pager_image_video2, null);
final VideoView vvFullScreen = (VideoView) view.findViewById(R.id.vv_full_screen);
final TouchImageView imgFullScreen = (TouchImageView) view.findViewById(R.id.img_full_screen);
final ImageView imgVideoBg = (ImageView) view.findViewById(R.id.img_video_bg);
final ProgressBar pBar = (ProgressBar) view.findViewById(R.id.pBar);
final LinearLayout llVideoPlay = (LinearLayout) view.findViewById(R.id.ll_video_play);
view.setTag("pos" + position);
//Bitmap image = (Bitmap) images.get(position).get("image");
String image_url = (String) images.get(position).get("image");
imgFullScreen.setVisibility(View.VISIBLE);
vvFullScreen.setVisibility(View.GONE);
llVideoPlay.setVisibility(View.GONE);
Glide.with(context).load(image_url)
.thumbnail(0.5f)
.crossFade()
.diskCacheStrategy(DiskCacheStrategy.ALL)
.into(imgFullScreen);
container.addView(view);
return view;
}
#Override
public int getCount() {
return images.size();
}
#Override
public boolean isViewFromObject(View view, Object obj) {
return view == obj;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
View view = (View) object;
container.removeView(view);
}
#Override
public int getItemPosition(Object object) {
return super.getItemPosition(object);
}
}
}
I am trying to use TextChangedListener to implement search functionality on my ListView. But after adding some character in EditText; the ListView goes blank. I have implemented filter method in my ArrayAdapter class.
I am getting my data from JSON.
My Logcat shows: getSlotFromBufferLocked: unknown buffer
Is there any other way to search ListView?
Here's my code:
UserList.java
public class UserList extends AppCompatActivity {
private ListView listView;
private ArrayList<MyDataModel> list;
private MyArrayAdapter adapter;
private EditText search;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.user_list);
search = (EditText) findViewById(R.id.search);
//Array List for Binding Data from JSON to this List
list = new ArrayList<>();
//Binding that List to Adapter
adapter = new MyArrayAdapter(this, list);
//Getting List and Setting List Adapter
listView = (ListView) findViewById(R.id.listView);
listView.setAdapter(adapter);
listView.setTextFilterEnabled(true);
search.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
String text = search.getText().toString().toLowerCase(Locale.getDefault());
adapter.filter(text);
}
#Override
public void afterTextChanged(Editable s) {
}
});
//Checking Internet Connection
if (InternetConnection.checkConnection(getApplicationContext())) {
new GetDataTask().execute();
} else {
Snackbar.make(findViewById(R.id.parentLayout),"Internet Connection Not Available", Snackbar.LENGTH_LONG).show();
}
}
//Creating Get Data Task for Getting Data From Web
class GetDataTask extends AsyncTask<Void, Void, Void> {
ProgressDialog dialog;
int jIndex;
int x;
#Override
protected void onPreExecute() {
super.onPreExecute();
//Progress Dialog for User Interaction
x=list.size();
if(x==0)
jIndex=0;
else
jIndex=x;
dialog = new ProgressDialog(UserList.this);
dialog.setTitle("Please Wait..."+x);
dialog.setMessage("Retrieving Data");
dialog.show();
}
#Nullable
#Override
protected Void doInBackground(Void... params) {
//Getting JSON Object from Web Using okHttp
JSONObject jsonObject = JSONParser.getDataFromWeb();
try {
if (jsonObject != null) {
if(jsonObject.length() > 0) {
JSONArray array = jsonObject.getJSONArray(Keys.KEY_CONTACTS);
//Check Length of Array...
int lenArray = array.length();
if(lenArray > 0) {
for( ; jIndex < lenArray; jIndex++) {
//Creating Every time New Object and adding to List
MyDataModel model = new MyDataModel();
JSONObject innerObject = array.getJSONObject(jIndex);
String name = innerObject.getString(Keys.KEY_NAME);
model.setName(name);
list.add(model);
}
}
}
} else {
}
} catch (JSONException je) {
Log.i(JSONParser.TAG, "" + je.getLocalizedMessage());
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
dialog.dismiss();
//Checking if List size if more than zero then update ListView
if(list.size() > 0) {
adapter.notifyDataSetChanged();
} else {
Snackbar.make(findViewById(R.id.parentLayout), "No Data Found", Snackbar.LENGTH_LONG).show();
}
}
}
}
I have implemented the filter method in my ArrayAdapter class.
Here's my ArrayAdapter class:
MyArrayAdapter.java
public class MyArrayAdapter extends ArrayAdapter<MyDataModel> implements Filterable{
List<MyDataModel> modelList;
Context context;
private LayoutInflater mInflater;
private ArrayList<MyDataModel> arrayList;
public MyArrayAdapter(Context context, List<MyDataModel> objects) {
super(context, 0, objects);
this.context = context;
this.mInflater = LayoutInflater.from(context);
modelList = objects;
this.arrayList = new ArrayList<MyDataModel>();
this.arrayList.addAll(modelList);
}
#Override
public MyDataModel getItem(int position) {
return modelList.get(position);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
final ViewHolder vh;
if (convertView == null) {
View view = mInflater.inflate(R.layout.layout_row_view, parent, false);
vh = ViewHolder.create((RelativeLayout) view);
view.setTag(vh);
} else {
vh = (ViewHolder) convertView.getTag();
}
MyDataModel item = getItem(position);
vh.textViewName.setText(item.getName());
return vh.rootView;
}
private static class ViewHolder {
public final RelativeLayout rootView;
public final TextView textViewName;
private ViewHolder(RelativeLayout rootView, TextView textViewName) {
this.rootView = rootView;
this.textViewName = textViewName;
}
public static ViewHolder create(RelativeLayout rootView) {
TextView textViewName = (TextView) rootView.findViewById(R.id.textViewName);
return new ViewHolder(rootView, textViewName);
}
}
// Filter Class
public void filter(String charText) {
charText = charText.toLowerCase(Locale.getDefault());
modelList.clear();
if (charText.length() == 0) {
modelList.addAll(arrayList);
} else {
for (MyDataModel wp : arrayList) {
if (wp.getName().toLowerCase(Locale.getDefault()).contains(charText)) {
modelList.add(wp);
}
}
}
notifyDataSetChanged();
}
Try,
modelList = new ArrayList<MyDataModel>;
Write this line after modelList.clear(); and check.
Go with this link, and follow steps for implementing the same:
and the problem with buffer is called every textchanged listener will call everytime if you add or delete any character or space in it. So avoid using that. It will cause memory leak problems.
I have a question about passing clicked cardview data to activity, and here the full story :
I have an Activity called "Details", which contains 2 TextViews in it's layout, Title & Description .
I have setup a fragment ( tab_1 ) which contain the recyclerview codes and the the items data, each item of those contain : title & description .
What i want :
When the user click the item, it will open the Details Activity, and change Details layout title, with clicked item title, and the same for description .
I've manged to create the other activity as an example, and made intent to start it, plus adding "addOnTouchlistener" thanks to Stackoverflow, i've found the way to make it .
So, how to make this alive? I've tried many ways of the available answers on Stackoverflow, but all of them not working, or not related to my request .
Here are my files :
itemsdata.java :
public class itemsdata {
int CatPic;
String title;
String Descr;
int Exapnd;
int expand_no;
tab_1.java ( fragment )
public class tab_1 extends Fragment implements SearchView.OnQueryTextListener {
private RecyclerView mRecyclerView;
public RecyclingViewAdapter adapter;
private Activity context;
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View layout = inflater.inflate(R.layout.tab_1, container, false);
mRecyclerView = (RecyclerView)layout.findViewById(R.id.recycler_view);
mRecyclerView.addOnItemTouchListener(new RecyclerItemClickListener
(getContext(), new RecyclerItemClickListener.OnItemClickListener() {
#Override
public void onItemClick(View view, int position) {
Intent i = new Intent(view.getContext(), DetailsActivity.class);
view.getContext().startActivity(i);
}
}));
mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
adapter = new RecyclingViewAdapter(getActivity(),Listed());
mRecyclerView.setAdapter(adapter);
return layout;
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.main, menu);
final MenuItem item = menu.findItem(R.id.action_search);
final SearchView searchView = (SearchView) MenuItemCompat.getActionView(item);
searchView.setOnQueryTextListener(this);
}
#Override
public boolean onQueryTextChange(String query) {
final List<itemsdata> filteredModelList = filter(Listed(), query);
adapter.animateTo(filteredModelList);
mRecyclerView.scrollToPosition(0);
return true;
}
#Override
public boolean onQueryTextSubmit(String query) {
return true;
}
private List<itemsdata> filter(List<itemsdata> models, String query) {
query = query.toLowerCase();
final List<itemsdata> filteredModelList = new ArrayList<>();
for (itemsdata model : models) {
final String text = model.title.toLowerCase();
if (text.contains(query)) {
filteredModelList.add(model);
}
}
return filteredModelList;
}
public List<itemsdata> Listed()
{
//Titles Strings
String sys_title1 = getString(R.string.system_item_title_1);
String sys_title2 = getString(R.string.system_item_title_2);
String sys_title3 = getString(R.string.system_item_title_3);
//Description Strings
String sys_descr1 = getString(R.string.system_item_desc_1);
String sys_descr2 = getString(R.string.system_item_desc_2);
String sys_descr3 = getString(R.string.system_item_desc_3);
//Adding New Cards
List<itemsdata> data = new ArrayList<>();
//Categories Icons New Items ** Make It The Same
int[] icons = {
R.drawable.facebook_icon ,
R.drawable.twitter_icon ,
R.drawable.twitter_icon
};
//Expand Button New Items
int[] expandbutton = {
R.drawable.expanded ,
R.drawable.expanded ,
R.drawable.expanded
};
//UnExpand Button New Items
int[] unexpandbutton = {
R.drawable.ca_expand ,
R.drawable.ca_expand ,
R.drawable.ca_expand
};
//Titles New Items
String[] titles = {
sys_title1 ,
sys_title2 ,
sys_title3
};
//Description New Items
String[] Description = {
sys_descr1 ,
sys_descr2 ,
sys_descr3
};
for(int i = 0;i<titles.length && i < icons.length && i < Description.length && i < unexpandbutton.length && i < expandbutton.length ; i++)
{
itemsdata current = new itemsdata();
current.CatPic = icons[i];
current.title = titles[i];
current.Descr = Description[i];
current.expand_no = unexpandbutton[i];
current.Exapnd = expandbutton[i];
data.add(current);
}
return data;
}
}
Details Activity :
public class DetailsActivity extends AppCompatActivity{
TextView title;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.details);
title = (TextView)findViewById(R.id.details_title);
}
EDIT : I've made it, i have added a button which open the fragment, and passed the data, in the Adapter, but i want it via tab_1.java, not the Adapter, i mean i want to click on the item to open the fragment, not on a button, here a snap from my Adapter code ( i've added it in OnBindViewHolder )
I've setup a OnClick and implemented the Vew.setOnClick ..etc, but when i click the item, nothing happen.
#Override
public void onBindViewHolder(final MyRecycleViewHolder holder, int position) {
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(v.getContext(),DetailsActivity.class);
v.getContext().startActivity(i);
}
});
//Referencing Data
final itemsdata currentobject = mdata.get(position);
//Referencing Items
holder.ProbTitle.setText(currentobject.title);
holder.ProbDescr.setText(currentobject.Descr);
holder.CategoryPic.setImageResource(currentobject.CatPic);
holder.ExpandButton.setImageResource(currentobject.Exapnd);
holder.ExpandNoButton.setImageResource(currentobject.expand_no);
//What Happen When You Click Expand Button .
holder.ExpandButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(v.getContext(), DetailsActivity.class);
i.putExtra("TitleKey",holder.ProbTitle.getText().toString());
v.getContext().startActivity(i);
}
}
);
public static class MyRecycleViewHolder extends RecyclerView.ViewHolder
{
SwipeLayout swipeLayout;
//Defining Items .
TextView ProbTitle;
ImageButton ExpandButton;
TextView ProbDescr;
ImageButton ExpandNoButton;
ImageView CategoryPic;
/*
TextView Card_Star;
TextView Card_UnStar;
*/
TextView Card_Share;
//Referencing Resources
public MyRecycleViewHolder(final View itemView) {
super(itemView);
ProbTitle = (TextView) itemView.findViewById(R.id.prob_title);
CategoryPic = (ImageView) itemView.findViewById(R.id.cat_pic);
ProbDescr = (TextView) itemView.findViewById(R.id.prob_descr);
ExpandButton = (ImageButton) itemView.findViewById(R.id.expand_button);
ExpandNoButton = (ImageButton) itemView.findViewById(R.id.expand_no_button);
/*
Card_Star = (TextView) itemView.findViewById(R.id.card_star);
Card_UnStar = (TextView) itemView.findViewById(R.id.card_unstar);
*/
Card_Share = (TextView) itemView.findViewById(R.id.card_share);
swipeLayout = (SwipeLayout) itemView.findViewById(R.id.swipe);
}
create an Interface inside your adapter containing methods. And while implementing your Adapter, those methods will be implemented in your activity and you can perform whatever action you want.
public class Adapter extends RecyclerView.Adapter<MyRecycleViewHolder> {
public interface Callbacks {
public void onButtonClicked(String titleKey);
}
private Callbacks mCallbacks;
public Adapter() {
}
#Override
public MyRecycleViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.layout_details, null);
return new MyRecycleViewHolder(v);
}
#Override
public void onBindViewHolder(final MyRecycleViewHolder holder, final int i) {
holder.ExpandButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mCallbacks != null) {
mCallbacks.onButtonClicked(holder.ProbTitle.getText().toString());
}
}
});
}
#Override
public int getItemCount() {
return;
}
public void setCallbacks(Callbacks callbacks) {
this.mCallbacks = callbacks;
}
}
you may try do this on your onItemClick()
Intent i = new Intent(view.getContext(), DetailsActivity.class);
i.putExtra("title", yourTitle);
i.putExtra("description", yourDescription);
view.getContext().startActivity(i);
and when oncreate in your DetailActivity,do this
String title = getIntent().getStringExtra("title");
String description = getIntent().getStringExtra("description");
so you can pass title and description to DetailActivity
IMO, you implement setOnClickListener inside Adapter of RecyclerView. You can refer to my following sample code, then apply its logic to your code. Hope it helps!
public class MyRVAdapter extends RecyclerView.Adapter<MyRVAdapter.ViewHolder> {
Context mContext;
List<String> mStringList;
public MyRVAdapter(Context mContext, List<String> mStringList) {
this.mContext = mContext;
this.mStringList = mStringList;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.cardview, parent, false);
v.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
TextView textView1 = (TextView) v.findViewById(R.id.textView1);
TextView textView2 = (TextView) v.findViewById(R.id.textView2);
Bundle bundle = new Bundle();
bundle.putString("key1", textView1.getText().toString());
bundle.putString("key2", textView2.getText().toString());
passToAnotherActivity(bundle);
}
});
return new ViewHolder(v);
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
// do something...
}
#Override
public int getItemCount() {
if (mStringList != null) {
return mStringList.size();
}
return 0;
}
private void passToAnotherActivity(Bundle bundle) {
if (mContext == null)
return;
if (mContext instanceof MainActivity) {
MainActivity activity = (MainActivity) mContext;
activity.passToAnotherActivity(bundle); // this method must be implemented inside `MainActivity`
}
}
public static class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
public ViewHolder(View itemView) {
super(itemView);
// do something...
}
#Override
public void onClick(View v) {
}
}
}
First of all make your "itemsdata" object to implement Parcelable. You can check it here . In your onItemClick method you pass the object to your Details activity using intent.putExtra("key",listOfDataItems.get(position));
In your DetailsActivity you can get your custom object with getParcelable("key")
All above methods worked, but kinda long, so this one worked for me :
Cardview cardview;
cardView = (CardView)itemView.findViewById(R.id.cv);
cardView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent (view.getContext(), DetailsActivity.class);
i.putExtra("TitleKey",ProbTitle.getText().toString());
i.putExtra("DescrKey",ProbDescr.getText().toString());
view.getContext().startActivity(i);
}
});
And in Details.java :
TextView title;
TextView Descr;
title = (TextView)findViewById(R.id.details_title);
Descr = (TextView)findViewById(R.id.details_descr);
String titleresult = result.getExtras().getString("TitleKey");
String Descrresult = result.getExtras().getString("DescrKey");
title.setText(titleresult);
Descr.setText(Descrresult);
I am using this project and edited it in my way. I used a common layout for every page. There is a ListView in that layout. I am checking the position of the page and setting different view to it depending on that position.
There is an editText in my actionbar. I want to filter the listview of the current page according to the onTextChanged of the editText. Everything is working fine but the filtering is not happening.
Here is my full code:
public class MainActivity extends ActionBarActivity {
public static TextView actionbarTitle;
public static EditText listViewEditText;
public static ImageButton listViewSearch;
public static Context context;
public static ListView songslist;
public static final int MAX_PAGES = 1;
private int num_pages = 5;
public ArrayList<String> title;
public ArrayList<Long> albumId;
public ArrayList albumName;
public ArrayList songs;
public ArrayList artist;
public ArrayList songsPath;
public ArrayList songsDuration;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
context = this;
populate();
ActionBar actionBar = getSupportActionBar();
LayoutInflater inflator = (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View v = inflator.inflate(R.layout.customactionbar, null);
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setDisplayShowCustomEnabled(true);
actionBar.setDisplayShowTitleEnabled(false);
actionBar.setIcon(R.drawable.ic_launcher);
actionBar.setCustomView(v);
listViewSearch = (ImageButton) findViewById(R.id.listViewSearch);
listViewEditText = (EditText) findViewById(R.id.editText);
actionbarTitle = (TextView) findViewById(R.id.text_left);
listViewSearch.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
actionbarTitle.setVisibility(View.GONE);
listViewEditText.setVisibility(View.VISIBLE);
}
});
final ViewPagerParallax pager = (ViewPagerParallax) findViewById(R.id.pager);
pager.set_max_pages(MAX_PAGES);
pager.setBackgroundAsset(R.drawable.picture);
pager.setAdapter(new my_adapter());
pager.getAdapter().notifyDataSetChanged();
if (savedInstanceState != null) {
num_pages = savedInstanceState.getInt("num_pages");
pager.setCurrentItem(savedInstanceState.getInt("current_page"), false);
}
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt("num_pages", num_pages);
final ViewPagerParallax pager = (ViewPagerParallax) findViewById(R.id.pager);
outState.putInt("current_page", pager.getCurrentItem());
}
private class my_adapter extends PagerAdapter {
#Override
public int getCount() {
return num_pages;
}
#Override
public boolean isViewFromObject(View view, Object o) {
return view == o;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView((View) object);
}
#Override
public Object instantiateItem(final ViewGroup container, final int position) {
View new_view = null;
LayoutInflater inflater = getLayoutInflater();
new_view = inflater.inflate(R.layout.page, null);
songslist = (ListView) new_view.findViewById(R.id.listView);
if (position == 0) {
songslist.setAdapter(new CustomListViewSongs(context, title, artist, songsDuration));
} else if (position == 1) {
songslist.setAdapter(new CustomListViewSongs(context, songsDuration, artist, songsDuration));
} else if (position == 2) {
songslist.setAdapter(new CustomListViewSongs(context, songsPath, artist, songsDuration));
}
listViewEditText.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
ArrayList<String> temp = new ArrayList<String>();
int length = listViewEditText.getText().length();
temp.clear();
for (int t = 0; t < title.size(); t++) {
if (length <= title.get(t).length()) {
if (listViewEditText.getText().toString().equalsIgnoreCase((String) title.get(t).substring(0, length))) {
temp.add(title.get(t));
}
}
}
songslist.setAdapter(new CustomListViewSongs(context, temp, artist, songsDuration));
}
#Override
public void afterTextChanged(Editable s) {
}
});
container.addView(new_view);
Log.e("TAG", "" + position);
return new_view;
}
}
private void populate() {
ArrayList<Long> albumId = new ArrayList<Long>();
ArrayList artist = new ArrayList();
ArrayList title = new ArrayList();
ArrayList album = new ArrayList();
ArrayList songs = new ArrayList();
ArrayList songsPath = new ArrayList();
ArrayList songsDuration = new ArrayList();
String selection = MediaStore.Audio.Media.IS_MUSIC + " != 0";
Cursor cursor;
String[] projection = {
MediaStore.Audio.Media._ID,
MediaStore.Audio.Media.ARTIST,
MediaStore.Audio.Media.TITLE,
MediaStore.Audio.Media.DATA,
MediaStore.Audio.Media.DISPLAY_NAME,
MediaStore.Audio.Media.DURATION,
MediaStore.Audio.Media.ALBUM,
MediaStore.Audio.Media.ALBUM_ID,
MediaStore.Audio.Media.TITLE
};
cursor = this.getContentResolver().query(
MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
projection,
selection,
null,
null);
while (cursor.moveToNext()) {
artist.add(cursor.getString(1));
songsPath.add(cursor.getString(3));
songs.add(cursor.getString(4));
songsDuration.add(cursor.getString(5));
album.add(cursor.getString(6));
albumId.add(cursor.getLong(7));
title.add(cursor.getString(2));
//songUri.add(cursor.getString(3));
}
cursor.close();
this.title = title;
this.albumId = albumId;
this.albumName = album;
this.songs = songs;
//this.songs = title;
this.artist = artist;
this.songsPath = songsPath;
this.songsDuration = songsDuration;
//Collections.sort(this.songs, String.CASE_INSENSITIVE_ORDER);
//Collections.sort(this.albumName, String.CASE_INSENSITIVE_ORDER);
}
}
It would be easier to use Autocomplete textView.