Image caching using Glide in android - android

I am using Glide to load images in my app. When app launches Home fragment loads in MainActivity in Home fragment I am fetching images in view pager.When I switch between the fragments and come back to Home fragment it takes sometime to load images in view pager why don't it loads images quickly as I am using Caching property provided by Glide.
What I have been doing so far is
Home.java
public class Home extends Fragment{
ViewPager bannerViewPager;
BannerAdapter adapter;
List<BannerModel> banners;
TabLayout tabLayout;
RequestQueue requestQueue;
StringRequest stringRequest;
private static final String URI = "https://www.example.com";
public Home() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_home, container, false);
tabLayout = view.findViewById(R.id.tabLayout);
bannerViewPager = view.findViewById(R.id.bannerViewpager);
tabLayout.setupWithViewPager(bannerViewPager, true);
banners = new ArrayList<>();
loadViewPager();
return view;
}
public void loadViewPager() {
requestQueue = Volley.newRequestQueue(getActivity());
stringRequest = new StringRequest(Request.Method.GET,URI, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONArray jsonArray = new JSONArray(response);
for(int i = 0;i<jsonArray.length();i++){
JSONObject jsonObject = jsonArray.getJSONObject(i);
String loadImages = jsonObject.getString("Image");
BannerModel model = new BannerModel(loadImages);
banners.add(model);
}
adapter = new BannerAdapter(banners,getActivity());
bannerViewPager.setAdapter(adapter);
}catch(JSONException e){
e.printStackTrace();
}
}
},new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
TastyToast.makeText(getActivity(),"Error:"+error.getMessage(),TastyToast.LENGTH_SHORT,TastyToast.ERROR).show();
}
});
requestQueue.add(stringRequest);
}
}
GlideSingleton.java
public class GlideSingleton {
private static GlideSingleton obj;
public RequestOptions options;
private GlideSingleton(){
options = new RequestOptions();
options.diskCacheStrategy(DiskCacheStrategy.AUTOMATIC);
}
public static synchronized GlideSingleton getInstance(){
if(obj == null){
obj = new GlideSingleton();
}
return obj;
}
}
BannerAdapter.java
public class BannerAdapter extends PagerAdapter {
private LayoutInflater layoutInflater;
Context context;
private List<BannerModel> banners;
public BannerAdapter(List<BannerModel> banners,Context context){
this.banners = banners;
this.context = context;
}
#Override
public int getCount() {
return banners.size();
}
#Override
public boolean isViewFromObject(#NonNull View view, #NonNull Object o) {
return view == o;
}
#NonNull
#Override
public Object instantiateItem(#NonNull ViewGroup container, int position) {
layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
assert layoutInflater != null;
View view = layoutInflater.inflate(R.layout.bannerlayout, null);
ImageView offerImage = view.findViewById(R.id.offerImage);
BannerModel model = banners.get(position);
Glide.with(context).load(model.getBannerImage()).apply(GlideSingleton.getInstance().options).into(offerImage);
container.addView(view);
return view;
}
#Override
public void destroyItem(#NonNull ViewGroup container, int position, #NonNull Object object) {
container.removeView((LinearLayout)object);
}
}
Someone please let me know how can I load the images quickly once they get downloaded by network in image view.
Any help will be appreciated.
THANKS

Create new class
class SingletonRequestOptions
{
private static SingletonRequestOptions obj;
public RequestOptions options;
private SingletonRequestOptions () {
options = new RequestOptions();
options.diskCacheStrategy(DiskCacheStrategy.AUTOMATIC);
}
// Only one thread can execute this at a time
public static synchronized SingletonRequestOptions getInstance()
{
if (obj==null)
obj = new SingletonRequestOptions ();
return obj;
}
}
Update your line with this
Glide.with(context).load(model.getBannerImage()).apply(SingletonRequestOptions.getInstance().options).into(offerImage);

Related

How to pass data from Adapter class to TabView Layout?

I am trying to pass data Adapter class to TabView Layout. I have used fragment in tab. I want to pass data from adapter to fragment (fragment class for tab).
________________________________________Adapter Class________________________________________________
package com.livediscount.restaurants.Adapter;
public class LiveContestAdapter extends RecyclerView.Adapter<LiveContestAdapter.MyViewHolder> {
Context context;
List<Contest_Data> contest_data;
public LiveContestAdapter(Context context, List<Contest_Data> contest_data) {
this.context=context;
this.contest_data=contest_data;
}
#NonNull
#Override
public MyViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
context=viewGroup.getContext();
View vh= LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.custom_list_win_iphone,viewGroup,false);
MyViewHolder myViewHolder=new MyViewHolder(vh);
return myViewHolder;
}
#Override
public void onBindViewHolder(#NonNull final LiveContestAdapter.MyViewHolder myViewHolder, final int i) {
final Contest_Data contest_position = contest_data.get(i);
Picasso.with(context).load(contest_data.get(i).getContestImage()).error(R.drawable.damme).placeholder(R.drawable.damme).into(myViewHolder.img);
myViewHolder.remainSlot.setText(contest_data.get(i).getContestTotal_slot());
myViewHolder.ent_fee.setText(contest_data.get(i).getContestEntry_Fee());
myViewHolder.Booked_Slot.setText(contest_data.get(i).getContestBooked());
final String contest_status = contest_data.get(i).getContestStatus();
String previous_contest = contest_data.get(i).getPrevious_contest();
String winner_announce = contest_data.get(i).getWinner_announce();
}
#Override
public int getItemCount() {
return contest_data.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder {
TextView name;
ImageView img;
public MyViewHolder(#NonNull View itemView) {
super(itemView);
//name=itemView.findViewById(R.id.totalslot);
img=itemView.findViewById(R.id.imageView2);
htp = itemView.findViewById(R.id.button2);
remainSlot=itemView.findViewById(R.id.tvTotalSlotNumber);
}
}
}
___________________________________________AppCompactActivity______________________________________
public class PrizeBreakup extends AppCompatActivity {
ImageButton back;
TabLayout tabLayout;
ViewPager viewPager;
String contest_id,contest_name;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_prize_breakup);
back = findViewById(R.id.back_button);
back.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
onBackPressed();
}
});
tabLayout= findViewById(R.id.tabs);
viewPager = findViewById(R.id.container);
PrizeLayoutAdapter adapter = new PrizeLayoutAdapter(getSupportFragmentManager());
adapter.add(new PrizeLayout(),"Prize Breakup");
adapter.add(new WinnerLayout(),"Winners");
viewPager.setAdapter(adapter);
tabLayout.setupWithViewPager(viewPager);
//here
SharedPreferences.Editor editor = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE).edit();
editor.putString("contestid1", "contest_id");
editor.apply();
/* Bundle bundle = getIntent().getExtras();
assert bundle!= null;
contest_id = bundle.getString("contest_id");
contest_name = bundle.getString("contest_name");*/
/* Bundle data = new Bundle();
data.putString("contestid1","contest_id");
Fragment argumentFragment = new PrizeLayout();
argumentFragment.setArguments(data);*/
}
}
_____________________________________PrizeLayout Fragment________________________________________
package com.livediscount.restaurants;
public class PrizeLayout extends Fragment {
List<Contest_Data> contest_data;
LiveContestAdapter live_contest_adapter;
private RecyclerView recyclerView;
TextView ContestId;
public static PrizeLayout newInstance() {
return new PrizeLayout();
}
#Override
public View onCreateView( LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.prize_layout, container, false);
SharedPreferences prefs = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE);
String contestid = getActivity().prefs.getString("contestid1", "contestid not found");
String Contest_id = this.getArguments().getString("edttext");
ContestId= view.findViewById(R.id.referral_code);
ContestId.setText(contestid);
return view;
}
}
________________________________________Winner Fragment______________________________________________
package com.livediscount.restaurants;
public class WinnerLayout extends Fragment {
private List<Winner_data> winner_data=new ArrayList<>();
private RecyclerView recyclerView_winner;
#Override
public View onCreateView(#NonNull LayoutInflater inflater, ViewGroup container , Bundle savedInstanceState)
{
View view = inflater.inflate(R.layout.winner_layout,container,false);
recyclerView_winner = view.findViewById(R.id.Recyclerview_Winner);
if(winner_data!=null)
{
winner_data.clear();
}
Winner_Data();
return view;
}
private void Winner_Data() {
RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());
String url = ("http://livediscounts.in/webservices/User_interface/Winner_List?contest_id=\"+razorpayPaymentID+\"");
StringRequest request = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
//progressBar_contest.setVisibility(View.GONE);
JSONObject jsonObject = new JSONObject(response);
if (jsonObject.getString("status").equals("1")) {
JSONArray jsonArray = jsonObject.getJSONArray("records");
/*for (int i = 0; i < jsonArray.length(); i++) {
JSONObject obj = jsonArray.getJSONObject(i);
Winner_data wd = new Winner_data();
cd.setContestId(obj.getString("id"));
cd.setContestName(obj.getString("name"));
cd.setContestImage(obj.getString("prize_1"));
cd.setContestDescription(obj.getString("description"));
cd.setContestType(obj.getString("type"));
cd.setContestEntry_Fee(obj.getString("entry_fee"));
cd.setContestTotal_slot(obj.getString("total_slot"));
cd.setContestTotal_winner(obj.getString("total_winner"));
cd.setContestPrice_Description(obj.getString("price_description"));
cd.setContestPrize_21(obj.getString("prize_21"));
cd.setContestPrize_22(obj.getString("prize_22"));
cd.setContestPrize_31(obj.getString("prize_31"));
cd.setContestPrize_32(obj.getString("prize_32"));
cd.setContestPrize_41(obj.getString("prize_41"));
cd.setContestPrize_42(obj.getString("prize_42"));
cd.setContestPrize_51(obj.getString("prize_51"));
cd.setContestPrize_52(obj.getString("prize_52"));
cd.setContestPrize_61(obj.getString("prize_61"));
cd.setContestPrize_62(obj.getString("prize_62"));
cd.setContestPrize_71(obj.getString("prize_71"));
cd.setContestPrize_72(obj.getString("prize_72"));
cd.setContestStatus(obj.getString("status"));
cd.setContestContest_Note(obj.getString("contest_note"));
cd.setContestStart_date(obj.getString("start_date"));
cd.setContestEnd_date(obj.getString("end_date"));
cd.setContestBooked(obj.getString("booked_slot"));
winner_data.add(wd);
}*/
/*WinnerAdapter winnerAdapter = new WinnerAdapter(getApplicationContext(), winner_data);
LinearLayoutManager llm = new LinearLayoutManager(getActivity());
llm.setOrientation(LinearLayoutManager.VERTICAL);
recyclerView_winner.setLayoutManager(llm);
recyclerView_winner.setAdapter(winnerAdapter);*/
} else {
// Toast.makeText(getApplicationContext(),"Something went Wrong",Toast.LENGTH_SHORT).show();
}
} catch (Exception ex) {
//progressBar_contest.setVisibility(View.GONE);
//Toast.makeText(getApplicationContext(),"No Data Found",Toast.LENGTH_LONG).show(); ex.printStackTrace();
}
}
}
,
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
//Toast.makeText(getApplicationContext(),"No Internet Connection",Toast.LENGTH_LONG).show();
}
}
);
requestQueue.add(request);
}
}
you can use shared pref using parent activity.

Unable to load images in ViewPager from server [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 4 years ago.
i have view pager defined in my app and i am trying to load images in view pager using volley library. I am doing as follows :
First, i am posting request to the server if response comes True, then i am sending another request in response method to fetch images from the server.
Here is the Error i am getting in log window:
java.lang.NullPointerException: Attempt to invoke virtual method 'com.android.volley.Request com.android.volley.RequestQueue.add(com.android.volley.Request)' on a null object reference
at tiffino.app.com.Home.loadDiscViewPager(Home.java:492)
at tiffino.app.com.Home$1.onResponse(Home.java:302)
at tiffino.app.com.Home$1.onResponse(Home.java:290)
at com.android.volley.toolbox.StringRequest.deliverResponse(StringRequest.java:60)
at com.android.volley.toolbox.StringRequest.deliverResponse(StringRequest.java:30)
at com.android.volley.ExecutorDelivery$ResponseDeliveryRunnable.run(ExecutorDelivery.java:99)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6776)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1496)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1386)
Here is the code i am using:
OfferImageModel.java
public class OfferImageModel {
String Image;
public OfferImageModel(){
}
public OfferImageModel(String image) {
Image = image;
}
public String getImage() {
return Image;
}
public void setImage(String image) {
Image = image;
}
}
Home.java
public class Home extends Fragment{
String str1 = "Ajmer";
ViewPager discImages;
RequestQueue requestQueue, discQueue;
StringRequest stringRequest, discRequest;
private static final String URL = "https://tiffino.herokuapp.com/fetch";
private static final String OFFER_URL = "https://tiffino.herokuapp.com/offers";
List<OfferImageModel> offers;
DiscViewPager adapter;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_home, container, false);
discImages = view.findViewById(R.id.discImages);
offers = new ArrayList<>();
sendLocation(str1);
return view;
}
private void sendLocation(final String str1) {
requestQueue = Volley.newRequestQueue(getActivity());
stringRequest = new StringRequest(Request.Method.POST, URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
if (response.equals("True")) {
loadDiscViewPager();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
HashMap<String, String> map = new HashMap<>();
map.put("name", str1);
return map;
}
};
requestQueue.add(stringRequest);
}
public void loadDiscViewPager() {
discRequest = new StringRequest(Request.Method.POST, OFFER_URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONArray jsonArray = new JSONArray(response);
for (int i = 0; i < jsonArray.length(); i++) {
OfferImageModel model = new OfferImageModel();
JSONObject jsonObject = jsonArray.getJSONObject(i);
String loadImages = jsonObject.getString("Image");
model.setImage(loadImages);
offers.add(model);
}
adapter = new DiscViewPager(getActivity(), offers);
discImages.setAdapter(adapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener()
{
#Override
public void onErrorResponse(VolleyError error) {
}
})
{
#Override
protected Map<String, String> getParams() throws AuthFailureError {
HashMap<String, String> params = new HashMap<>();
params.put("Place",str1);
return params;
}
};
discQueue.add(discRequest);
}
}
DiscViewPager.java
public class DiscViewPager extends PagerAdapter {
private LayoutInflater layoutInflater;
Context context;
private List<OfferImageModel> offers;
public DiscViewPager(Context context, List<OfferImageModel> offers) {
this.context = context;
this.offers = offers;
}
#Override
public int getCount() {
return offers.size();
}
#Override
public boolean isViewFromObject(#NonNull View view, #NonNull Object o) {
return (view == o);
}
#NonNull
#Override
public Object instantiateItem(#NonNull ViewGroup container, int position) {
layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
assert layoutInflater != null;
View view = layoutInflater.inflate(R.layout.custom_offer, null);
ImageView offerImage = view.findViewById(R.id.offerImage);
OfferImageModel model = offers.get(position);
Picasso.with(context).load(model.getImage()).fit().centerInside().into(offerImage);
ViewPager vp = (ViewPager) container;
vp.addView(view, 0);
return view;
}
#Override
public void destroyItem(#NonNull ViewGroup container, int position, #NonNull Object object) {
ViewPager vp = (ViewPager) container;
View view = (View) object;
vp.removeView(view);
}
}
Please let me know what i am doing wrong in above code.
THANKS
You don't seem to be initializing discQueue anywhere, thus the null pointer exception

Volley shows null error when activity loads first time

I have view pager in my android activity and using NodeJs and MongoDb as a back-end service.When my activity starts first time it shows volley error null
and when i stop my app and start it again it loads images in the view pager and works fine.
Why it is not fetching data from the server when activity starts first time.
Here is my code:
MainActivity.java
public class MainActivity extends AppCompatActivity {
ViewPager viewPager;
TabLayout tab;
RequestQueue rq;
List<Model> list;
Adapter adapter;
String request_url = "https://example.com";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
rq = CustomRequest.getInstance(MainActivity.this).getRequestQueue();
viewPager = findViewById(R.id.viewPager);
tab = findViewById(R.id.tabLayout);
list = new ArrayList<>();
tab.setupWithViewPager(viewPager, true);
final ProgressDialog prg = new ProgressDialog(MainActivity.this);
prg.setMessage("Loading");
prg.show();
StringRequest stringRequest = new StringRequest(Request.Method.POST, request_url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
prg.dismiss();
try {
JSONArray jsonArr = new JSONArray(response);
for (int i = 0; i < jsonArr.length(); i++) {
Model model = new Model();
JSONObject jsonObject = jsonArr.getJSONObject(i);
model.setImage(jsonObject.getString("Image"));
list.add(model);
}
adapter = new Adapter((ArrayList<Model>) list, MainActivity.this);
viewPager.setAdapter(adapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
prg.dismiss();
Toast.makeText(getApplicationContext(),""+error.getMessage(),Toast.LENGTH_SHORT).show();
}
}){
#Override
protected Map<String, String> getParams() throws AuthFailureError {
HashMap<String,String> params = new HashMap<>();
params.put("place","Ajmer");
return params;
}
};
CustomRequest.getInstance(MainActivity.this).addToRequetQueue(stringRequest);
}
}
Adapter.java
public class Adapter extends PagerAdapter {
ArrayList<Model> list = new ArrayList<>();
Context context;
LayoutInflater layoutInflater;
public Adapter(ArrayList<Model> list, Context context) {
this.list = list;
this.context = context;
}
#Override
public int getCount() {
return list.size();
}
#Override
public boolean isViewFromObject(#NonNull View view, #NonNull Object o) {
return view == o;
}
#NonNull
#Override
public Object instantiateItem(#NonNull ViewGroup container, final int position) {
layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
assert layoutInflater != null;
View view = layoutInflater.inflate(R.layout.custom, null);
Model model = list.get(position);
ImageView imageView = view.findViewById(R.id.imageView);
Glide.with(context).load(model.getImage()).into(imageView);
ViewPager vp = (ViewPager) container;
vp.addView(view, 0);
return view;
}
#Override
public void destroyItem(#NonNull ViewGroup container, int position, #NonNull Object object) {
container.removeView((LinearLayout)object);
}
}
Please someone let me know why I am getting this issue.
THANKS
Did you initialized RequestQueue. if not please add following code before string request
RequestQueue queue = Volley.newRequestQueue(context);
After that call add queue.add after string request call
queue.add(stringRequest);
If the error still continues...
print response of volley whether its getting null or not.

How to fetch images on ViewPager from server

I want to implement one app for image showing where images will come from server side and there will be maximum 4 images suppose that there are only one or two image on server then the pager will shown extra page or slider like this image.
public class BlankActivity extends FragmentActivity implements View.OnClickListener{
public static final String KEY_PIC = "pic";
public static final String KEY_PIC1 = "pic1";
public static final String KEY_PIC2 = "pic2";
public static final String KEY_PIC3 = "pic3";
public static final String JSON_ARRAY = "result";
String url1="https://www.maangal.com/photos/large_";
public String pic0="";
public String pic1="";
public String pic2="";
public String pic3="";
public String p0="";
public String p1="";
public String p2="";
public String p3="";
private ArrayList<String> ImagesArray = new ArrayList<>();
CustomTextView context;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_blank);
mPager = (ViewPager) findViewById(R.id.pager);
getData();
for slider call init function.
private void init( String p0,String p1,String p2,String p3) {
this.p0 = p0;
this.p1 = p1;
this.p2 = p2;
this.p3 = p3;
String[] IMAGES={p0,p1,p2,p3};
for(int i=0;i<IMAGES.length;i++) {
ImagesArray.add(IMAGES[i]);
if (p0.equalsIgnoreCase("https://www.maangal.com/photos/large_"))
{ Log.e("pic**********", url1 + IMAGES[i]);
mPager.setVisibility(View.GONE);
}
else Log.e("pic_______________", url1 + IMAGES[i]);
}
mPager = (ViewPager) findViewById(R.id.pager);
mPager.setAdapter(new SlidingImage_Adapter(BlankActivity.this,ImagesArray));
CirclePageIndicator indicator = (CirclePageIndicator) findViewById(R.id.indicator);
indicator.setViewPager(mPager);
final float density = getResources().getDisplayMetrics().density;
//Set circle indicator radius
indicator.setRadius(5 * density);
NUM_PAGES = IMAGES.length;
indicator.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageSelected(int position) {
currentPage = position;
}
#Override
public void onPageScrolled(int pos, float arg1, int arg2) {
}
#Override
public void onPageScrollStateChanged(int pos) {
}
});
}
getData function where I used Volley response to fetch the images from server
private void getData() {
tv21.setText(getIntent().getExtras().getString("id"));
id = tv21.getText().toString().trim();
Bundle extras = getIntent().getExtras();
if (extras != null) {
id = extras.getString("ID");
strGender = extras.getString("gender");
} else {
// handle case
}
String detailsURL ="https://www.maangal.com/maangal_mobile/details2.php?id="+id+"&gender="+strGender+"&curr_user_id="+current_Id;
StringRequest stringRequest = new StringRequest(Request.Method.POST,detailsURL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
showJSON(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(BlankActivity.this,error.getMessage().toString(),Toast.LENGTH_LONG).show();
}
});
RequestQueue requestQueue = Volley.newRequestQueue(BlankActivity.this);
requestQueue.add(stringRequest);
}
private void showJSON(String response){
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray result = jsonObject.getJSONArray(Config.JSON_ARRAY);
JSONObject userData = result.getJSONObject(0);
pic0 = userData.getString(KEY_PIC);
pic1 = userData.getString(KEY_PIC1);
pic2 = userData.getString(KEY_PIC2);
pic3 = userData.getString(KEY_PIC3);
init(url1+pic0,url1+pic1,url1+pic2,url1+pic3);
}
SlidingImage_Adapter pager adapter
public class SlidingImage_Adapter extends PagerAdapter {
private ArrayList<String> IMAGES;
private LayoutInflater layoutInflater;
private Context context;
ProgressBar progressBar;
private ImageLoader imageLoader;
SessionManager session;
public String str_gender;
public SlidingImage_Adapter(Context context, ArrayList<String> IMAGES) {
this.context = context;
this.IMAGES=IMAGES;
for(int i=0;i<IMAGES.size();i++)
layoutInflater = LayoutInflater.from(context);
}
#Override
public Object instantiateItem(ViewGroup view, int position) {
layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View item_view = layoutInflater.inflate(R.layout.screen_slide_fragment, view, false);
ImageView imageView = (ImageView) item_view.findViewById(R.id.image);
progressBar=(ProgressBar)item_view.findViewById(R.id.progressBar);
// Session class instance
session = new SessionManager(context);
// get user data from session
HashMap<String, String> user = session.getUserDetails();
str_gender = user.get(SessionManager.KEY_GENDER);
if(str_gender.equalsIgnoreCase("Female")){
Picasso.with(context)
.load(IMAGES.get(position))
.error(R.drawable.girl)
.placeholder(R.drawable.girl)
.fit()
.into(imageView);
view.addView(item_view);
}
else{
Picasso.with(context)
.load(IMAGES.get(position))
.error(R.drawable.boy)
.placeholder(R.drawable.boy)
.into(imageView);
view.addView(item_view);
}
return item_view;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView((View) object);
}
#Override
public int getCount() {
return IMAGES.size();
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view.equals(object);
}
#Override
public void restoreState(Parcelable state, ClassLoader loader) {
}
#Override
public Parcelable saveState(){
return null;
}
}
You need to check if other URLs are blank then you don't need to add into Array of Image. Change your code with below code and check.
String[] IMAGES={p0,p1,p2,p3};
for(int i=0;i<IMAGES.length;i++) {
if(!IMAGES[i].isEmpty()) {
ImagesArray.add(IMAGES[i]);
}
if (p0.equalsIgnoreCase("https://www.maangal.com/photos/large_"))
{
Log.e("pic**********", url1 + IMAGES[i]);
mPager.setVisibility(View.GONE);
}
}
I have done it, if there is images then the array will ImagesArray.add(url1 + IMAGES[i]); and if there is no images nothing will add on arrayList
String[] IMAGES = {p0, p1, p2, p3};
for (int i = 0; i < IMAGES.length; i++) {
if (IMAGES[i].equalsIgnoreCase("") || IMAGES[i].equalsIgnoreCase("nophoto.jpg") || IMAGES[i].equalsIgnoreCase("https://www.maangal.com/photos/large_")) {
Log.e("piccc-----------", IMAGES[i]);
} else {
ImagesArray.add(url1 + IMAGES[i]);
Log.e("else", url1 + IMAGES[i]);
}
}

use same recyclerview adapter with different layout

I've a recyclerview adapter with 3 textviews. I used a model class to set texts. Now I want to use the same adapter with different layout and in a different class which only have 1 textview. When I tried, I got NullPointerException (may be becuz the other 2 textviews are blank). Is there any way to use same adapter with different layout and in different class?
// second class - I used 1 textview
public class Customers extends AppCompatActivity{
private CShowProgress cShowProgress;
private RecyclerView mRecyclerView;
private TimeLineAdapter mTimeLineAdapter;
private List<TimeLineModel> mDataList = new ArrayList<>();
private static final String CUSTOMERS = "http://192.168.200.3/ubooktoday/android/showspacustomerlist";
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.customers);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
cShowProgress = CShowProgress.getInstance();
mRecyclerView = (RecyclerView) findViewById(R.id.recyclerView);
mRecyclerView.setLayoutManager(getLinearLayoutManager());
mRecyclerView.setHasFixedSize(true);
showCustomers();
}
private void showCustomers() {
if(mDataList!=null )mDataList.clear();
cShowProgress.showProgress(Customers.this);
StringRequest stringRequest = new StringRequest(Request.Method.POST, CUSTOMERS,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
cShowProgress.hideProgress();
try {
JSONArray jsonArray = new JSONArray(response);
for(int i=0; i<jsonArray.length(); i++){
JSONObject obj = jsonArray.getJSONObject(i);
TimeLineModel model = new TimeLineModel();
model.setCustname(obj.getString("customername"));
mDataList.add(model);
mTimeLineAdapter = new TimeLineAdapter(getApplicationContext(), R.layout.item_row_customer, mDataList);
mRecyclerView.setAdapter(mTimeLineAdapter);
}
mTimeLineAdapter.notifyDataSetChanged();
} catch (JSONException e) {
// JSON error
e.printStackTrace();
Toast.makeText(getApplicationContext(), "Json error: " + e.getMessage(), Toast.LENGTH_LONG).show();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(), "VolleyError" + error.toString(), Toast.LENGTH_LONG).show();
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("spaid", "145");
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());
requestQueue.add(stringRequest);
}
private LinearLayoutManager getLinearLayoutManager() {
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getApplicationContext());
return linearLayoutManager;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
onBackPressed();
break;
}
return true;
}
}
// first class - I used all 3 textviews
public class Walkin extends Fragment{
private RecyclerView mRecyclerView;
private TimeLineAdapter mTimeLineAdapter;
private List<TimeLineModel> mDataList = new ArrayList<>();
private static final String DASHBOARD = "My API";
#Nullable
#Override
#Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.walkin, container, false);
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
mRecyclerView = (RecyclerView) view.findViewById(R.id.recyclerView);
mRecyclerView.setLayoutManager(getLinearLayoutManager());
mRecyclerView.setHasFixedSize(true);
showDashboard();
}
private void showDashboard() {
if(mDataList!=null )mDataList.clear();
cShowProgress.showProgress(getActivity());
StringRequest stringRequest = new StringRequest(Request.Method.POST, DASHBOARD,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray jsonArray = jsonObject.getJSONArray("walkinlist");
for(int i=0; i<jsonArray.length(); i++){
JSONObject obj = jsonArray.getJSONObject(i);
TimeLineModel model = new TimeLineModel();
model.setCustname(obj.getString("customername"));
model.setTime(obj.getString("serviceDuration"));
model.setServname(obj.getString("service"));
mDataList.add(model);
mTimeLineAdapter = new TimeLineAdapter(getActivity(), R.layout.item_row_dashboard, mDataList);
mRecyclerView.setAdapter(mTimeLineAdapter);
}
mTimeLineAdapter.notifyDataSetChanged();
} catch (JSONException e) {
// JSON error
e.printStackTrace();
Toast.makeText(getActivity(), "Json error: " + e.getMessage(), Toast.LENGTH_LONG).show();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getActivity(), "VolleyError" + error.toString(), Toast.LENGTH_LONG).show();
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("spaid", "145");
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(getActivity());
requestQueue.add(stringRequest);
}
private LinearLayoutManager getLinearLayoutManager() {
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity());
return linearLayoutManager;
}
}
// Adapter class
public class TimeLineAdapter extends RecyclerView.Adapter<TimeLineViewHolder> {
private List<TimeLineModel> mFeedList;
int resource;
private Context mContext;
public TimeLineAdapter(Context mContext, int resource, List<TimeLineModel> feedList) {
this.resource = resource;
this.mContext = mContext;
mFeedList = feedList;
}
#Override
public TimeLineViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = View.inflate(parent.getContext(), resource, null);
return new TimeLineViewHolder(view, viewType);
}
#Override
public void onBindViewHolder(TimeLineViewHolder holder, int position) {
TimeLineModel timeLineModel = mFeedList.get(position);
holder.servicename.setText(timeLineModel.getServname());
holder.custname.setText(timeLineModel.getCustname());
holder.time.setText(timeLineModel.getTime());
}
#Override
public int getItemCount() {
return (mFeedList!=null? mFeedList.size():0);
}
}
// ViewHolder class
public class TimeLineViewHolder extends RecyclerView.ViewHolder {
public TextView servicename, custname, time;
public TimeLineViewHolder(View itemView, int viewType) {
super(itemView);
servicename = (TextView) itemView.findViewById(R.id.tv_service);
custname = (TextView) itemView.findViewById(R.id.tv_cust);
time = (TextView) itemView.findViewById(R.id.tv_time);
}
}
You can use the getItemViewType().
Make your adapter(here TimeLineAdapter) extend RecyclerView.Adapter only.
You can change the Adapter's constructer to recieve ItemType and use it in the getItemViewType
Override the int getItemViewType (int position) method in your adapter.
In the onCreateViewHolder you can differentiate between which layout you want to inflate by using the viewType parameter.
In onBindViewHolder use instanceof to check which ViewHolder was created and call the related bind functions
A Sample Code-
// Adapter class
public class TimeLineAdapter extends RecyclerView.Adapter{
.....
int type;
public TimeLineAdapter(Context mContext, int resource, List<TimeLineModel> feedList,int layoutType) {
.....
.....
type=layoutType;
}
#Override
public int getItemViewType(int position) {
return type;
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
if(viewType==1){
View view = View.inflate(parent.getContext(), resource, null);
return new TimeLineViewHolder(view, viewType);
}else{
View view = View.inflate(parent.getContext(), resource, null);
return new TimeLineViewHolder2(view, viewType);
}
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
if(holder instanceof TimeLineViewHolder){
TimeLineModel timeLineModel = mFeedList.get(position);
((TimeLineViewHolder) holder).servicename.setText(timeLineModel.getServname());
......
}
else if(holder instanceof TimeLineViewHolder2){
....
....
}
}
#Override
public int getItemCount() {
return (mFeedList!=null? mFeedList.size():0);
}
}

Categories

Resources