I have five tabs they are 1.home 2.menu 3.cart 4.account 5.more.Here cart tab consist of list view which is having the remove button in it,when i click on that remove button it must refresh the fragment itself so that it can load new data from the Json
MainActivity.class
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);
viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
Session cartsession=new Session(getApplicationContext());
if (cartsession.isLoggedIn()){
if (position==2){
((Cart) pageAdapter.getItem(position)).cartdata();
}
}
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
}
public void setupTabLayout(TabLayout tabLayout) {
tabLayout.setTabMode(TabLayout.MODE_FIXED);
tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
tabLayout.setupWithViewPager(mViewpager);
for (int i = 0; i < tabLayout.getTabCount(); i++) {
TabLayout.Tab tab = tabLayout.getTabAt(i);
tab.setCustomView(pageAdapter.getTabView(i));
}
tabLayout.requestFocus();
}
}
TabAdapter.class
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;
}
public int getItemPosition(Object object) {
return POSITION_NONE;
}
}
Cart.Java
public class Cart extends Fragment {
Button check_out;
TextView subtotal;
ListView cartview;
CartAdapter cartAdapter;
List<JSONParser> cartitems;
SharedPreferences loginPreferences;
SharedPreferences.Editor loginPrefsEditor;
TextView cartstatus,cartempty;
LinearLayout linearlay;
RelativeLayout cartvisible;
#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);
cartstatus = (TextView) cartfrag.findViewById(R.id.cartstatus);
cartempty = (TextView) cartfrag.findViewById(R.id.cartempty);
linearlay = (LinearLayout) cartfrag.findViewById(R.id.linearlay);
cartvisible = (RelativeLayout) cartfrag.findViewById(R.id.cartvisible);
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()) {
cartitems.clear();
cartdata();
} else {
cartstatus.setText("Please Login");
}
return cartfrag;
}
void cartdata() {
cartitems.clear();
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 {
if (response.getString("status").equals("empty")) {
cartstatus.setVisibility(View.GONE);
cartempty.setText("Your Cart is Empty");
} else {
JSONArray objarray = response.getJSONArray("items");
for (int i = 0; i < objarray.length(); i++) {
JSONObject cartdataobj = objarray.getJSONObject(i);
linearlay.setVisibility(View.VISIBLE);
cartvisible.setVisibility(View.GONE);
JSONParser parserdata = new JSONParser();
parserdata.setCartquantity(cartdataobj.getString("qty"));
parserdata.setCartbase(cartdataobj.getString("BaseName"));
parserdata.setCartprice(cartdataobj.getString("price"));
cartitems.add(parserdata);
loginPreferences = getActivity().getSharedPreferences("loginPrefs", Context.MODE_PRIVATE);
loginPrefsEditor = loginPreferences.edit();
JSONObject subobj = response.getJSONObject("details");
String subtext = subobj.getString("subtotal");
loginPrefsEditor.putString("Price", subtext);
loginPrefsEditor.commit();
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;
}
}
CartAdapter.class
public class CartAdapter extends BaseAdapter {
Context context;
TextView quantity, basenamecart, cartprice;
ImageButton delete;
private List<JSONParser> cartitems;
LayoutInflater inflater;
String removequantity, removeitemprice,removebasename;
public CartAdapter(Context context, List<JSONParser> cartitems) {
this.context = context;
this.cartitems = cartitems;
}
#Override
public int getCount() {
return cartitems.size();
}
#Override
public Object getItem(int position) {
return cartitems.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
convertView = inflater.inflate(R.layout.cartitems, parent, false);
quantity = (TextView) convertView.findViewById(R.id.quantity);
basenamecart = (TextView) convertView.findViewById(R.id.basenamecart);
cartprice = (TextView) convertView.findViewById(R.id.cartprice);
delete= (ImageButton) convertView.findViewById(R.id.delete);
final JSONParser dataparser = cartitems.get(position);
quantity.setText(dataparser.getCartquantity());
basenamecart.setText(dataparser.getCartbase());
cartprice.setText(dataparser.getCartprice());
delete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
removequantity=dataparser.getCartquantity();
removebasename=dataparser.getCartbase();
removeitemprice=dataparser.getCartprice();
removecart();
}
});
}
return convertView;
}
private void removecart(){
SharedPreferences customerid=context.getSharedPreferences("loginPrefs", Context.MODE_PRIVATE);
String removeid=customerid.getString("customerid","");
String removeurl="http://standardtakeaway.co.uk/json/del_cartitems.php?userid="+removeid+"&Item="+removebasename+"&price="+removeitemprice;
Log.d("Remove",removeurl);
final JsonArrayRequest removearray=new JsonArrayRequest(Request.Method.GET, removeurl, (String) null, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
for (int i=0;i<response.length();i++){
Log.d("Remove", String.valueOf(response));
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
removearray.setRetryPolicy(new DefaultRetryPolicy(6000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
AppController.getInstance().addToRequestQueue(removearray);
}
}
You need to remove the concerned object from the list cartitems and then call the notifyDataSetChanged() method to notify the any dependent views to refresh itself.
Documentation here
Also, this is not the correct way to implement a BaseAdapter and handle changes in it. Maybe this will help : http://androidadapternotifiydatasetchanged.blogspot.in/
Also, try using the new RecyclerView in order to implement such things. It is available in the support library and definitely a good way to display collections and also makes it easy to add remove items with default animations too. Please read through it. A starting point http://developer.android.com/training/material/lists-cards.html
see added line and updated line.
add make sure only remove item from list if removed successfully from server.
#Override
public View getView(int position, View convertView, ViewGroup parent) {
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
convertView = inflater.inflate(R.layout.cartitems, parent, false);
quantity = (TextView) convertView.findViewById(R.id.quantity);
basenamecart = (TextView) convertView.findViewById(R.id.basenamecart);
cartprice = (TextView) convertView.findViewById(R.id.cartprice);
delete= (ImageButton) convertView.findViewById(R.id.delete);
final JSONParser dataparser = cartitems.get(position);
quantity.setText(dataparser.getCartquantity());
basenamecart.setText(dataparser.getCartbase());
cartprice.setText(dataparser.getCartprice());
final int pos =position; // added line
delete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
removequantity=dataparser.getCartquantity();
removebasename=dataparser.getCartbase();
removeitemprice=dataparser.getCartprice();
removecart(pos); //updated line
}
});
}
return convertView;
}
public void updateCartitems(List<JSONParser> newCartitems) {
cartitems.clear();
cartitems.addAll(newCartitems);
this.notifyDataSetChanged();
}
private void removecart(int pos){ // updated line
SharedPreferences customerid=context.getSharedPreferences("loginPrefs", Context.MODE_PRIVATE);
String removeid=customerid.getString("customerid","");
String removeurl="http://standardtakeaway.co.uk/json/del_cartitems.php?userid="+removeid+"&Item="+removebasename+"&price="+removeitemprice;
Log.d("Remove",removeurl);
final JsonArrayRequest removearray=new JsonArrayRequest(Request.Method.GET, removeurl, (String) null, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
for (int i=0;i<response.length();i++){
Log.d("Remove", String.valueOf(response));
}
cartitems.remove(pos); //added line
updateCartitems(cartitems);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
removearray.setRetryPolicy(new DefaultRetryPolicy(6000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
AppController.getInstance().addToRequestQueue(removearray);
}
Related
I am trying to pass data Adapter class to TabView Layout. I have used fragment in tab. I want to pass data from adapter to fragment (fragment class for tab).
________________________________________Adapter Class________________________________________________
package com.livediscount.restaurants.Adapter;
public class LiveContestAdapter extends RecyclerView.Adapter<LiveContestAdapter.MyViewHolder> {
Context context;
List<Contest_Data> contest_data;
public LiveContestAdapter(Context context, List<Contest_Data> contest_data) {
this.context=context;
this.contest_data=contest_data;
}
#NonNull
#Override
public MyViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
context=viewGroup.getContext();
View vh= LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.custom_list_win_iphone,viewGroup,false);
MyViewHolder myViewHolder=new MyViewHolder(vh);
return myViewHolder;
}
#Override
public void onBindViewHolder(#NonNull final LiveContestAdapter.MyViewHolder myViewHolder, final int i) {
final Contest_Data contest_position = contest_data.get(i);
Picasso.with(context).load(contest_data.get(i).getContestImage()).error(R.drawable.damme).placeholder(R.drawable.damme).into(myViewHolder.img);
myViewHolder.remainSlot.setText(contest_data.get(i).getContestTotal_slot());
myViewHolder.ent_fee.setText(contest_data.get(i).getContestEntry_Fee());
myViewHolder.Booked_Slot.setText(contest_data.get(i).getContestBooked());
final String contest_status = contest_data.get(i).getContestStatus();
String previous_contest = contest_data.get(i).getPrevious_contest();
String winner_announce = contest_data.get(i).getWinner_announce();
}
#Override
public int getItemCount() {
return contest_data.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder {
TextView name;
ImageView img;
public MyViewHolder(#NonNull View itemView) {
super(itemView);
//name=itemView.findViewById(R.id.totalslot);
img=itemView.findViewById(R.id.imageView2);
htp = itemView.findViewById(R.id.button2);
remainSlot=itemView.findViewById(R.id.tvTotalSlotNumber);
}
}
}
___________________________________________AppCompactActivity______________________________________
public class PrizeBreakup extends AppCompatActivity {
ImageButton back;
TabLayout tabLayout;
ViewPager viewPager;
String contest_id,contest_name;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_prize_breakup);
back = findViewById(R.id.back_button);
back.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
onBackPressed();
}
});
tabLayout= findViewById(R.id.tabs);
viewPager = findViewById(R.id.container);
PrizeLayoutAdapter adapter = new PrizeLayoutAdapter(getSupportFragmentManager());
adapter.add(new PrizeLayout(),"Prize Breakup");
adapter.add(new WinnerLayout(),"Winners");
viewPager.setAdapter(adapter);
tabLayout.setupWithViewPager(viewPager);
//here
SharedPreferences.Editor editor = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE).edit();
editor.putString("contestid1", "contest_id");
editor.apply();
/* Bundle bundle = getIntent().getExtras();
assert bundle!= null;
contest_id = bundle.getString("contest_id");
contest_name = bundle.getString("contest_name");*/
/* Bundle data = new Bundle();
data.putString("contestid1","contest_id");
Fragment argumentFragment = new PrizeLayout();
argumentFragment.setArguments(data);*/
}
}
_____________________________________PrizeLayout Fragment________________________________________
package com.livediscount.restaurants;
public class PrizeLayout extends Fragment {
List<Contest_Data> contest_data;
LiveContestAdapter live_contest_adapter;
private RecyclerView recyclerView;
TextView ContestId;
public static PrizeLayout newInstance() {
return new PrizeLayout();
}
#Override
public View onCreateView( LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.prize_layout, container, false);
SharedPreferences prefs = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE);
String contestid = getActivity().prefs.getString("contestid1", "contestid not found");
String Contest_id = this.getArguments().getString("edttext");
ContestId= view.findViewById(R.id.referral_code);
ContestId.setText(contestid);
return view;
}
}
________________________________________Winner Fragment______________________________________________
package com.livediscount.restaurants;
public class WinnerLayout extends Fragment {
private List<Winner_data> winner_data=new ArrayList<>();
private RecyclerView recyclerView_winner;
#Override
public View onCreateView(#NonNull LayoutInflater inflater, ViewGroup container , Bundle savedInstanceState)
{
View view = inflater.inflate(R.layout.winner_layout,container,false);
recyclerView_winner = view.findViewById(R.id.Recyclerview_Winner);
if(winner_data!=null)
{
winner_data.clear();
}
Winner_Data();
return view;
}
private void Winner_Data() {
RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());
String url = ("http://livediscounts.in/webservices/User_interface/Winner_List?contest_id=\"+razorpayPaymentID+\"");
StringRequest request = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
//progressBar_contest.setVisibility(View.GONE);
JSONObject jsonObject = new JSONObject(response);
if (jsonObject.getString("status").equals("1")) {
JSONArray jsonArray = jsonObject.getJSONArray("records");
/*for (int i = 0; i < jsonArray.length(); i++) {
JSONObject obj = jsonArray.getJSONObject(i);
Winner_data wd = new Winner_data();
cd.setContestId(obj.getString("id"));
cd.setContestName(obj.getString("name"));
cd.setContestImage(obj.getString("prize_1"));
cd.setContestDescription(obj.getString("description"));
cd.setContestType(obj.getString("type"));
cd.setContestEntry_Fee(obj.getString("entry_fee"));
cd.setContestTotal_slot(obj.getString("total_slot"));
cd.setContestTotal_winner(obj.getString("total_winner"));
cd.setContestPrice_Description(obj.getString("price_description"));
cd.setContestPrize_21(obj.getString("prize_21"));
cd.setContestPrize_22(obj.getString("prize_22"));
cd.setContestPrize_31(obj.getString("prize_31"));
cd.setContestPrize_32(obj.getString("prize_32"));
cd.setContestPrize_41(obj.getString("prize_41"));
cd.setContestPrize_42(obj.getString("prize_42"));
cd.setContestPrize_51(obj.getString("prize_51"));
cd.setContestPrize_52(obj.getString("prize_52"));
cd.setContestPrize_61(obj.getString("prize_61"));
cd.setContestPrize_62(obj.getString("prize_62"));
cd.setContestPrize_71(obj.getString("prize_71"));
cd.setContestPrize_72(obj.getString("prize_72"));
cd.setContestStatus(obj.getString("status"));
cd.setContestContest_Note(obj.getString("contest_note"));
cd.setContestStart_date(obj.getString("start_date"));
cd.setContestEnd_date(obj.getString("end_date"));
cd.setContestBooked(obj.getString("booked_slot"));
winner_data.add(wd);
}*/
/*WinnerAdapter winnerAdapter = new WinnerAdapter(getApplicationContext(), winner_data);
LinearLayoutManager llm = new LinearLayoutManager(getActivity());
llm.setOrientation(LinearLayoutManager.VERTICAL);
recyclerView_winner.setLayoutManager(llm);
recyclerView_winner.setAdapter(winnerAdapter);*/
} else {
// Toast.makeText(getApplicationContext(),"Something went Wrong",Toast.LENGTH_SHORT).show();
}
} catch (Exception ex) {
//progressBar_contest.setVisibility(View.GONE);
//Toast.makeText(getApplicationContext(),"No Data Found",Toast.LENGTH_LONG).show(); ex.printStackTrace();
}
}
}
,
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
//Toast.makeText(getApplicationContext(),"No Internet Connection",Toast.LENGTH_LONG).show();
}
}
);
requestQueue.add(request);
}
}
you can use shared pref using parent activity.
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 have set up recyclerview for same Api data on two fragments.After clicking on one of Card, a new Detail fragment for same Card is open on Another Fragment.The cardview contain images.After clicking one of image I need to get information of that CardView position.But as I click on one of card in First Fragment and I move to same card position in Second Fragment but I swipe to other cards and click on Image of other CardView still I am getting information for same Card which was clicked first.
This is code for Adapter
class public class StatusInfoAdapter extends RecyclerView.Adapter<StatusInfoAdapter.ViewHolder> {
private FragmentManager fm;
private FragmentTransaction tx;
private ArrayList<StatusEntry> entries;
private int finalPos,tempPos;
Context context;
String People, id,Id;
SnackBarAlert alertMsg=new SnackBarAlert();
private String myToken;
public StatusInfoAdapter(ArrayList<StatusEntry> entries, Context context) {
this.entries = entries;
this.context = context;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.status_info_card, parent, false);
return new ViewHolder(v);
}
#Override
public void onBindViewHolder(ViewHolder holder,int position) {
StatusEntry entry = entries.get(position);
tempPos = holder.getAdapterPosition();
finalPos = tempPos + 1;
holder.id.setText(entry.getid());
holder.Idno.setText(entry.getidno());
holder.fname.setText(entry.getFname());
holder.lname.setText(entry.getLname());
holder.people.setText(entry.getPeople());
noOfPeople = entries.get(position).getPeople();
fid = entries.get(position).getFyraid();
Id = entries.get(position).getid();
}
#Override
public int getItemCount() {
return entries.size();
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public int getItemViewType(int position) {
return position;
}
public class ViewHolder extends RecyclerView.ViewHolder {
public TextView fname;
public TextView lname;
public TextView people;
public TextView d;
TextView Idno;
ImageView cancelEntry;
public ViewHolder(View v) {
super(v);
SharedPreferences preferences=context.getSharedPreferences("myPrefs",Context.MODE_PRIVATE);
fname = (TextView) v.findViewById(R.id.fname);
lname = (TextView) v.findViewById(R.id.lname);
people = (TextView) v.findViewById(R.id.adults);
fyra_id = (TextView) v.findViewById(R.id.fyraid);
Idno = (TextView) v.findViewById(R.id.Id);
cancelEntry = (ImageView) v.findViewById(R.id.cancel);
cancelEntry.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
final AppCompatActivity activity = (AppCompatActivity) v.getContext();
final Dialog dialog=new Dialog(activity);
dialog.setContentView(R.layout.cancel_reason);
dialog.show();
Button yes = (Button) dialog.findViewById(R.id.yes);
Button no = (Button) dialog.findViewById(R.id.no);
no.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog.cancel();
}
});
yes.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog.cancel();
removeFromQueue();
alertMsg.infoMessage(v,"Removed from List");
entries.remove(tempPos);
notifyItemRemoved(tempPos);
ChooseTab chooseTab1=new ChooseTab();
fm=activity.getSupportFragmentManager();
CurrentStatus currentStatus=new CurrentStatus();
tx=fm.beginTransaction();
tx.detach(currentStatus);
tx.attach(currentStatus);
tx.replace(R.id.frame,chooseTab1);
tx.commit();
}
});
}
});
}
}
This is code for setting RecyclerView
JsonArrayRequest request=new JsonArrayRequest(Request.Method.GET, url, null, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
try{
for(int i=0;i<response.length();i++)
{
JSONObject object=response.getJSONObject(i);
final StatusEntry entry=new StatusEntry();
String id=object.getString("fid");
Idno=object.getString("idno");
JsonObjectRequest(Request.Method.GET,url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
String first_name=response.getString("firstname");
String last_name=response.getString("lastname");
String id=response.getString("id");
entry.setFname(first_name);
entry.setLname(last_name);
entry.setid(id);
entry.setidNo(Idno);
adapter.notifyDataSetChanged();
progressDialog.hide();
}
catch (JSONException e)
{
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
})
};
AppController.getInstance().addToRequestQueue(foodie_request,foodie_data);
String no_of_people=object.getString("no_people");
entry.setPeople(no_of_people);
progressDialog.dismiss();
entries.add(entry);
adapter = new StatusInfoAdapter(entries, getActivity().getApplicationContext());
recyclerView.setAdapter(adapter);
}
}catch(JSONException e)
{
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
})
};
AppController.getInstance().addToRequestQueue(request,foo_request);
}
I am getting the same Idno for all CardView after swiping to other cards.How to resolve this ?
pass the model of list in the constructor of the fragment at time of begin transaction and receive it by creating same model in another fragment from constructor
I want show website datas in 3 fragments with json! when swipe between TABs not duplicate datas. but when click on TABs, duplicate previous data again!
For send data from from AsyncTask to Fragments i use EventBus component.
Fragment codes:
public class free_fragment extends Fragment {
private RecyclerView mRecyclerView;
private free_recycler_adapter mAdapter;
private RecyclerView.LayoutManager mLayoutManager;
private List<DataModel> dataModels = new ArrayList<DataModel>();
private Context context;
private boolean isDataFetched;
private boolean mIsVisibleToUser;
private View view;
#Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
view = inflater.inflate(R.layout.fragment_free_layout, container, false);
context = getContext();
if (mIsVisibleToUser) {
LoadData();
}
///----- RecyclerView -----
mRecyclerView = (RecyclerView) view.findViewById(R.id.pdf_RecyclerView);
mRecyclerView.setHasFixedSize(true);
mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
mAdapter = new free_recycler_adapter(context, dataModels);
mRecyclerView.setAdapter(mAdapter);
return view;
}
#Subscribe
public void onEvent(MyEvent event) {
List<DataModel> dataModels = event.getInfoModels();
/* if (dataModels.size() > 0) {
dataModels.remove(dataModels.size() - 1);
mAdapter.notifyItemRemoved(dataModels.size());
//mAdapter.setLoaded();
}*/
if (event.fragmentTag.equals("forfragment1")) {
mAdapter.add(dataModels);
isDataFetched = true;
mAdapter.notifyDataSetChanged();
}
}
#Override
public void setUserVisibleHint(boolean isVisibleToUser) {
mIsVisibleToUser = isVisibleToUser;
if (isVisibleToUser && !isDataFetched && getContext() != null) {
context = getContext();
LoadData(); //Remove this call from onCreateView
}
}
private void LoadData() {
freeDataInfo dataInfo = new freeDataInfo();
// here getMainDataInfo() should return the server response
dataInfo.getFreeDataInfo(context);
}
#Override
public void onResume() {
super.onResume();
EventBus.getDefault().register(this);
}
#Override
public void onPause() {
EventBus.getDefault().unregister(this);
super.onPause();
}
}
AsyncTask codes:
public class freeDataInfo {
private Context mContext;
private String ServerAddress = freeServer_IP.getFreeIP();
private DiskLruDataCache mDiskLruCache;
public void getFreeDataInfo(Context context) {
mContext = context;
this.mDiskLruCache=new DiskLruDataCache(context);
//new getInfo().execute(ServerAddress + "limit=10");
new getInfo().execute(ServerAddress);
}
private class getInfo extends AsyncTask<String, Void, String> {
EventBus bus = EventBus.getDefault();
private String ou_response;
private List<DataModel> infoModels = new ArrayList<>();
private ProgressDialog dialog;
#Override
protected void onPreExecute() {
//CustomProcessDialog.createAndShow(mContext);
//infoModels = new ArrayList<>();
// Initiate Progress
dialog = new ProgressDialog(mContext);
this.dialog.setMessage("شکیبا باشید...");
this.dialog.show();
infoModels.clear();
}
#Override
protected String doInBackground(String... params) {
OkHttpClient client = new OkHttpClient();
//String url = (String) params[0];
Request request = new Request.Builder()
//.url(ServerAddress + "limit=10")
.url(ServerAddress)
.cacheControl(CacheControl.FORCE_NETWORK)
.build();
Response response;
try {
if(CheckInternet.isConnected(mContext)) {
response = client.newCall(request).execute();
ou_response = response.body().string();
if (ou_response != null) {
mDiskLruCache.cacheToDisk(ServerAddress, ou_response);
}
response.body().close();
}
else{
ou_response=mDiskLruCache.fetchFromDiskCache(ServerAddress);
}
if (ou_response != null) {
try {
JSONObject postObj = new JSONObject(ou_response);
JSONArray postsArray = postObj.optJSONArray("result");
for (int i = 0; i <= postsArray.length(); i++) {
JSONObject postObject = (JSONObject) postsArray.get(i);
int id = postObject.getInt("id");
Log.d("id", String.valueOf(id));
String title = postObject.getString("title");
String description = postObject.getString("full_description");
String image = postObject.getString("image");
String category = postObject.getString("categoryName");
String date = postObject.getString("date");
String url = postObject.getString("url");
Log.d("Data", "Post ID: " + id);
Log.d("Data", "Post title: " + title);
Log.d("Data", "Post image: " + image);
Log.d("Data", "Post url: " + url);
Log.d("Data", "---------------------------------");
//Use the title and id as per your requirement
infoModels.add(new DataModel(id, title, description, category, date, url, image));
}
} catch (JSONException e) {
e.printStackTrace();
Log.e("error", String.valueOf(e));
}
}
} catch (IOException e) {
e.printStackTrace();
Log.e("error2", String.valueOf(e));
}
return ou_response;
}
#Override
protected void onPostExecute(String result) {
//CustomProcessDialog.dissmis();
//Stop Progress
if (dialog.isShowing()) {
dialog.dismiss();
}
if (result != null) {
bus.post(new MyEvent("forfragment1", infoModels));
} else {
Toast.makeText(mContext, "Check Internet", Toast.LENGTH_LONG).show();
}
}
}
}
Adapter Codes:
public class free_recycler_adapter extends RecyclerView.Adapter<free_recycler_adapter.ViewHolder> {
private List<DataModel> mDateSet;
private Context context;
// Provide a suitable constructor (depends on the kind of dataset)
public free_recycler_adapter(Context context, List<DataModel> dataSet) {
this.context = context;
this.mDateSet = dataSet;
}
// Create new views (invoked by the layout manager)
#Override
public free_recycler_adapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
// create a new view
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.free_card_layout, parent, false);
// create ViewHolder
return new ViewHolder(view);
}
// Replace the contents of a view (invoked by the layout manager)
#Override
public void onBindViewHolder(ViewHolder viewHolder, final int position) {
// - get data from your itemsData at this position
// - replace the contents of the view with that itemsData
viewHolder.free_titleText.setText(Html.fromHtml(mDateSet.get(position).getTitle()));
viewHolder.free_titleText.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
v.getContext().startActivity(new Intent(v.getContext(), ContentPage.class)
.putExtra("title", mDateSet.get(position).getTitle())
.putExtra("desc", mDateSet.get(position).getDescription())
.putExtra("image", mDateSet.get(position).getImage())
.putExtra("url", mDateSet.get(position).getUrl())
.putExtra("category", mDateSet.get(position).getCategory())
.putExtra("date", mDateSet.get(position).getDate()));
}
});
Glide.with(context)
.load(mDateSet.get(position).getImage())
.placeholder(R.drawable.ic_download_image)
.crossFade()
.into(viewHolder.free_avatarImage);
viewHolder.free_avatarImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
v.getContext().startActivity(new Intent(v.getContext(), ContentPage.class)
.putExtra("title", mDateSet.get(position).getTitle())
.putExtra("desc", mDateSet.get(position).getDescription())
.putExtra("image", mDateSet.get(position).getImage())
.putExtra("url", mDateSet.get(position).getUrl())
.putExtra("category", mDateSet.get(position).getCategory())
.putExtra("date", mDateSet.get(position).getDate()));
}
});
viewHolder.free_descText.setText(Html.fromHtml(mDateSet.get(position).getDescription()));
viewHolder.free_descText.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
v.getContext().startActivity(new Intent(v.getContext(), ContentPage.class)
.putExtra("title", mDateSet.get(position).getTitle())
.putExtra("desc", mDateSet.get(position).getDescription())
.putExtra("image", mDateSet.get(position).getImage())
.putExtra("url", mDateSet.get(position).getUrl())
.putExtra("category", mDateSet.get(position).getCategory())
.putExtra("date", mDateSet.get(position).getDate()));
}
});
}
// Return the size of your dataset (invoked by the layout manager)
#Override
public int getItemCount() {
return mDateSet.size();
}
public void remove(int position) {
mDateSet.remove(position);
notifyItemRemoved(position);
}
public void clear() {
mDateSet.clear();
notifyDataSetChanged();
}
public void add(List<DataModel> models) {
mDateSet.addAll(models);
notifyDataSetChanged();
}
public void update(List<DataModel> models) {
mDateSet.clear();
mDateSet.addAll(models);
notifyDataSetChanged();
}
// inner class to hold a reference to each item of RecyclerView
public static class ViewHolder extends RecyclerView.ViewHolder {
public TextView free_titleText, free_descText;
public ImageView free_avatarImage;
public ViewHolder(View itemLayoutView) {
super(itemLayoutView);
free_titleText = (TextView) itemLayoutView.findViewById(R.id.pdf_card_title);
free_descText = (TextView) itemLayoutView.findViewById(R.id.pdf_card_content);
free_avatarImage = (ImageView) itemLayoutView.findViewById(R.id.pdf_card_image);
}
}
}
MainActivity codes:
public class Main_Page extends AppCompatActivity {
private CollapsingToolbarLayout mCollapsingToolbarLayout;
private Toolbar toolbar;
private TabLayout tabLayout;
private ViewPager viewPager;
private DrawerLayout mDrawer;
private NavigationView nvDrawer;
private ImageView menuImage;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main__page);
CalligraphyConfig.initDefault(new CalligraphyConfig.Builder()
.setDefaultFontPath("fonts/iransans.ttf")
.setFontAttrId(R.attr.fontPath)
.build());
mCollapsingToolbarLayout = (CollapsingToolbarLayout) findViewById(R.id.collapsing_toolbar_layout);
//mCollapsingToolbarLayout.setTitle(getResources().getString(R.string.app_name));
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setTitle("");
//getSupportActionBar().setDisplayHomeAsUpEnabled(true);
viewPager = (ViewPager) findViewById(R.id.viewpager);
setupViewPager(viewPager);
tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
setupTabIcons();
mDrawer = (DrawerLayout) findViewById(R.id.drawer_layout);
nvDrawer = (NavigationView) findViewById(R.id.navigation_drawer);
menuImage = (ImageView) findViewById(R.id.DrawableMenu_image);
menuImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mDrawer.openDrawer(GravityCompat.END);
}
});
}
/**
* Adding custom view to tab
*/
private void setupTabIcons() {
TextView tabOne = (TextView) LayoutInflater.from(this).inflate(R.layout.custom_tab, null);
tabOne.setText(R.string.free_fragment_title);
tabOne.setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.ic_download_image, 0, 0);
tabLayout.getTabAt(0).setCustomView(tabOne);
TextView tabTwo = (TextView) LayoutInflater.from(this).inflate(R.layout.custom_tab, null);
tabTwo.setText(R.string.paid_fragment_title);
tabTwo.setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.ic_paid_download_image, 0, 0);
tabLayout.getTabAt(1).setCustomView(tabTwo);
TextView tabThree = (TextView) LayoutInflater.from(this).inflate(R.layout.custom_tab, null);
tabThree.setText(R.string.pdf_fragment_title);
tabThree.setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.ic_pdf_icon, 0, 0);
tabLayout.getTabAt(2).setCustomView(tabThree);
}
/**
* Adding fragments to ViewPager
*
* #param viewPager
*/
private void setupViewPager(ViewPager viewPager) {
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
adapter.addFrag(new free_fragment(), "رایگان ها");
adapter.addFrag(new paid_fragment(), "پرداختی ها");
adapter.addFrag(new pdf_fragment(), "مقالات");
viewPager.setAdapter(adapter);
}
class ViewPagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
public ViewPagerAdapter(FragmentManager manager) {
super(manager);
}
#Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
#Override
public int getCount() {
return mFragmentList.size();
}
public void addFrag(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
}
#Override
public void onBackPressed() {
if (mDrawer.isDrawerOpen(GravityCompat.END)) {
mDrawer.closeDrawers();
} else
super.onBackPressed();
}
#Override
protected void attachBaseContext(Context newBase) {
super.attachBaseContext(CalligraphyContextWrapper.wrap(newBase));
}
}
How can i fix this and not duplicate datas when click on TabLayout ?
I am amateur and i really need this help, please help me. Thanks all<3
Check the commented code : It's causing the dataModels to be added every time to your adapter.
#Subscribe
public void onEvent(MyEvent event) {
List<DataModel> dataModels = event.getInfoModels();
if (event.fragmentTag.equals("forfragment1")) {
//mAdapter.add(dataModels);
isDataFetched = true;
mAdapter.notifyDataSetChanged();
}
}
In your adapter, in add() method, you are adding the data to the list all over again, this is unnecessary, calling notifyDataSetChanged automatically intimates the adapter that the original data has been changed.
Just call notifyDataSetChanged on adapter to refresh the updated data. Hope it helps.
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.