Unable to load images in ViewPager from server [duplicate] - android

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

Related

Image caching using Glide in 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);

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.

debugger showing -> 'this' is not available in onResponse method of volley for Recyclerview

I have this silly problem.
I searched for it but couldn't get any anwser hence I posted it here.
In following fragment I have recyclerview which populate data from server with Post POJO with help of Gson.
I have use similar code many times in my another projects, but today I got an error due to which my recyclerview is not showing values. So I debug code and I got following output which shows 'this' is not available for my recycleview inside onResponse of Volley.
My Fragment class is as follows:
public class Seller_Corner_Tab2 extends Fragment implements PostAdapter.OnItemClickListener {
public static final String TAG = Seller_Corner_Tab2.class.getSimpleName();
RecyclerView recyclerView;
ProgressDialog progressDialog;
AppPreferences preferences;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.seller_corner_tab2,container,false);
preferences = new AppPreferences(getActivity());
recyclerView = (RecyclerView)view.findViewById(R.id.seller_corner_2_rv);
LinearLayoutManager mLinearLayoutManagerVertical = new LinearLayoutManager(getContext()); // (Context context)
mLinearLayoutManagerVertical.setOrientation(LinearLayoutManager.VERTICAL);
recyclerView.setLayoutManager(mLinearLayoutManagerVertical);
progressDialog = new ProgressDialog(getContext());
/*progressDialog.setMessage("Loading your Posts");
progressDialog.setCancelable(false);
progressDialog.show();*/
fetchSellerPosts();
return view;
}
public void fetchSellerPosts() {
final Seller seller = EKrushiKattaApplication.getInstance().getPrefManager().getSeller();
StringRequest strReq = new StringRequest(Request.Method.POST,
EndPoints.GETPOSTBYID, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
ArrayList<Post>templist = new ArrayList<>();
/*progressDialog.hide();*/
try {
GsonBuilder gsonbuilder= new GsonBuilder();
Gson gson=gsonbuilder.create();
Log.e("Response",response);
templist =gson.fromJson(response, new TypeToken<List<Post>>(){}.getType());
}catch (Exception e)
{
e.printStackTrace();
}
recyclerView.setAdapter( new PostAdapter(templist,getContext(),Seller_Corner_Tab2.this));
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
progressDialog.hide();
NetworkResponse networkResponse = error.networkResponse;
Log.e(TAG, "Connection error: " + error.getMessage() + ", code: " + networkResponse);
Toast.makeText(getActivity(), "Volley error: " + error.getMessage(), Toast.LENGTH_SHORT).show();
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<>();
params.put(CommonLib.SELLER_ID,String.valueOf(seller.getSellerId()));
Log.e(TAG, "params: " + params.toString());
return params;
}
};
//Adding request to request queue
EKrushiKattaApplication.getInstance().addToRequestQueue(strReq);
}
#Override
public void onItemClick(Post post) {
}}
My debugger showing me this output
My PostAdapter Class is as follows :
public class PostAdapter extends RecyclerView.Adapter<PostAdapter.ViewHolder>{
private ArrayList<Post> posts;
private Context context;
private OnItemClickListener listener;
public PostAdapter(ArrayList<Post> posts, Context context, OnItemClickListener listener) {
this.posts = posts;
this.context = context;
this.listener = listener;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.item_post, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(final ViewHolder holder, int position) {
if(posts!=null){
final Post post = posts.get(position);
holder.title.setText(post.getPostTitle());
holder.desc.setText(post.getPostDescription());
holder.cost.setText(post.getPostCost());
RequestOptions options = new RequestOptions()
.centerCrop()
// .placeholder(R.drawable.placeholder)
// .error(R.drawable.ic_pic_error)
.priority(Priority.HIGH);
new GlideImageLoader(holder.image,
holder.progressBar).load(EndPoints.BASE_URL+post.getPostImage(),options);
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
listener.onItemClick(post);
}
});
}
}
#Override
public int getItemCount() {
int size=0;
try {
size = posts.size();
} catch (Exception e) {
e.printStackTrace();
}
return size;
}
#Override
public long getItemId(int position) {
return super.getItemId(position);
}
class ViewHolder extends RecyclerView.ViewHolder{
ImageView image;
TextView title,desc,cost;
ProgressBar progressBar;
public ViewHolder(View itemView) {
super(itemView);
image=(ImageView)itemView.findViewById(R.id.post_item_image);
title=(TextView)itemView.findViewById(R.id.post_item_title);
desc=(TextView)itemView.findViewById(R.id.post_item_desc);
cost=(TextView)itemView.findViewById(R.id.post_item_cost);
progressBar=(ProgressBar)itemView.findViewById(R.id.post_item_progressbar);
}
}
public interface OnItemClickListener {
void onItemClick(Post post);
}}
Try this:
1) Pull the data source creation out of the onResponse()
2) Create adapter right after recycler view inflation.
3) In onResponse() fill data source with new data.
4) Call notifyDatasetChanged() in adapter.
public class Seller_Corner_Tab2 extends Fragment implements PostAdapter.OnItemClickListener {
public static final String TAG = Seller_Corner_Tab2.class.getSimpleName();
RecyclerView recyclerView;
ProgressDialog progressDialog;
AppPreferences preferences;
ArrayList<Post>templist = new ArrayList<>();
PostAdapter adapter;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.seller_corner_tab2,container,false);
preferences = new AppPreferences(getActivity());
recyclerView = (RecyclerView)view.findViewById(R.id.seller_corner_2_rv);
LinearLayoutManager mLinearLayoutManagerVertical = new LinearLayoutManager(getContext()); // (Context context)
mLinearLayoutManagerVertical.setOrientation(LinearLayoutManager.VERTICAL);
recyclerView.setLayoutManager(mLinearLayoutManagerVertical);
progressDialog = new ProgressDialog(getContext());
adapter = new PostAdapter(templist,getContext(),this);
recyclerView.setAdapter(adapter);
/*progressDialog.setMessage("Loading your Posts");
progressDialog.setCancelable(false);
progressDialog.show();*/
fetchSellerPosts();
return view;
}
public void fetchSellerPosts() {
final Seller seller = EKrushiKattaApplication.getInstance().getPrefManager().getSeller();
StringRequest strReq = new StringRequest(Request.Method.POST,
EndPoints.GETPOSTBYID, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
ArrayList<Post> newList = new ArrayList();
/*progressDialog.hide();*/
try {
GsonBuilder gsonbuilder= new GsonBuilder();
Gson gson=gsonbuilder.create();
Log.e("Response",response);
templist =gson.fromJson(response, new TypeToken<List<Post>>(){}.getType());
}catch (Exception e)
{
e.printStackTrace();
}
templist.addAll(newList);
adapter.notifyDatasetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
progressDialog.hide();
NetworkResponse networkResponse = error.networkResponse;
Log.e(TAG, "Connection error: " + error.getMessage() + ", code: " + networkResponse);
Toast.makeText(getActivity(), "Volley error: " + error.getMessage(), Toast.LENGTH_SHORT).show();
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<>();
params.put(CommonLib.SELLER_ID,String.valueOf(seller.getSellerId()));
Log.e(TAG, "params: " + params.toString());
return params;
}
};
//Adding request to request queue
EKrushiKattaApplication.getInstance().addToRequestQueue(strReq);
}
#Override
public void onItemClick(Post post) {
}}

How to apply RecycleView in Fragment

I have a fragment, the name is galery. in the fragment galery i'll showing a recycleView that contains name list. but i find an error in this script :
LinearLayoutManager llm = new LinearLayoutManager(this);
and this my full code :
public class galery extends Fragment {
private RecyclerView lvhape;
private RequestQueue requestQueue;
private StringRequest stringRequest;
ArrayList<HashMap<String, String>> list_data;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_galery, container, false);
String url = "http://bls.hol.es/read.php";
lvhape = (RecyclerView) rootView.findViewById(R.id.lvhape);
LinearLayoutManager llm = new LinearLayoutManager(this);
llm.setOrientation(LinearLayoutManager.VERTICAL);
lvhape.setLayoutManager(llm);
requestQueue = Volley.newRequestQueue(galery.this);
list_data = new ArrayList<HashMap<String, String>>();
stringRequest = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d("response", response);
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray jsonArray = jsonObject.getJSONArray("result");
for (int a = 0; a < jsonArray.length(); a++) {
JSONObject json = jsonArray.getJSONObject(a);
HashMap<String, String> map = new HashMap<String, String>();
map.put("id", json.getString("id"));
map.put("nama", json.getString("nama"));
map.put("alamat", json.getString("alamat"));
map.put("poto", json.getString("poto"));
list_data.add(map);
AdapterList adapter = new AdapterList(galery.this, list_data);
lvhape.setAdapter(adapter);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getActivity().getApplicationContext(), error.getMessage(), Toast.LENGTH_SHORT).show();
}
});
requestQueue.add(stringRequest);
return rootView;
}
}
Try This On Fragment Create Adapter And Model Class And RecyclerView in .xml Class.
public class Event extends Fragment {
RecyclerView recyclerView;
private Event_Adapter event_adapter;
public Event_Model event_model;
public static List<Event_Model> list;
RecyclerView.LayoutManager mLayoutManager;
private static final String FETCH_ID = "id";
private static final String FETCH_NAME = "event_type";
private static final String FETCH_MOBILE = "contact";
private static final String FETCH_DATE = "date";
private static final String FETCH_IMAGE = "uri";
public static final String FETCH_DETAIL = "Your Url";
String type,number,date,uri,id;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v= inflater.inflate(R.layout.fragment_event, container, false);
list = new ArrayList<Event_Model>();
recyclerView = (RecyclerView) v.findViewById(R.id.event_recycler);
mLayoutManager = new LinearLayoutManager(getActivity());
recyclerView.setLayoutManager(mLayoutManager);
fetchdetails();
return v;
}
private void fetchdetails(){
StringRequest jor = new StringRequest(Request.Method.POST, FETCH_DETAIL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
/* Toast.makeText(getActivity(),response,Toast.LENGTH_LONG).show();*/
try {
JSONArray ja = new JSONArray(response);
for (int i = 0; i < ja.length(); i++) {
JSONObject jsonObject = ja.getJSONObject(i);
Integer.parseInt(jsonObject.optString("id").toString());
type = jsonObject.getString(FETCH_NAME);
number = jsonObject.getString(FETCH_MOBILE);
date = jsonObject.getString(FETCH_DATE);
uri = jsonObject.getString(FETCH_IMAGE);
id = jsonObject.getString(FETCH_ID);
event_model = new Event_Model(type,number,date,uri,id);
list.add(event_model);
}
} catch (JSONException e) {
e.printStackTrace();
}
event_adapter= new Event_Adapter(getActivity(), list);
recyclerView.setAdapter(event_adapter);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("Volley", "Error");
}
}
);
RetryPolicy retryPolicy=new DefaultRetryPolicy(60000,0,DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
jor.setRetryPolicy(retryPolicy);
VolleySingleton.getInstance(getActivity()).addToRequestQueue(jor);
}
}
I did some changes it works fine in my app try it and if any error occurred mention in comment.
public class GalaryFragment extends Fragment {
private RecyclerView recyclerView;
private List<ProductModel> list1;
private ProductModel productMode;
private ProductAdapter productAdapter;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.frament_galary, container, false);
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
String url = "http://bls.hol.es/read.php";
mRecyclerView = (RecyclerView) view.findViewById(R.id.lvhape);
list1 = new ArrayList<>();
mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity(), LinearLayoutManager.HORIZONTAL, false));
cashbackAdapter = new ProductAdapter(getActivity(), list1);
mRecyclerView2.setAdapter(productAdapter);
final ProgressDialog dialog = new ProgressDialog(getActivity());
dialog.setMessage("Loading......");
dialog.show();
StringRequest stringRequest = new StringRequest(Method.POST, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
//Toast.makeText(getActivity(),response+"",Toast.LENGTH_LONG).show();
try {
JSONArray jsonArray = new JSONArray(response);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
String id = jsonObject.getString("id");
String name = jsonObject.getString("name");
String image = jsonObject.getString("image");
productModel = new ProductModel(id, name, image);
list1.add(productModel);
}
productAdapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("Volley", "Error");
}
});
VolleySingleton.getInstance(getActivity()).addToRequestQueue(stringRequest);
}
}
ProductAdapter code:
public class ProductAdapter extends RecyclerView.Adapter<ProductAdapter.MyViewHolder> {
private List<ProductModel> list;
private Context mContext;
public ProductAdapter(Context mContext, List<ProductModel> list) {
this.mContext = mContext;
this.list=list;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.cardview_galary, parent, false);
return new MyViewHolder(itemView);
}
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
final ProductModel productModel=list.get(position);
holder.name.setText(productModel.getName());
Picasso.with(mContext)
.load(productModel.getImage())
.placeholder(R.mipmap.ic_launcher)
.error(R.mipmap.ic_launcher)
.into(holder.iv);
}
#Override
public int getItemCount() {
return list.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder {
public TextView name;
public ImageView iv;
public MyViewHolder(View view) {
super(view);
name = (TextView) view.findViewById(R.id.name);
iv = (ImageView) view.findViewById(R.id.image);
}
}
}
PoductModel code:
public class ProductModel {
String id;
String name;
String image;
public nameModel(String id, String name, String image) {
this.id = id;
this.name = name;
this.image = image;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getname() {
return name;
}
public void setname(String name) {
this.name = name;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
}
VolleySingleton class:
public class VolleySingleton {
private static VolleySingleton mInstance;
private RequestQueue mRequestQueue;
private ImageLoader mImageLoader;
private static Context mCtx;
private VolleySingleton(Context context) {
mCtx = context;
mRequestQueue = getRequestQueue();
mImageLoader = new ImageLoader(mRequestQueue,
new ImageLoader.ImageCache() {
private final LruCache<String, Bitmap>
cache = new LruCache<String, Bitmap>(20);
#Override
public Bitmap getBitmap(String url) {
return cache.get(url);
}
#Override
public void putBitmap(String url, Bitmap bitmap) {
cache.put(url, bitmap);
}
});
}
public static synchronized VolleySingleton getInstance(Context context) {
if (mInstance == null) {
mInstance = new VolleySingleton(context);
}
return mInstance;
}
public RequestQueue getRequestQueue() {
if (mRequestQueue == null) {
// getApplicationContext() is key, it keeps you from leaking the
// Activity or BroadcastReceiver if someone passes one in.
mRequestQueue = Volley.newRequestQueue(mCtx.getApplicationContext());
}
return mRequestQueue;
}
public <T> void addToRequestQueue(Request<T> req) {
getRequestQueue().add(req);
}
public ImageLoader getImageLoader() {
return mImageLoader;
}
}
try this
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_galery, container, false);
String url = "http://bls.hol.es/read.php";
lvhape = (RecyclerView) getView().findViewById(R.id.lvhape);
LinearLayoutManager llm = new LinearLayoutManager(gallary.getContext());
llm.setOrientation(LinearLayoutManager.VERTICAL);
lvhape.setLayoutManager(llm);
requestQueue = Volley.newRequestQueue(galery.this);
list_data = new ArrayList<HashMap<String, String>>();
stringRequest = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d("response", response);
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray jsonArray = jsonObject.getJSONArray("result");
for (int a = 0; a < jsonArray.length(); a++) {
JSONObject json = jsonArray.getJSONObject(a);
HashMap<String, String> map = new HashMap<String, String>();
map.put("id", json.getString("id"));
map.put("nama", json.getString("nama"));
map.put("alamat", json.getString("alamat"));
map.put("poto", json.getString("poto"));
list_data.add(map);
AdapterList adapter = new AdapterList(galery.this, list_data);
lvhape.setAdapter(adapter);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getActivity().getApplicationContext(), error.getMessage(), Toast.LENGTH_SHORT).show();
}
});
requestQueue.add(stringRequest);
return rootView;
}
onCreate() will be called before onCreateView() methods so getView() will return null
Try like this
public class galery extends Fragment {
private RecyclerView lvhape;
private RequestQueue requestQueue;
private StringRequest stringRequest;
ArrayList<HashMap<String, String>> list_data;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_galery, container, false);
return rootView;
}
public void onViewCreated(View view, Bundle savedInstanceState) {
String url = "http://bls.hol.es/read.php";
lvhape = (RecyclerView) view.findViewById(R.id.lvhape);
LinearLayoutManager llm = new LinearLayoutManager(this);
llm.setOrientation(LinearLayoutManager.VERTICAL);
lvhape.setLayoutManager(llm);
requestQueue = Volley.newRequestQueue(getActivity());
list_data = new ArrayList<HashMap<String, String>>();
stringRequest = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d("response", response);
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray jsonArray = jsonObject.getJSONArray("result");
for (int a = 0; a < jsonArray.length(); a++) {
JSONObject json = jsonArray.getJSONObject(a);
HashMap<String, String> map = new HashMap<String, String>();
map.put("id", json.getString("id"));
map.put("nama", json.getString("nama"));
map.put("alamat", json.getString("alamat"));
map.put("poto", json.getString("poto"));
list_data.add(map);
AdapterList adapter = new AdapterList(galery.this, list_data);
lvhape.setAdapter(adapter);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getActivity().getApplicationContext(), error.getMessage(), Toast.LENGTH_SHORT).show();
}
});
requestQueue.add(stringRequest);
}

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