Looping through ViewPager Images Android - android

I am developing an android app where I use viewpager to show some images from a rest api. These Api has lots of images in json format. I only want to show the the first 8 or 10 images into viewpager. But I am not getting the correct way to loop throug the images. Here is my code for view pager.
private static ViewPager viewPager;
private static int currentPage = 0;
private List<NewsModel> imageList=new ArrayList<>( );
private ViewPagerAdapter adapter;
private NewsController mController;
private Timer swipeTimer;
private Handler handler;
private Runnable Update;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.option_main_fragment, container, false);
viewPager = view.findViewById(R.id.pager);
adapter=new ViewPagerAdapter( this.getActivity(),imageList );
CircleIndicator indicator = (CircleIndicator) view.findViewById(R.id.indicator);
viewPager.setAdapter(adapter);
indicator.setViewPager(viewPager);
adapter.registerDataSetObserver(indicator.getDataSetObserver());
mController = new NewsController(this);
mController.startFetching();
return view;
}
#Override
public void onResume() {
// Auto start of viewpager
handler = new Handler();
Update= new Runnable() {
public void run() {
if (currentPage == imageList.size()) {
currentPage = 0;
}
viewPager.setCurrentItem(currentPage++, true);
System.out.println(viewPager.getCurrentItem());
}
};
swipeTimer = new Timer();
swipeTimer.schedule(new TimerTask() {
#Override
public void run() {
handler.post(Update);
}
},2000,5000);
super.onResume();
}
#Override
public void onPause() {
swipeTimer.cancel();
super.onPause();
}
Edited Code This is the code for fetching json data
public class NewsController {
private static final String TAG = NewsController.class.getSimpleName();
private UserCallbackListener mListener;
private NewsRestApiManager mApiManager;
private AppImage appImages;
Realm news_realm;
ArrayList<String> title_list = new ArrayList<>();
GlobalClass globalClass = new GlobalClass();
public NewsController(UserCallbackListener listener) {
mListener = listener;
mApiManager = new NewsRestApiManager();
}
public void startFetching(){
news_realm = Realm.getDefaultInstance();
mApiManager.getNewsApi().getNews(new Callback<String>() {
#Override
public void success(String s, Response response) {
Log.d(TAG, "JSON :: " + s);
try {
JSONArray array = new JSONArray(s);
for(int i = 0; i < array.length(); i++) {
JSONObject jsonObject = array.getJSONObject(i);
NewsModel news = new NewsModel();
news.setTitle( jsonObject.optString( "title") );
news.setBody( jsonObject.optString( "body" ) );
news.setUpdatedAt( jsonObject.getString( "updated_at" ) );
ArrayList<AppImage> list = new ArrayList();
JSONArray imageArray =jsonObject.getJSONArray("appImages");
if (imageArray.length() > 1) {
for(int j=0; j<imageArray.length();j++){
appImages = new AppImage();
try {
appImages.setSrc( new JSONArray( s ).getJSONObject( i ).getJSONArray( "appImages" ).getJSONObject( j ).optString( "src" ) );
}catch (JSONException e){
e.printStackTrace();
}
list.add(appImages);
}
}
news.setAppImages( list );
TeaserImageSmall coverImage=new TeaserImageSmall();
try {
coverImage.setSrc( jsonObject.getJSONObject("teaserImageSmall").optString("src"));
news.setTeaserImageSmall(coverImage);
} catch (JSONException e) {
Log.d(TAG, "News image could not be loaded for: " + news.getTitle());
}
mListener.onFetchProgressNews(news);
}
} catch (JSONException e) {
mListener.onFetchFailed();
}
mListener.onFetchComplete();
}
#Override
public void failure(RetrofitError error) {
Log.d(TAG, "Error :: " + error.getMessage());
mListener.onFetchComplete();
}
});
}
public interface UserCallbackListener{
void onFetchProgressNews(NewsModel news);
void onFetchComplete();
void onFetchFailed();
}
}
Adapter Class
public class ViewPagerAdapter extends PagerAdapter{
private List<NewsModel> imageList;
private LayoutInflater layoutInflater;
private Context context;
public ViewPagerAdapter(Context context, List<NewsModel> imageList) {
this.context = context;
this.imageList=imageList;
}
#Override
public int getCount() {
return imageList.size();
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view==object;
}
#Override
public Object instantiateItem(ViewGroup view, int position) {
layoutInflater=(LayoutInflater) context.getSystemService( Context.LAYOUT_INFLATER_SERVICE );
View itemView = layoutInflater.inflate(R.layout.sliding_img_layout, view, false);
final NewsModel imageFromNews=imageList.get( position );
ImageView myImage = itemView.findViewById(R.id.sliding_image);
Picasso.with(itemView.getContext()).load(imageFromNews.getTeaserImageSmall().getSrc()).into( myImage );
view.addView(itemView, 0);
myImage.setOnClickListener( new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i=new Intent(context,DetailNews.class);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
i.putExtra("src",imageFromNews.getTeaserImageSmall().getSrc());
i.putExtra("title",imageFromNews.getTitle());
i.putExtra("body",imageFromNews.getBody());
context.startActivity(i);
}
} );
return itemView;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView((View) object);
}
}

I guess you can change the code as below
ArrayList<AppImage> list = new ArrayList();
JSONArray imageArray =jsonObject.getJSONArray("appImages");
if (imageArray.length() > 1) {
for(int j=0; j<imageArray.length() && j < 8;j++) { // Added condition j < 8
appImages = new AppImage();
try {
appImages.setSrc( new JSONArray( s ).getJSONObject( i ).getJSONArray( "appImages" ).getJSONObject( j ).optString( "src" ) );
}catch (JSONException e){
e.printStackTrace();
}
list.add(appImages);
}
}
news.setAppImages( list );
there are other ways to do this as well
you can fix viewpager item count
#Override
public int getCount() {
return imageList.size() <= 8? imageList.size():8;
}

Related

How to fetch image in slide viewPager in android by using volley

API File
METHOD : POST
PARAMETER TO PASS:
INPUT:
OUTPUT:
{
"status": true,
"result": {
"sliderImg": [
{
"slidername": "slider 1",
"imagename": "http://192.168.1.80/slider/slider1.jpg"
},
{
"slidername": "slider 2",
"imagename": "http://192.168.1.80/slider/slider2.jpg"
},
],
"categoryImg": [
{
"cat_id": "1",
"cat_name": "Automotive Battery chargers",
"image_name": "http://192.168.1.80/cat/Automotive.png.png"
},
{
"cat_id": "2",
"cat_name": "CVCC Chargers",
"image_name": "http://192.168.1.80/cat/CVCC_Charger.png"
}
]
},
"message": "Get Dashboard successfully!"
}
Model Class
public class MyPojo
{
private String message;
private Result result;
private String status;
public String getMessage ()
{
return message;
}
public void setMessage (String message)
{
this.message = message;
}
public Result getResult ()
{
return result;
}
public void setResult (Result result)
{
this.result = result;
}
public String getStatus ()
{
return status;
}
public void setStatus (String status)
{
this.status = status;
}
#Override
public String toString()
{
return "ClassPojo [message = "+message+", result = "+result+", status = "+status+"]";
}
}
public class Result
{
private SliderImg[] sliderImg;
private CategoryImg[] categoryImg;
public SliderImg[] getSliderImg ()
{
return sliderImg;
}
public void setSliderImg (SliderImg[] sliderImg)
{
this.sliderImg = sliderImg;
}
public CategoryImg[] getCategoryImg ()
{
return categoryImg;
}
public void setCategoryImg (CategoryImg[] categoryImg)
{
this.categoryImg = categoryImg;
}
#Override
public String toString()
{
return "ClassPojo [sliderImg = "+sliderImg+", categoryImg = "+categoryImg+"]";
}
}
public class CategoryImg
{
private String cat_id;
private String image_name;
private String cat_name;
public String getCat_id ()
{
return cat_id;
}
public void setCat_id (String cat_id)
{
this.cat_id = cat_id;
}
public String getImage_name ()
{
return image_name;
}
public void setImage_name (String image_name)
{
this.image_name = image_name;
}
public String getCat_name ()
{
return cat_name;
}
public void setCat_name (String cat_name)
{
this.cat_name = cat_name;
}
#Override
public String toString()
{
return "ClassPojo [cat_id = "+cat_id+", image_name = "+image_name+", cat_name = "+cat_name+"]";
}
}
public class SliderImg
{
private String slidername;
private String imagename;
public String getSlidername ()
{
return slidername;
}
public void setSlidername (String slidername)
{
this.slidername = slidername;
}
public String getImagename ()
{
return imagename;
}
public void setImagename (String imagename)
{
this.imagename = imagename;
}
#Override
public String toString()
{
return "ClassPojo [slidername = "+slidername+", imagename = "+imagename+"]";
}
}
Adapter Class
public class ViewPagerAdapter extends PagerAdapter {
private Context context;
private LayoutInflater layoutInflater;
private List<SliderImg> sliderImg;
private ImageLoader imageLoader;
public ViewPagerAdapter(List sliderImg, Context context) {
this.sliderImg = sliderImg;
this.context = context;
}
#Override
public int getCount() {
return sliderImg.size();
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == object;
}
#Override
public Object instantiateItem(ViewGroup container, final int position) {
layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = layoutInflater.inflate(R.layout.dashboard_slide_layout, null);
SliderImg utils = sliderImg.get(position);
ImageView imageView = (ImageView) view.findViewById(R.id.dash_img_slider_view);
imageLoader = CustomVolleyRequest.getInstance(context).getImageLoader();
imageLoader.get(utils.getImagename(), ImageLoader.getImageListener(imageView, R.mipmap.ic_launcher, android.R.drawable.ic_dialog_alert));
view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (position == 0) {
Toast.makeText(context, "Slide 1 Clicked", Toast.LENGTH_SHORT).show();
} else if (position == 1) {
Toast.makeText(context, "Slide 2 Clicked", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(context, "Slide 3 Clicked", Toast.LENGTH_SHORT).show();
}
}
});
ViewPager vp = (ViewPager) container;
vp.addView(view, 0);
return view;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
ViewPager vp = (ViewPager) container;
View view = (View) object;
vp.removeView(view);
}
}
Custom Volly Request Class
public class CustomVolleyRequest {
private static CustomVolleyRequest customVolleyRequest;
private static Context context;
private RequestQueue requestQueue;
private ImageLoader imageLoader;
private CustomVolleyRequest(Context context){
this.context = context;
this.requestQueue = getRequestQueue();
imageLoader = new ImageLoader(requestQueue, 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 CustomVolleyRequest getInstance(Context context){
if(customVolleyRequest == null){
customVolleyRequest = new CustomVolleyRequest(context);
}
return customVolleyRequest;
}
public RequestQueue getRequestQueue(){
if(requestQueue == null){
Cache cache = new DiskBasedCache(context.getCacheDir(), 10 * 1024 * 1024);
Network network = new BasicNetwork(new HurlStack());
requestQueue = new RequestQueue(cache, network);
requestQueue.start();
}
return requestQueue;
}
public void addToRequestQueue(Request req) {
getRequestQueue().add(req);
}
public ImageLoader getImageLoader(){
return imageLoader;
}
}
MainActivity
ViewPager viewPager;
LinearLayout sliderDotspanel;
private int dotscount;
private ImageView[] dots;
RequestQueue rq;
List<SliderImg> sliderImg;
ViewPagerAdapter viewPagerAdapter;
String request_url = " http://192.168.1.80/appapi/dashboard";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
rq = CustomVolleyRequest.getInstance(this).getRequestQueue();
sliderImg = new ArrayList<>();
viewPager = (ViewPager) findViewById(R.id.dash_pager_introduction);
sliderDotspanel = (LinearLayout) findViewById(R.id.dash_view_pager_count_dots);
sendRequest();
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].setImageDrawable(ContextCompat.getDrawable(getApplicationContext(), R.drawable.non_selected_item_dot));
}
dots[position].setImageDrawable(ContextCompat.getDrawable(getApplicationContext(), R.drawable.selected_item_dot));
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
/*
* Initiatization of views
* */
initializingViews();
}
private void sendRequest() {
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Request.Method.POST, request_url, null, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
for(int i = 0; i < response.length(); i++){
SliderImg sliderUtils = new SliderImg();
try {
JSONObject jsonObject = response.getJSONObject(i);
sliderUtils.setImagename(jsonObject.getString("imagename"));
} catch (JSONException e) {
e.printStackTrace();
}
sliderImg.add(sliderUtils);
}
viewPagerAdapter = new ViewPagerAdapter(sliderImg, MainActivity.this);
viewPager.setAdapter(viewPagerAdapter);
dotscount = viewPagerAdapter.getCount();
dots = new ImageView[dotscount];
for(int i = 0; i < dotscount; i++){
dots[i] = new ImageView(MainActivity.this);
dots[i].setImageDrawable(ContextCompat.getDrawable(getApplicationContext(), R.drawable.non_selected_item_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(getApplicationContext(), R.drawable.selected_item_dot));
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
CustomVolleyRequest.getInstance(this).addToRequestQueue(jsonArrayRequest);
}
I am trying to fetch images in ViewPager Sliderby using volley but getting some problem. Above I have given the complete code. In MainActivity after setting viewPager slider calling the sendRequest method by using volley request. I dont know how to fetch the image in Slider through Volley. Please help me guys.
Use Picasso
implementation 'com.squareup.picasso:picasso:2.5.2'
the above Library add build.gradle
Picasso.with(getApplicationContext()).load(utils.getImagename()).placeholder(R.mipmap.ic_launcher).into(imageView );

How to get size of a particular variable from Model class in Android?

I have a model class:
public class Home_Model_ViewPager {
public String buttonLink;
public String tipsDescription;
public String tipsButton;
public Context context;
public Home_Model_ViewPager( Context context, String tipsDescription, String tipsButton, String buttonLink) {
this.context = context;
this.tipsDescription = tipsDescription;
this.tipsButton = tipsButton;
this.buttonLink = buttonLink;
}
public String getButtonLink() {
return buttonLink;
}
public void setButtonLink(String buttonLink) {
this.buttonLink = buttonLink;
}
public String getTipsDescription() {
return tipsDescription;
}
public void setTipsDescription(String tipsDescription) {
this.tipsDescription = tipsDescription;
}
public String getTipsButton() {
return tipsButton;
}
public void setTipsButton(String tipsButton) {
this.tipsButton = tipsButton;
}
}
I have used this model class to use it in viewpager adapter.
So, I am using a recyclerview and setting data to it. Now I have a problem that I have a viewpager in recycleritem. I want to return the size of viewpager adapter of any element in Home_Model_ViewPager as each element has diff size.
This is what I tried in ViewPagerAdapter:
public class ViewPagerAdapter extends PagerAdapter {
// Declare Variables
Context context;
LayoutInflater inflater;
List<Home_Model_ViewPager> totalList;
public ViewPagerAdapter(Context context, List<Home_Model_ViewPager> totalList) {
this.context = context;
this.totalList = totalList;
inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return totalList.size();
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == object;
}
#Override
public Object instantiateItem(ViewGroup container, final int position) {
// Declare Variables
TextView tricksDescription;
Button tricksButton;
View itemView = inflater.inflate(R.layout.viewpager_item, container,
false);
tricksDescription = itemView.findViewById(R.id.xtv_tricks_description);
tricksButton = itemView.findViewById(R.id.tricks_button);
tricksDescription.setText(Html.fromHtml(totalList.get(position).getTipsDescription()));
tricksButton.setText(Html.fromHtml(totalList.get(position).getTipsButton()));
tricksButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
try {
Intent intent = new Intent(Intent.ACTION_VIEW);
String url = totalList.get(position).getButtonLink();
intent.setData(Uri.parse(url));
startActivity(intent);
}
catch (Exception e) {
e.printStackTrace();
}
}
});
container.addView(itemView);
return itemView;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
View view = (View) object;
container.removeView(view);
}
}
I am using volley to get the values as JSON..
private void Home() {
try {
if (getActivity()!=null)
Commonfunctions.LoadPreferences(getActivity());
System.out.println("Authtoken:" + Commonfunctions.Token_key);
appservice.View_All_Events(Commonfunctions.Token_key, String.valueOf(pagenumber), new Server_Callback() {
#Override
public void onSuccess(String response) {
System.out.println("HOME Response :" + response);
try {
JSONObject signObject = new JSONObject(response);
String resStatus = signObject.getString(AppConstants.STATUS);
String resCode = signObject.getString(AppConstants.CODE);
String resMsg = signObject.getString(AppConstants.MSG);
if (resCode.equals(AppConstants.SUCCESS_CODE)) {
JSONArray allEvents = signObject.getJSONArray("all");
System.out.println("INNER Response :" + allEvents);
for (int i = 0; i < allEvents.length(); i++) {
JSONObject innerObj1 = allEvents.getJSONObject(i);
String backgroundImg = innerObj1.getString("backg_img");
String declinedCount = innerObj1.getString("decli_count");
String acceptedCount = innerObj1.getString("accep_count");
String invitedCount = innerObj1.getString("invi_count");
String messages = innerObj1.getString("i_chat");
String name = innerObj1.getString("name");
String eventTime = innerObj1.getString("duration");
String userPhoto = innerObj1.getString("photo");
JSONArray viewpagerEvents = innerObj1.getJSONArray("action");
for (int u = 0; u < viewpagerEvents.length(); u++) {
JSONObject innerObj3 = viewpagerEvents.getJSONObject(u);
String buttonText = innerObj3.getString("text");
String tipsDesc = innerObj3.getString("action_text");
String buttonLink = innerObj3.getString("button_link");
final Home_Model home_data = new Home_Model(name, messages,invitedCount,declinedCount,acceptedCount,eventTime,
userPhoto,backgroundImg);
data.add(home_data);
final Home_Model_ViewPager home_viewpager = new Home_Model_ViewPager(getContext(),tipsDesc,buttonText, buttonLink);
viewPagerData.add(home_viewpager);
}
}
adapter = new HomeAdapter(getContext(),data);
pagerAdapter = new ViewPagerAdapter(getActivity(), viewPagerData);
home_recycler.setAdapter(adapter);
adapter.notifyDataSetChanged();
if (adapter.getItemCount()==0) {
noeventLayout.setVisibility(View.VISIBLE);
}
else {
noeventLayout.setVisibility(View.GONE);
}
} else if (resCode.equals(AppConstants.UPDATE_CODE)) {
//Version_Update versionUpdate=new Version_Update(SignIn.this,response);
} else {
getActivity().getWindow().clearFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE);
Commonfunctions.showerrorsnackbar(resMsg, getActivity(), parentLayout);
}
} catch (JSONException e) {
e.printStackTrace();
}
}//on success close
});//server callback closed
} catch (Exception e) {
e.printStackTrace();
}
}
HomeAdapter:
class HomeAdapter extends RecyclerView.Adapter<HomeAdapter.ViewHolder> {
Context context;
List<Home_Model> students;
public HomeAdapter(Context context,List<Home_Model> students) {
this.context = context;
this.students = students;
}
#Override
public HomeAdapter.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.event_home_list, viewGroup, false);
return new HomeAdapter.ViewHolder(view);
}
#Override
public void onBindViewHolder(final HomeAdapter.ViewHolder holder, final int position) {
holder.title.setText(students.get(position).getName());
holder.invited.setText(students.get(position).getInvited());
holder.accepted.setText(students.get(position).getAccept());
holder.declined.setText(students.get(position).getDecline());
holder.eventTime.setText(students.get(position).getEvent_time());
holder.messages.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivity(new Intent(getActivity(),Chat_view.class));
}
});
holder.viewPager.setAdapter(pagerAdapter);
holder.dots = new ImageView[holder.dotsCount];
for (int i = 0; i < holder.dotsCount; i++) {
holder.dots[i] = new ImageView(context);
holder.dots[i].setImageDrawable(ContextCompat.getDrawable(context, R.drawable.ic_dot_gray ));
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
params.setMargins(8, 0, 8, 0);
holder.sliderDots.addView(holder.dots[i], params);
}
holder.dots[0].setImageDrawable(ContextCompat.getDrawable(context, R.drawable.ic_dot_colorprimary));
holder.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 < holder.dotsCount; i++) {
holder.dots[i].setImageDrawable(ContextCompat.getDrawable(context, R.drawable.ic_dot_gray));
}
holder.dots[position].setImageDrawable(ContextCompat.getDrawable(context, R.drawable.ic_dot_colorprimary));
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
if (students.get(position).getMessages().contentEquals("false")) {
holder.status.setVisibility(View.INVISIBLE);
}
else {
holder.status.setVisibility(View.VISIBLE);
}
holder.status.setVisibility(View.INVISIBLE);
try {
Glide.with(getActivity()).load(students.get(position).getProimg()).into(holder.pro_img);
Glide.with(getActivity()).load(students.get(position).getBgimg()).into(holder.card_main);
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public int getItemCount() {
return students.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
TextView title, messages, invited, accepted, declined, eventTime;
private PorterShapeImageView pro_img;
ImageView card_main, status;
ViewPager viewPager;
LinearLayout sliderDots;
private ImageView[] dots;
private int dotsCount;
public ViewHolder(View itemView) {
super(itemView);
title = itemView.findViewById(R.id.xtv_welcome);
messages = itemView.findViewById(R.id.xtv_message);
invited = itemView.findViewById(R.id.xtv_invited);
accepted = itemView.findViewById(R.id.xtv_accepted);
declined = itemView.findViewById(R.id.xtv_decline);
eventTime = itemView.findViewById(R.id.contact_number);
pro_img = itemView.findViewById(R.id.pro_pic);
card_main = itemView.findViewById(R.id.card_main);
status = itemView.findViewById(R.id.incoming_image);
viewPager = itemView.findViewById(R.id.viewPagerTips);
sliderDots = itemView.findViewById(R.id.sliderDots);
dotsCount = pagerAdapter.getCount();
}
}
}
Please try to make one different array list for your viewpager's adapter:
ArrayList<Home_Model_ViewPager> tempList = new ArrayList<>();
for(int k=0;k<viewpagerData.size();k++){
Home_Model_ViewPager object = viewPagerData.get(k);
if(object.getTripDesc()!=null && object.getTripDesc().length() >0){
tempList.add(object);
}
}
ViewPagerAdapter pagerAdapter = new ViewPagerAdapter(getActivity(), tempList);
home_recycler.setAdapter(adapter);
adapter.notifyDataSetChanged();

Volley, SwipeToRefresh and notifyDataSetChanged() not working

I fetch the data from my Server with Volley and put the data inside a GridView.
Now when I use swipeToRefresh, it should load the new/changed data. For this I tried everything but nothing worked.
First my code:
MainActivity.java
public class MainActivity extends AppCompatActivity {
List<getter_setter> list = new ArrayList<>();
grid_adapter grid_adapter;
GridView gridView;
SwipeRefreshLayout swipeRefreshLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
swipeRefreshLayout = findViewById(R.id.swipeRefresh);
getData();
gridView = findViewById(R.id.gridView);
grid_adapter = new grid_adapter(getApplicationContext(),list);
gridView.setAdapter(grid_adapter);
swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
getData();
grid_adapter.update(list);
swipeRefreshLayout.setRefreshing(false);
}
});
}
public void getData(){
final String url = "http://*.**.***.***/";
final RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray jsonArray = response.getJSONArray("userdata");
for(int i = 0; i < jsonArray.length(); i++){
JSONObject jsonObject = jsonArray.getJSONObject(i);
String NAME = jsonObject.getString("NAME");
String BILD = jsonObject.getString("VORSCHAUBILD");
getter_setter getter_setter = new getter_setter(NAME,"",BILD);
list.add(getter_setter);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
requestQueue.add(jsonObjectRequest);
}
}
And the BaseAdapter
public class grid_adapter extends BaseAdapter{
Context context;
List<getter_setter> list;
public grid_adapter(Context context, List<getter_setter> list) {
this.context = context;
this.list = list;
}
#Override
public int getCount() {
return list.size();
}
#Override
public Object getItem(int i) {
return list.get(i);
}
#Override
public long getItemId(int i) {
return 0;
}
public void update(List<getter_setter> listUpdate){
this.list.addAll(listUpdate);
notifyDataSetChanged();
}
#Override
public View getView(int i, View view, ViewGroup viewGroup) {
View gridView = view;
if(view == null){
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
gridView = inflater.inflate(R.layout.grid_design,null);
}
final getter_setter getter = list.get(i);
TextView name = gridView.findViewById(R.id.NAME);
final ImageView bild = gridView.findViewById(R.id.bild);
name.setText(getter.getNAME());
Picasso.with(context).load(getter.getVORSCHAUBILD()).into(bild);
return gridView;
}
}
Check The Updated Listener
Explanation-:
Since You Are Passing Reference Of Your List Into RecyclerView Hence Updating List In The Activity Will Update The List In Adapter Automatically
No Need To Call update Method
swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
list.clear(); // Clean The List Before Adding Updated Data
grid_adapter.notifyDataSetChanged();
getData();
grid_adapter.notifyDataSetChanged();
swipeRefreshLayout.setRefreshing(false);
}
});

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]);
}
}

Pass JSON Array in RecyclerView Adapter Class to Activity Class

I have a RecyclerView and am creating a JSON Array with the ids of elements which are clicked in the onClick method. I am able to generate the JSON Array but I am facing trouble passing this JSON Array to my Activity.
I created an interface :
public interface ClientDataTransfer {
public void getValues(JSONArray jsonArray);
}
and modified the Adapter constructor like this:
public ClientListAdapter(List<ClientListData> clientListData, Context context, ClientDataTransfer clientDataTransfer) {
super();
this.clientListData = clientListData;
this.context = context;
this.clientDataTransfer = clientDataTransfer;
}
and in my Activity class I am setting the adapter like this:
recyclerViewAdapter = new ClientListAdapter(clientListData, this, this);
recyclerView.setAdapter(recyclerViewAdapter);
I implemented the Interface in the Activity class and inherited the method but I am facing trouble getting the JSON Array in the Activity class.
I am creating the JSON Array inside the setOnClickListener method in onBindViewHolder.
Here is my Adapter Class:
public class ClientListAdapter extends RecyclerView.Adapter<ClientListAdapter.ViewHolder> {
private Context context;
private List<ClientListData> clientListData;
public JSONArray clientArray = new JSONArray();
public ClientDataTransfer clientDataTransfer;
public ClientListAdapter(List<ClientListData> clientListData, Context context, ClientDataTransfer clientDataTransfer) {
super();
this.clientListData = clientListData;
this.context = context;
this.clientDataTransfer = clientDataTransfer;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.client_list_item, parent, false);
ViewHolder viewHolder = new ViewHolder(view);
return viewHolder;
}
#Override
public void onBindViewHolder(final ClientListAdapter.ViewHolder holder, final int position) {
final ClientListData clientListDataModel = clientListData.get(position);
holder.clientList.setText(clientListDataModel.getClientName());
holder.itemView.setBackgroundColor(clientListDataModel.isSelected() ? Color.GRAY : Color.WHITE);
holder.clientList.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
clientListDataModel.setSelected(!clientListDataModel.isSelected());
try {
JSONObject clientObject = new JSONObject();
if(clientListDataModel.isSelected()) {
holder.itemView.setBackgroundColor(Color.GRAY);
clientObject.put("id", clientListData.get(position).getClientId());
clientArray.put(clientObject);
} else if(!clientListDataModel.isSelected()) {
holder.itemView.setBackgroundColor(Color.WHITE);
for (int i = 0; i < clientArray.length(); i++) {
clientObject = clientArray.getJSONObject(i);
if (clientObject.getString("id").equals(clientListDataModel.getClientId())) {
clientArray=removeFromJsonArray(clientArray,i);
break;
}
}
}
//clientArray.put(clientObject);
} catch (JSONException e) {
e.printStackTrace();
}
clientDataTransfer.getValues(clientArray);
Log.e("client id array", ""+clientArray);
}
});
}
#Override
public int getItemCount() {
return clientListData == null ? 0:clientListData.size();
}
class ViewHolder extends RecyclerView.ViewHolder {
public TextView clientList;
public ViewHolder(View itemView) {
super(itemView);
clientList = (TextView) itemView.findViewById(R.id.tv_client_list);
}
}
private JSONArray removeFromJsonArray(JSONArray array,int position) {
JSONArray newArray = new JSONArray();
for (int i=0;i<array.length();i++)
{
//Excluding the item at position
if (i != position)
{
try {
newArray.put(array.get(i));
} catch (JSONException e) {
e.printStackTrace();
}
}
}
return newArray;
}
}
holder.clientList.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
clientListDataModel.setSelected(!clientListDataModel.isSelected());
try {
JSONObject clientObject = new JSONObject();
if(clientListDataModel.isSelected()) {
holder.itemView.setBackgroundColor(Color.GRAY);
clientObject.put("id", clientListData.get(position).getClientId());
clientArray.put(clientObject);
} else if(!clientListDataModel.isSelected()) {
holder.itemView.setBackgroundColor(Color.WHITE);
for (int i = 0; i < clientArray.length(); i++) {
clientObject = clientArray.getJSONObject(i);
if (clientObject.getString("id").equals(clientListDataModel.getClientId())) {
clientArray=removeFromJsonArray(clientArray,i);
break;
}
}
}
//clientArray.put(clientObject);
} catch (JSONException e) {
e.printStackTrace();
}
clientDataTransfer.getValues(clientArray);
Log.e("client id array", ""+clientArray);
}
});
Here is my Activity Class where I am implementing the Adapter:
public class ClientListActivity extends AppCompatActivity implements View.OnClickListener, ClientDataTransfer {
private String groupId;
private String clientId;
private String clientName;
private RecyclerView recyclerView;
private List<ClientListData> clientListData;
private RecyclerView.LayoutManager recyclerViewLayoutManager;
private RecyclerView.Adapter recyclerViewAdapter;
private JSONArray clientArrayList = new JSONArray();
ClientDataTransfer clientDataTransferx;
private Toolbar toolbar;
private FloatingActionButton share;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_client_list);
recyclerView = (RecyclerView) findViewById(R.id.rv_client_list);
toolbar = (Toolbar) findViewById(R.id.client_list_toolbar);
share = (FloatingActionButton) findViewById(R.id.floating_action_button);
share.setOnClickListener(this);
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
Window window = getWindow();
window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
window.setStatusBarColor(ContextCompat.getColor(this, R.color.colorSecondary));
}
setSupportActionBar(toolbar);
ActionBar actionBar = getSupportActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
clientListData = new ArrayList<>();
recyclerViewLayoutManager = new LinearLayoutManager(this);
recyclerView.addItemDecoration(new DividerItemDecoration(this, LinearLayoutManager.VERTICAL));
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.setLayoutManager(recyclerViewLayoutManager);
if(getIntent() != null) {
Bundle bundle = getIntent().getExtras();
try {
JSONObject jsonClientListObject = new JSONObject(getIntent().getStringExtra("clientList"));
JSONArray clientArray = jsonClientListObject.optJSONArray("activeClients");
for(int i = 0 ; i < clientArray.length(); i++) {
ClientListData clientListData = new ClientListData();
clientListData.setClientId(clientArray.getJSONObject(i).getString("id"));
clientListData.setClientName(clientArray.getJSONObject(i).getString("name"));
clientId = clientListData.getClientId();
clientName = clientListData.getClientName();
}
groupId = bundle.getString("groupId");
for(int i=0; i<clientArray.length(); i++) {
ClientListData clientListDataModel = new ClientListData();
JSONObject jsonObject = null;
jsonObject = clientArray.getJSONObject(i);
clientListDataModel.setClientName(jsonObject.getString("name"));
clientListDataModel.setClientId(jsonObject.getString("id"));
clientListData.add(clientListDataModel);
}
recyclerViewAdapter = new ClientListAdapter(clientListData, this, this);
recyclerView.setAdapter(recyclerViewAdapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
/*#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.select_all, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.select_all:
break;
}
return super.onOptionsItemSelected(item);
}*/
#Override
public void getValues(JSONArray jsonArray) {
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.floating_action_button:
clientDataTransferx = new ClientDataTransfer() {
#Override
public void getValues(JSONArray jsonArray) {
clientDataTransferx.getValues(clientArrayList);
}
};
break;
}
}
}
pass json object as a String
when you have to read use :-
JJSONObject obj = new JSONObject(Stringhere);
JSONArray jsonArray = obj.getJSONArray("results");
ArrayList < objectClass > somearray= new ArrayList < objectClass > ();
for (int i = 0; i < jsonArray.length(); i++)
{
Movie objectClass = new objectClass();
JSONObject json_data = jsonArray.getJSONObject(i);
somearray.setImageUrl(json_data.getString("key1"));
somearray.setTitle(json_data.getString("key2"));
somearray.setPlot(json_data.getString("key3"));
}

Categories

Resources