How to make it automatically view pager in few seconds?
I have tried several ways but still failed when viewpager changes
Error message is "Attempt to invoke interface method 'int java.util.List.size()' on a null object reference"
private Handler handler;
private int delay = 5000; //milliseconds
private int page = 0;
private HomeSliderPagerAdapter myAdapter;
Runnable runnable = new Runnable() {
public void run() {
if (myAdapter.getCount() == page) {
page = 0;
} else {
page++;
}
viewPager.setCurrentItem(page, true);
handler.postDelayed(this, delay);
}
};
on ActivityCreated
handler = new Handler();
viewPager = (ViewPager) getActivity().findViewById(R.id.vPager);
sliderImg = new ArrayList<>();
volleyObjectResult = new VolleyObjectResult() {
#Override
public void resSuccess(String requestType, JSONObject response) {
try {
//String images = response.getString("images");
JSONArray jsonArray = response.getJSONArray("banner");
for (int i=0; i<jsonArray.length(); i++) {
SliderUtil sliderUtil = new SliderUtil();
try {
JSONObject jsonObject = jsonArray.getJSONObject(i);
sliderUtil.setSliderImgUrl(jsonObject.getString("IMAGES"));
Log.e(TAG, "Test -> " + jsonObject.getString("IMAGES"));
}catch(Exception e){
e.printStackTrace();
}
sliderImg.add(sliderUtil);
}
HomeSliderPagerAdapter hspa = new HomeSliderPagerAdapter(sliderImg, getActivity());
hspa.notifyDataSetChanged();
viewPager.setAdapter(hspa);
viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
page = position;
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
}catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void resError(String requestType, VolleyError error) {
Toast.makeText(getActivity(), "Network connection problem", Toast.LENGTH_LONG).show();
}
};
volleyObjectService = new VolleyObjectService(volleyObjectResult, getActivity());
volleyObjectService.postJsonObject("GETCALL", requestUrl, data);
}
Result:
when the image changes it will force close with an error message "Attempt to invoke interface method 'int java.util.List.size()' on a null object reference"
Use View Pager custom adapter
public class SliderPagerAdapter extends PagerAdapter {
private LayoutInflater layoutInflater;
Activity activity;
List<ImageSliderModel> imageSliderModels;
public SliderPagerAdapter(Activity activity, List<ImageSliderModel> imageSliderModels) {
this.activity = activity;
this.imageSliderModels = imageSliderModels;
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
layoutInflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = layoutInflater.inflate(R.layout.layout_slider, container, false);
ImageView im_slider = (ImageView) view.findViewById(R.id.im_slider);
String url = imageSliderModels.get(position).getImage();
Glide.with(activity).load(imageSliderModels.get(position).getImage()).into(im_slider);
container.addView(view);
return view;
}
#Override
public int getCount() {
return imageSliderModels.size();
}
#Override
public boolean isViewFromObject(View view, Object obj) {
return view == obj;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
View view = (View) object;
container.removeView(view);
}
And in Activity call view pager and adapter
mvViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int i, float v, int i1) {
}
#Override
public void onPageSelected(int i) {
addBottomDots(i, ll_dots);
page = i;
}
#Override
public void onPageScrollStateChanged(int i) {
}
});
h.postDelayed(new Runnable() {
#Override
public void run() {
try {
if (sliderPagerAdapter.getCount() == page) {
page = 0;
} else {
page++;
}
}catch (Exception ignored)
{
}
mvViewPager.setCurrentItem(page);
h.postDelayed(this, 4000);
}
}, 1000);
And pass list to Custom adapter like this.
sliderPagerAdapter = new SliderPagerAdapter((Activity) HomeScreen.this, imageSliderModels);
mvViewPager.setAdapter(sliderPagerAdapter);
sliderPagerAdapter.notifyDataSetChanged();
private void setTimer()
{
CountDownTimer countDownTimer = new CountDownTimer(5000,2000) {
#Override
public void onTick(long millisUntilFinished) {
}
#Override
public void onFinish() {
if(viewPager.getCurrentItem() < arrayList.size() - 1)
{
viewPager.setCurrentItem(viewPager.getCurrentItem() + 1);
}
else {
viewPager.setCurrentItem(0);
}
countDownTimer.start();
}
};
countDownTimer.start();
}
Related
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();
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;
}
I am trying to slide image in viewPager, images sliding well automatically while I am using images from drawable folder. But while I am tying to show images from server to be slided from server image url its showing error something like this:
The application's PagerAdapter changed the adapter's contents without calling PagerAdapter#notifyDataSetChanged!
I have tried to solve this problem by googling but I could not solve that. I need help. My code is below:
activity work:
String imageListQuery=null;
try {
imageListQuery=URLEncoder.encode("getChatRooms", "UTF-8") + "=" + URLEncoder.encode("getChatRooms", "UTF-8");
backgroundTask=new AsyncTaskClass(context_NavigationActivity, new AsyncTaskResult() {
#Override
public void AsyncTaskResult(String result) throws JSONException {
if(result!=null){
pageViewerAdapter.notifyDataSetChanged();
}
JSONObject js = new JSONObject(result);
// Log.v("ResDFrJ",js.toString());
JSONArray arr = js.getJSONArray("result");
for (int i = 0; i < arr.length(); i++) {
JSONObject tmpOb = new JSONObject(arr.optString(i));
UsersListShowClass tmpClass = new UsersListShowClass();
tmpClass.setProPicUrl_users(InfoSetClass.getBaseUrl()+tmpOb.getString("profile_pic_id"));
imageList.add(i,tmpClass);
}
}
});
backgroundTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR,"POST","mobileApi/chatRooms",imageListQuery);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
viewPager=(ViewPagerCustomDuration)findViewById(R.id.pageViewerId);
viewPager.setScrollDurationFactor(15);
pageViewerAdapter=new PageViewerAdapter(context_NavigationActivity,imageList);
NUM_PAGES=pageViewerAdapter.getCount();
viewPager.setAdapter(pageViewerAdapter);
pageViewerAdapter.notifyDataSetChanged();
final Handler handler = new Handler();
final Runnable update = new Runnable() {
public void run() {
if (currentPage == NUM_PAGES - 1) {
currentPage = 0;
}
viewPager.setCurrentItem(currentPage++, true);
}
};
new Timer().schedule(new TimerTask() {
#Override
public void run() {
handler.post(update);
}
}, 100, 5000);
adapter:
public class PageViewerAdapter extends PagerAdapter {
private Context context;
private ArrayList<UsersListShowClass> imageList;
UsersListShowClass usersListShowClass;
public PageViewerAdapter(Context context,ArrayList<UsersListShowClass> imageList){
this.context=context;
this.imageList=imageList;
}
#Override
public int getCount() {
if(imageList != null){
return imageList.size();
}
return 0;
}
#Override
public boolean isViewFromObject(View view, Object object) {
return (view==(LinearLayout)object);
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
LayoutInflater layoutInflater=(LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view=layoutInflater.inflate(R.layout.page_viewer_adapter_layout,container,false);
ImageView imageView=(ImageView)view.findViewById(R.id.videoViewId);
usersListShowClass=imageList.get(position);
Picasso.with(context).load(usersListShowClass.getProPicUrl_users()).error(R.drawable.ic_circle_24dp).
placeholder(R.drawable.ic_circle_24dp).into(imageView);
container.addView(view);
return view;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView((LinearLayout) object);
}
#Override
public int getItemPosition(Object object) {
return PageViewerAdapter.POSITION_NONE;
}
}
i know its already solved almost similar error in stackoverflow, but in my case maybe a little different. please need help.
Try to add:
pageViewerAdapter.notifyDataSetChanged();
after:
imageList.add(i,tmpClass);
When the listview in Activity,the button works,as long as my class extends Fragment ,there nothing happen.
public class OnlineNopaymentInsuranceFragment extends Fragment implements OnItemClickListener,OnItemSelectedListener,OnListViewListener,OnClickListener {
private ScrollListView MainView;
private BasicAdapter Adapter;
private Integer Step=3;
private Integer Start=0;
private Integer End=Step;
private Handler handler,handler2;
//private List<Map<String, Object>> Lists;
private DataTable Table;
public static String SelectCode="";
private static final int OVER = 1;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_online_insurance,container,false);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
this.MainView=(ScrollListView)getView().findViewById(R.id.contractlistView1);
this.MainView.setOnItemClickListener(this);
this.MainView.setOnItemSelectedListener(this);
this.MainView.setPullLoadEnable(true);
this.MainView.setXListViewListener(this);
handler2 = new Handler();
Control.StartDialog(getActivity());
new Thread(new Runnable() {
public void run() {
Looper.prepare();
handler2.post(runSetList);
handler1.sendEmptyMessage(1);
Looper.loop();
}
}).start();
this.MainView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
Toast.makeText(getActivity(), "nothing", Toast.LENGTH_LONG).show();
}
});
}
private void SetList(){
Start=0;
End=3;
this.Table = new DataTable(getActivity(),"newcontracta");
this.Table.Load("AgentCode="+OnlineNopaymentInsuranceFragment.SelectCode+"&Start=0&End="+Step);
if(Table.GetRowCount()>0){
this.MainView.setVisibility(0);
this.StartData(this.Table.GetList(),R.layout.userlistitem3);
}else{
this.MainView.setVisibility(8);
TextView NullView=(TextView) getView().findViewById(R.id.listViewNull1);
NullView.setVisibility(0);
NullView.setHeight(50);
}
}
private void StartData(ArrayList<Map<String, Object>> List, int Resource) {
this.Adapter = new BasicAdapter(getActivity(), List, Resource,
new String[] { "Provider", "ProdName", "NoType", "ContractNo",
"AcceptTime", "ContractStatus", "Premium", "Gain",
"ReceivedPremium", "Name" },
new int[] {R.id.contractitem_label_Provider,
R.id.contractitem_label_ProdName,
R.id.contract_label_cno,
R.id.contractitem_label_contractNo,
R.id.contractitem_label_acceptTime,
R.id.contractitem_label_contractStatus,
R.id.contractitem_label_premium,
R.id.contractitem_label_feilv,
R.id.contractitem_label_receivedPremium,
R.id.contractitem_label_Name },
new int[] {R.id.listitem_button_look, R.id.listitem_button_pay,R.id.listitem_main1 });
handler = new Handler();
this.Adapter.Start(this.MainView);
this.Start += Step;
this.End += Step;
}
private void LoadData(){
this.Table.Load("AgentCode="+OnlineNopaymentInsuranceFragment.SelectCode+"&Start="+Start+"&End="+End);
this.Start += Step;
this.End += Step;
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.listitem_button_pay:
LogUtil.e("OnlineNopaymentInsuranceFragment", "nothing happen in here");
Toast.makeText(getActivity(),"nothing happen in here", Toast.LENGTH_SHORT).show();
break;
case R.id.listitem_main1:
Toast.makeText(getActivity(),"nothing happen in here,too", Toast.LENGTH_SHORT).show();
break;
default:
break;
}
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int Index, long id) {}
#Override
public void onNothingSelected(AdapterView<?> parent) {}
#Override
public void onItemClick(AdapterView<?> parent, View view, int Index, long id) {}
private void stopRefresh() {
this.MainView.stopRefresh();
this.MainView.setRefreshTime("刚刚");
}
private void stopLoadMore() {
this.MainView.stopLoadMore();
}
#Override
public void onRefresh() {
handler.postDelayed(new Runnable() {
#Override
public void run() {
SetList();
stopRefresh();
}
}, 2000);
}
#Override
public void onLoadMore() {
handler.postDelayed(new Runnable() {
#Override
public void run() {
LoadData();
stopLoadMore();
}
}, 2000);
}
#SuppressLint("HandlerLeak")
Handler handler1 = new Handler() {
public void handleMessage(Message msg) {
switch (msg.what) {
case OVER:
Control.ExitDialog();
break;
default:
break;
}
super.handleMessage(msg);
}
};
Runnable runSetList = new Runnable() {
#Override
public void run() {
SetList();
}
};
}
Adapter code:
public class BasicAdapter extends SimpleAdapter {
private Context context;
private ArrayList<Integer> Indexs;
public BasicAdapter(Context context,List<? extends Map<String,?>> data,int resource,String[] from,int[] to){
super(context,data,resource,from,to);
this.context=context;
this.Indexs =new ArrayList<Integer>();
}
public BasicAdapter(Context context,List<? extends Map<String,?>> data,int resource,String[] from,int[] to,int[] Ids){
super(context,data,resource,from,to);
this.context=context;
this.Indexs =new ArrayList<Integer>();
if (Ids != null) {
for (int i = 0; i < Ids.length; i++) {
this.Indexs.add(Ids[i]);
}
}
}
public void Add(Integer ViewId){this.Indexs.add(ViewId);}
#Override
public View getView(int position,View convertView,ViewGroup parent){
LogUtil.e("===basicadapter", "getview");
View view = super.getView(position, convertView, parent);
for(int i=0;i<this.Indexs.size();i++){
View TempView=(View) view.findViewById(this.Indexs.get(i));
TempView.setOnClickListener((OnClickListener) this.context);
TempView.setTag(position);
}
return view;
}
public void Start(ListView View){
View.setAdapter(this);
this.setViewBinder(new ViewBinder() {
#Override
public boolean setViewValue(View view,Object data,String textRepresentation) {
if(view instanceof TextView && data instanceof HkBoolean){
HkBoolean Data = (HkBoolean) data;
view.setVisibility(Data.GetVisibility());
return true;
}else if(view instanceof ImageView && data instanceof Bitmap){
ImageView iv = (ImageView) view;
iv.setImageBitmap((Bitmap) data);
return true;
}else if(view instanceof ImageView && data instanceof Integer){
ImageView iv = (ImageView) view;
iv.setBackgroundResource((Integer) data);
return true;
}else {
return false;
}
}
});
}
}
If I put button lister in BasicAdapter,it can call ,too.But I want the button'click listener in Fragment.Any suggestion will be appreciated.
this.Adapter = new BasicAdapter(getActivity(), List, Resource,
new String[] { "Provider", "ProdName", "NoType", "ContractNo",
"AcceptTime", "ContractStatus", "Premium", "Gain",
"ReceivedPremium", "Name" },
Fragment is implementing the listener and not the activity. So you should do
this.Adapter = new BasicAdapter(this, List, Resource,
new String[] { "Provider", "ProdName", "NoType", "ContractNo",
"AcceptTime", "ContractStatus", "Premium", "Gain",
"ReceivedPremium", "Name" },
hi friends i am new to the android development i am developing an app similar to flipkart. i am using the tab layout where there are 4tabs 1.home 2.menu 3.cart 4.settings
Each tab consists of list view where each one is having fragment in it,when i click the menu button and select an item that i want to order,after ordering it, it is not loading in the cart so i am not able to locate the item in the cart
MenuAdapter.Java
public class Second_adapter extends BaseAdapter {
Context context;
TextView basename, SubItemprice, itemdesc, SubItemdesc;
LayoutInflater inflater;
ImageView order;
private List<JSONParser> items;
String itembasename, itemde, subtmsub, subitempri;
SharedPreferences.Editor loginPrefsEditor;
public Second_adapter(Context context, List<JSONParser> items) {
this.context = context;
this.items = items;
}
#Override
public int getCount() {
return items.size();
}
#Override
public Object getItem(int i) {
return items.get(i);
}
#Override
public long getItemId(int i) {
return i;
}
#Override
public View getView(int i, View view, ViewGroup viewGroup) {
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (view == null)
view = inflater.inflate(R.layout.item_clicked, viewGroup, false);
basename = (TextView) view.findViewById(R.id.basename);
SubItemprice = (TextView) view.findViewById(R.id.SubItemprice);
itemdesc = (TextView) view.findViewById(R.id.itemdesc);
SubItemdesc = (TextView) view.findViewById(R.id.SubItemdesc);
order = (ImageView) view.findViewById(R.id.order);
final JSONParser setdata = items.get(i);
basename.setText(setdata.getBaseName());
itemdesc.setText(setdata.getItemdesc());
SubItemdesc.setText(setdata.getSubItemdesc());
SubItemprice.setText(setdata.getSubItemprice());
order.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
itembasename = setdata.getBaseName();
itemde = setdata.getItemdesc();
subtmsub = setdata.getSubItemdesc();
subitempri = setdata.getSubItemprice();
Session userloggedin=new Session(context);
if (userloggedin.isLoggedIn()){
addcart();
Cart cart=new Cart();
cart.cartdata();
Toast.makeText(context, "LoggedIn" +itembasename+itemde+subtmsub+subitempri, Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(context,"Please Login", Toast.LENGTH_SHORT).show();
}
}
});
return view;
}
private void addcart() {
SharedPreferences customerid=context.getSharedPreferences("loginPrefs",Context.MODE_PRIVATE);
String customid=customerid.getString("customerid","");
String addcarturl = "http://standardtakeaway.co.uk/json/cart_process.php?userid="+customid+"&Item="+itembasename+itemde+subtmsub+"&Itemcount=1&price="+subitempri;
Log.d("Cart",addcarturl);
JsonArrayRequest cartreq=new JsonArrayRequest(Request.Method.POST, addcarturl, (String) null, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
for (int i=0;i<response.length();i++){
try {
JSONObject cartobj=response.getJSONObject(i);
String count=cartobj.getString("count");
loginPrefsEditor.putString("Badge",count);
loginPrefsEditor.commit();
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(context,""+error, Toast.LENGTH_SHORT).show();
}
});
AppController.getInstance().addToRequestQueue(cartreq);
}
}
Cart.Class
public class Cart extends Fragment {
Button check_out;
TextView subtotal;
ListView cartview;
CartAdapter cartAdapter;
List<JSONParser> cartitems;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View cartfrag = inflater.inflate(R.layout.cart, container, false);
subtotal = (TextView) cartfrag.findViewById(R.id.subtotal);
cartview = (ListView) cartfrag.findViewById(R.id.cartview);
cartitems = new ArrayList<JSONParser>();
cartAdapter = new CartAdapter(getActivity(), cartitems);
cartview.setAdapter(cartAdapter);
check_out = (Button) cartfrag.findViewById(R.id.check_out);
check_out.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent cart_check = new Intent(getActivity(), Check.class);
startActivity(cart_check);
}
});
Session cartlogged=new Session(getActivity());
if (cartlogged.isLoggedIn()){
cartdata();
}else {
Toast.makeText(getActivity(),"Not Logged", Toast.LENGTH_SHORT).show();
}
cartdata();
return cartfrag;
}
void cartdata() {
SharedPreferences customerid=getActivity().getSharedPreferences("loginPrefs", Context.MODE_PRIVATE);
String customid=customerid.getString("customerid","");
String carturl = "http://standardtakeaway.co.uk/json/view_cart.php?userid=" + customid;
Log.d("CartData", carturl);
JsonObjectRequest cartreq = new JsonObjectRequest(Request.Method.GET, carturl, (String) null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray objarray = response.getJSONArray("items");
for (int i = 0; i < objarray.length(); i++) {
JSONObject cartdataobj = objarray.getJSONObject(i);
JSONParser parserdata = new JSONParser();
parserdata.setCartquantity(cartdataobj.getString("qty"));
parserdata.setCartbase(cartdataobj.getString("BaseName"));
parserdata.setCartprice(cartdataobj.getString("price"));
cartitems.add(parserdata);
}
JSONObject subobj=response.getJSONObject("details");
String subtext=subobj.getString("subtotal");
subtotal.setText(subtext);
} catch (JSONException e) {
e.printStackTrace();
}
cartAdapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getActivity(), "" + error, Toast.LENGTH_SHORT).show();
}
});
cartreq.setRetryPolicy(new DefaultRetryPolicy(6000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
AppController.getInstance().addToRequestQueue(cartreq);
}
public static Cart getInstance(String message) {
Cart cart = new Cart();
Bundle bundle = new Bundle();
bundle.putString("MSG", message);
cart.setArguments(bundle);
return cart;
}
TabLayout.java
public class TabAdapter extends FragmentStatePagerAdapter {
private Context mContext;
private List<Fragment> mFragments = new ArrayList<>();
private List<String> mFragmentTitles = new ArrayList<>();
private List<Integer> mFragmentIcons = new ArrayList<>();
public TabAdapter(Context context, FragmentManager fm) {
super(fm);
this.mContext = context;
}
public void addFragment(Fragment fragment, String title, int drawable) {
mFragments.add(fragment);
mFragmentTitles.add(title);
mFragmentIcons.add(drawable);
}
#Override
public Fragment getItem(int position) {
return mFragments.get(position);
}
#Override
public int getCount() {
return mFragments.size();
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitles.get(position);
}
public View getTabView(int position) {
View tab = LayoutInflater.from(mContext).inflate(R.layout.customtab, null);
TextView tabText = (TextView) tab.findViewById(R.id.tabText);
ImageView tabImage = (ImageView) tab.findViewById(R.id.tabImage);
tabText.setText(mFragmentTitles.get(position));
tabImage.setBackgroundResource(mFragmentIcons.get(position));
if (position == 0) {
tab.setSelected(true);
}
return tab;
}
}
MainActivity.java
public class MainActivity extends BaseActivity implements OnFragmentInteractionListener {
#Bind(R.id.tabpager)
ViewPager mViewpager;
#Bind(R.id.tab_layout)
TabLayout mTabs;
private TabAdapter pageAdapter;
String home,menu,cart,account,more;
#Override
protected int getLayoutResource() {
return R.layout.activity_main;
}
#Override
protected void initVariables(Bundle savedInstanceState) {
home= getString(R.string.home);
menu = getString(R.string.menu);
cart = getString(R.string.cart);
account = getString(R.string.account);
more = getString(R.string.more);
}
#Override
protected void initData(Bundle savedInstanceState) {
setupViewPager(mViewpager);
setupTabLayout(mTabs);
}
public void setupViewPager(ViewPager viewPager) {
pageAdapter = new TabAdapter(getApplicationContext(), getSupportFragmentManager());
pageAdapter.addFragment(MainFragment.getInstance(home), home, R.drawable.home);
pageAdapter.addFragment(MenuItems.getInstance(menu), menu, R.drawable.menu);
pageAdapter.addFragment(Cart.getInstance(cart), cart, R.drawable.cart);
pageAdapter.addFragment(Account.getInstance(account), account, R.drawable.account);
pageAdapter.addFragment(More.getInstance(more), more, R.drawable.more);
viewPager.setAdapter(pageAdapter);
}
public void setupTabLayout(TabLayout tabLayout) {
tabLayout.setTabMode(TabLayout.MODE_FIXED);
tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
tabLayout.setupWithViewPager(mViewpager);
mViewpager.setOffscreenPageLimit(4);
for (int i = 0; i < tabLayout.getTabCount(); i++) {
TabLayout.Tab tab = tabLayout.getTabAt(i);
tab.setCustomView(pageAdapter.getTabView(i));
}
tabLayout.requestFocus();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
You can fix this way by setting setOnPageChangeListener on viewPager:
viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageSelected(int index) {
// TODO Auto-generated method stub
if(index==3){
((Cart) mAdapter.getItem(index)).cartdata();
}
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
// TODO Auto-generated method stub
}
#Override
public void onPageScrollStateChanged(int arg0) {
// TODO Auto-generated method stub
}
});
Your cartdata() must be public.