ViewPagerAdapter update fragment when starting again - android

I have the following ViewPagerAdapter:
private void setupViewPager(ViewPager viewPager) {
adapter = new ViewPagerAdapter(((AppCompatActivity)getActivity()).getSupportFragmentManager());
adapter.addFrag(new OwnerPendingBookingsFragment(), "Pendientes");
adapter.addFrag(new OwnerConfirmedBookingsFragment(), "Confirmados");
adapter.addFrag(new OwnerFinishedBookingsFragment(), "Finalizados");
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 android.support.v4.app.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);
}
}
And one of the fragments that I use is like that:
public class OwnerConfirmedBookingsFragment extends Fragment {
private View myView;
private ListView booking_list;
private ArrayAdapter adapter;
private SharedPreferences preferences;
private Toast toast;
private ProgressDialog progressDialog;
private BookingList bookings;
private boolean isFirstTime;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
if (isFirstTime) {
myView = inflater.inflate(R.layout.owner_confirmed_bookings_layout, container, false);
isFirstTime = false;
}
return myView;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
isFirstTime = true;
//Getting out sharedpreferences
preferences = getActivity().getSharedPreferences(Config.SHARED_PREF_LOGIN, Context.MODE_PRIVATE);
new FindBookings().execute("");
}
private void setUpAdapter(){
booking_list = (ListView) myView.findViewById(R.id.owner_confirmed_bookings);
getActivity().setTitle("Nuevas solicitudes");
if(bookings.getBookings().size() == 0){
booking_list.setVisibility(View.GONE);
LinearLayout no_vehicles = (LinearLayout) myView.findViewById(R.id.no_confirmed_bookings_layout);
no_vehicles.setVisibility(View.VISIBLE);
}else {
for (int i = 0; i < bookings.getBookings().size(); i++){
try {
new setImageTask(i).execute(bookings.getBookings().get(i).getDriver_image()).get();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}
adapter = new OwnerFinishedBookingsAdapter(myView.getContext(), bookings.getBookings());
booking_list.setAdapter(adapter);
booking_list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
int booking_line = bookings.getBookings().get(position).getBooking_line_id();
Fragment booking_info = new OwnerPendingBookingInfoFragment();
Bundle args = new Bundle();
args.putInt("bookingLine", booking_line);
booking_info.setArguments(args);
FragmentTransaction transaction = getFragmentManager().beginTransaction();
transaction.replace(R.id.content_frame, booking_info);
transaction.addToBackStack(null);
transaction.commit();
}
});
}
}
private class FindBookings extends AsyncTask<String, Void, String> {
String token = preferences.getString(Config.TOKEN, "");
#Override
protected void onPreExecute() {
toast = Toast.makeText(getActivity().getApplicationContext(), "", Toast.LENGTH_LONG);
progressDialog = new ProgressDialog(getActivity());
progressDialog.setMessage(getActivity().getString(R.string.finding_bookings));
progressDialog.show();
}
#Override
protected void onPostExecute(String s){
if(bookings.getError() != 0){
if(bookings.getError() == Config.JWT_EXPIRED){
logout();
Toast.makeText(getActivity().getApplicationContext(),
getActivity().getString(R.string.session_expired),
Toast.LENGTH_LONG).show();
}else {
toast.setText(getActivity().getString(R.string.find_pendings_errror));
toast.show();
}
}else {
setUpAdapter();
}
progressDialog.dismiss();
}
#Override
protected String doInBackground(String... params) {
bookings = DBConnect.getPendingBookingList(preferences.getInt(Config.IDUSER, 0), token);
return "done";
}
}
The first time I use it, all the fragments loads without any problem. But when I go to another activity and then return it doesn't update the data. I debug it and onCreate and onCreateView are not firing?
I tried to remove the fragment when going to another activity but nothing worked for me.

Related

Using only one Fragment with RecyclerView for multiple TabLayout , not updating data correctly on tabs change

There is a question similar to me, but that solution didn't work for my case.
The question I have referred is
this
I have a fragment named "HomeFragment" which consists of a VieWPager and TabLayout. I am adding tabs dynamically from the backend. So I am using another Fragment named "SecondFragment" for all tabs since all tabs contain a RecyclerView only. I am populating the RecyclerView onCreate() of the SecondFragment. My issue comes here that when I swipe or change the tab, the RecyclerView not updating correctly. On continuing swiping, the data changes but it does not correspond to the selected tab. I have logged the flow and I am getting correct data from backend on swiping, but it does not updating the RrecyclerView.
My HomeFragment class is
public class HomeFragment extends Fragment implements HTTPCallback {
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
private OnFragmentInteractionListener mListener;
private RecyclerView recyclerView;
private CardView cardview;
private boolean isShow;
View rootview;
private Toolbar toolbar;
private ImageView imageView, tabBg;
private CollapsingToolbarLayout collapsingToolbar;
private TabLayout mTabLayout;
Context context;
private ViewPager mViewPager, mViewPager1;
AppBarLayout appBarLayout;
Integer url_size;
int i;
boolean stopSliding = false;
String url, url2;
String message, version;
private ArrayList<HomeModel> planList;
JSONObject jsonObject, jsonObject2;
JSONArray jsonArray, jsonArray2;
ViewPagerAdapter adapter;
List<Product> products;
int numTab = 0;
private SharedPreferences sharedPreferences;
private SharedPreferences.Editor editor;
public HomeFragment() {
}
public static HomeFragment newInstance(String param1, String param2) {
HomeFragment fragment = new HomeFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
rootview = inflater.inflate(R.layout.fragment_home, container, false);
appBarLayout = (AppBarLayout) rootview.findViewById(R.id.appbar);
mViewPager1 = (ViewPager) rootview.findViewById(R.id.view_pager);
collapsingToolbar = (CollapsingToolbarLayout) rootview.findViewById(R.id.collapsing_toolbar);
sharedPreferences = getContext().getSharedPreferences("spade", Context.MODE_PRIVATE);
editor = sharedPreferences.edit();
mViewPager = (ViewPager) rootview.findViewById(R.id.viewpager);
mTabLayout = (TabLayout) rootview.findViewById(R.id.tabs);
mTabLayout.setSelectedTabIndicatorColor(Color.parseColor("#FF0000"));
mTabLayout.setSelectedTabIndicatorHeight((int) (5 * getResources().getDisplayMetrics().density));
mTabLayout.setTabTextColors(Color.parseColor("#727272"), Color.parseColor("#FF0000"));
new HTTPRequest(getContext(), null, null, HTTPRequest.METHOD.GET, this).execute(url2);
mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
if (position == 0) {
appBarLayout.setExpanded(true);
} else {
appBarLayout.setExpanded(false);
}
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
try {
} catch (Exception e) {
e.printStackTrace();
}
mTabLayout.setOnTabSelectedListener(
new TabLayout.ViewPagerOnTabSelectedListener(mViewPager) {
#Override
public void onTabSelected(TabLayout.Tab tab) {
super.onTabSelected(tab);
mViewPager.setCurrentItem(tab.getPosition());
numTab = tab.getPosition();
HomeModel browsePlan = planList.get(numTab);
editor.putString("tab", browsePlan.getName()).commit();
}
});
return rootview;
}
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
#Override
public void onConnectionStarted() {
}
#Override
public void onConnectionFailed() {
}
#Override
public void onCompleted(JSONObject resultData) {
HomeModel model;
planList = new ArrayList<>();
adapter = new ViewPagerAdapter(getChildFragmentManager());
try {
jsonArray = resultData.getJSONArray("details");
editor.putString("tab", jsonArray.getJSONObject(0).getString("name"));
editor.commit();
for (int i = 0; i < jsonArray.length(); i++) {
jsonObject2 = jsonArray.getJSONObject(i);
model = new HomeModel();
model.setCatid(jsonObject2.getString("id"));
model.setImage(jsonObject2.getString("image"));
model.setName(jsonObject2.getString("name"));
planList.add(model);
setupViewPager(mViewPager, jsonObject2.getString("name"));
}
setAdapter();
} catch (JSONException e) {
e.printStackTrace();
}
}
private void setAdapter() {
appBarLayout.setExpanded(false);
mViewPager.setAdapter(adapter);
mTabLayout.setupWithViewPager(mViewPager);
}
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
void onFragmentInteraction(Uri uri);
}
private void setupViewPager(ViewPager mViewPager, String name) {
adapter.addFragment(new SecondFragment(), name);
mViewPager.setOffscreenPageLimit(1);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
}
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 addFragment(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
}
}
SecondFragment class is
public class SecondFragment extends Fragment implements HTTPCallback {
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
String mParam1;
String mParam2;
Button solo, grp;
View rootview;
Fragment fragment;
String url;
JSONObject jsonObject, jsonObject2;
JSONArray jsonArray, jsonArray2;
private ArrayList<Spaceship> planList;
RecyclerView rv;
private RecyclerHomeAdapter adapter = new RecyclerHomeAdapter(getContext(), planList);
;
private SharedPreferences sharedPreferences;
String tab_name;
private OnFragmentInteractionListener mListener;
public SecondFragment() {
}
public static SecondFragment newInstance(String s, String s1) {
SecondFragment fragment = new SecondFragment();
Bundle args = new Bundle();
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
rootview = inflater.inflate(R.layout.fragment_second, container, false);
sharedPreferences = getContext().getSharedPreferences("spade", Context.MODE_PRIVATE);
tab_name = sharedPreferences.getString("tab", "onnumilla");
rv = (RecyclerView) rootview.findViewById(R.id.rv);
rv.setLayoutManager(new LinearLayoutManager(getContext()));
url = "My_url_here";
HashMap<String, String> data = new HashMap<String, String>();
data.put("name", tab_name);
new HTTPRequest2(getContext(), data, null, HTTPRequest2.METHOD.POST, this).execute(url);
return rootview;
}
#Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
if (isVisibleToUser) {
adapter.notifyDataSetChanged();
// getFragmentManager().beginTransaction().detach(this).attach(this).commit();
}
}
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
#Override
public void onConnectionStarted() {
}
#Override
public void onConnectionFailed() {
}
#Override
public void onCompleted(JSONObject resultData) {
Spaceship model;
planList = new ArrayList<>();
planList.clear();
try {
jsonArray = resultData.getJSONArray("products");
for (int i = 0; i < jsonArray.length(); i++) {
jsonObject2 = jsonArray.getJSONObject(i);
model = new Spaceship();
model.setName(jsonObject2.getString("package_name"));
model.setImage(jsonObject2.getString("images"));
planList.add(model);
}
setAdapter();
} catch (JSONException e) {
e.printStackTrace();
}
}
private void setAdapter() {
adapter = new RecyclerHomeAdapter(getContext(), planList);
adapter.notifyDataSetChanged();
rv.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
void onFragmentInteraction(Uri uri);
}
}
This doesn't work for me. But in the setUserVisibleHint(boolean isVisibleToUser) method when i add getFragmentManager().beginTransaction().detach(this).attach(this).commit();
instead of adapter.notifyDataSetChanged(); it works but it takes some time to hide previous data on swiping tab.
Anyone, please suggest me a solution. I have referred many questions but nothing works for me. All your response is appreciated.
This seems to be ViewPager page cashing issue. pls call below code from onCreateView()
of HomeFragment.
mViewPager.setOffscreenPageLimit(1);

How to handle back button in tab's fragment?

I have an activity,and have 2 fragments thats name is AddressFragment and ProfileFragment thats extend from BaseFragment.
How i can handle back button in tab fragment.
if a info_ll(a linearlayout) is show,when back button is pressed gone and a recyclerview is show
and if recyclerview is showing,when back press button clicked finish activity
public class ProfileActivity extends AppCompatActivity{
TabLayout tabLayout;
ViewPager viewPager;
public void setTv_name(String tv_name) {
ProfileActivity.tv_name.setText(tv_name);
}
public void setTv_email(String tv_email) {
ProfileActivity.tv_email.setText(tv_email);
}
public void setTv_phone(String tv_phone) {
ProfileActivity.tv_phone.setText(tv_phone);
}
public static MyTextView tv_name;
public static MyTextView tv_email;
public static MyTextView tv_phone;
CircularImageView iv_profile;
ImageButton btn_back;
BaseFragment currentFragment;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile);
viewPager = (ViewPager) findViewById(R.id.viewpager);
setupViewPager(viewPager);
tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
TabLayout tabhost = (TabLayout) this.findViewById(R.id.tabs);
tabhost.getTabAt(getIntent().getIntExtra("go_to",0)).select();
tv_name= (MyTextView) findViewById(R.id.tv_name);
tv_email= (MyTextView)findViewById(R.id.tv_email);
tv_phone= (MyTextView)findViewById(R.id.tv_phone);
iv_profile= (CircularImageView) findViewById(R.id.profile);
btn_back= (ImageButton) findViewById(R.id.btn_Back);
btn_back.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
finish();
}
});
}
private void setupViewPager(ViewPager viewPager) {
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
adapter.addFragment(new ProfileFragment(), "ویرایش اطلاعات");
adapter.addFragment(new AddressFragment(), "آدرس های منتخب");
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) {
currentFragment = null;
switch (position) {
case 0:
currentFragment = new ProfileFragment();
break;
case 1:
currentFragment = new AddressFragment();
break;
}
return currentFragment;
}
#Override
public int getCount() {
return mFragmentList.size();
}
public void addFragment(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
}
public void setImage(){
if(!DataContainer.getObject().getProfileImagePath().equals("None"))
Glide.with(this).load(DataContainer.getObject().getProfileImagePath()).into(iv_profile);
}
#Override
public void onBackPressed() {
if(currentFragment == null || !currentFragment.onBackPressed())
super.onBackPressed();
}
}
AddressFragment
public class AddressFragment extends BaseFragment {
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
private String mParam1;
private String mParam2;
private OnFragmentInteractionListener mListener;
ProgressDialog pDialog;
int pDilog_Counter=0;
private View rootView;
private RecyclerView recyclerView;
MyEditText et_title;
MyEditText et_address;
LinearLayout info_ll;
Button btn_edit;
ImageButton btn_location;
FloatingActionButton fab;
double latitude;
double longitude;
public static final int RESULT_OK = -1;
int status=0;
int profileID=0;
public AddressFragment() {
}
public static AddressFragment newInstance(String param1, String param2) {
AddressFragment fragment = new AddressFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
rootView = inflater.inflate(R.layout.fragment_address, container, false);
info_ll= (LinearLayout) rootView.findViewById(R.id.info_ll);
et_title= (MyEditText) rootView.findViewById(R.id.et_title);
et_address= (MyEditText) rootView.findViewById(R.id.et_address);
btn_edit= (Button) rootView.findViewById(R.id.btn_edit);
btn_location= (ImageButton) rootView.findViewById(R.id.btn_location);
fab= (FloatingActionButton) rootView.findViewById(R.id.fab);
recyclerView= (RecyclerView) rootView.findViewById(R.id.Address_recycler);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
recyclerView.setVisibility(View.GONE);
fab.setVisibility(View.GONE);
info_ll.setVisibility(View.VISIBLE);
status=0;
btn_edit.setText("ثبت");
//PAProfileAddressAdd();
}
});
private static class SimpleAdapter extends RecyclerView.Adapter<SimpleAdapter.ViewHolder> {
private JSONArray Addresses;
AddressFragment addressFragment;
public SimpleAdapter(AddressFragment addressFragment, JSONArray AddressArray) {
this.addressFragment=addressFragment;
this.Addresses=AddressArray;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.address_recyclerview_item, parent, false);
return new ViewHolder(itemView);
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
holder.bind(position);
}
#Override
public int getItemCount() {
return Addresses.length();
}
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
private MyTextView title;
private int position;
public ViewHolder(View itemView) {
super(itemView);
title = (MyTextView) itemView.findViewById(R.id.address_txt);
itemView.setOnClickListener(this);
}
public void bind(int position) {
this.position = position;
try {
title.setText(Addresses.getJSONObject(position).getString("Title"));
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
public void onClick(View view) {
addressFragment.status=1;
addressFragment.rootView.findViewById(R.id.Address_recycler).setVisibility(View.GONE);
addressFragment.rootView.findViewById(R.id.fab).setVisibility(View.GONE);
addressFragment.rootView.findViewById(R.id.info_ll).setVisibility(View.VISIBLE);
addressFragment.et_title.setEnabled(false);
addressFragment.et_address.setEnabled(false);
try {
addressFragment.et_title.setText(Addresses.getJSONObject(position).getString("Title"));
} catch (JSONException e) {
e.printStackTrace();
}
try {
addressFragment.et_address.setText(Addresses.getJSONObject(position).getString("Address"));
} catch (JSONException e) {
e.printStackTrace();
}
addressFragment.status=1;
try {
addressFragment.profileID=Integer.parseInt(Addresses.getJSONObject(position).getString("ProfileAddressID"));
} catch (JSONException e) {
e.printStackTrace();
}
//TODO open edit dialog for Addresses.getJSONObject(position)
}
}
}
#Override
public boolean onBackPressed() {
if(info_ll.getVisibility()==View.VISIBLE){
fab.setVisibility(View.VISIBLE);
recyclerView.setVisibility(View.VISIBLE);
info_ll.setVisibility(View.GONE);
return true;
}else {
return false;
}
}
}
ProfileFragment
public class ProfileFragment extends BaseFragment {
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
private String mParam1;
private String mParam2;
private OnFragmentInteractionListener mListener;
Button btn_edit;
EditText et_name;
EditText et_phone;
EditText et_email;
ProgressDialog pDialog;
int pDilog_Counter=0;
public ProfileFragment() {
// Required empty public constructor
}
public static ProfileFragment newInstance(String param1, String param2) {
ProfileFragment fragment = new ProfileFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v=inflater.inflate(R.layout.fragment_profile, container, false);
btn_edit=(Button) v.findViewById(R.id.btn_edit);
et_name= (EditText) v.findViewById(R.id.et_name);
et_email= (EditText) v.findViewById(R.id.et_email);
et_phone= (EditText) v.findViewById(R.id.et_phone);
PAProfileInfo();
btn_edit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
PAProfileEdit();
}
});
((ProfileActivity)getActivity()).setImage();
return v;
}
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
public interface OnFragmentInteractionListener {
void onFragmentInteraction(Uri uri);
}
private void PAProfileInfo() {
String url="http://RO.nirasoftware.com:8888/WS/WSPAProfileInfo.aspx?"+
"CustomerCode="+ DataContainer.getObject().getCustomerCode() +
"&TokenID="+ DataContainer.getObject().getTokenID() +
"&Type=JSON&VS="+DataContainer.getObject().getVersion();
showProgress();
StringRequest request = new StringRequest(Request.Method.GET,url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject NRS=(new JSONObject(response)).getJSONObject("NRS");
if(NRS.getJSONObject("Error").getInt("ErrCode")==0){
Toast.makeText(getActivity(),NRS.getJSONObject("Error").getString("ErrFa"), Toast.LENGTH_SHORT).show();
try {
et_name.setText(NRS.getJSONObject("Customer").getString("CustomerFullName"));
et_email.setText(NRS.getJSONObject("Customer").getString("EMail"));
et_phone.setText(NRS.getJSONObject("Customer").getString("MobileNo"));
((ProfileActivity)getActivity()).setTv_name(NRS.getJSONObject("Customer").getString("CustomerFullName"));
((ProfileActivity)getActivity()).setTv_email(NRS.getJSONObject("Customer").getString("EMail"));
((ProfileActivity)getActivity()).setTv_phone(NRS.getJSONObject("Customer").getString("MobileNo"));
}catch (JSONException e){
}
hideProgress();
}else{
Toast.makeText(getActivity(),NRS.getJSONObject("Error").getString("ErrFa"), Toast.LENGTH_SHORT).show();
hideProgress();
}
} catch (JSONException e) {
Toast.makeText(getActivity(),"Error in json received", Toast.LENGTH_LONG).show();
hideProgress();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
//VolleyLog.d(TAG, "Error: " + error.getMessage());
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity(),R.style.MyDialogTheme);
// 2. Chain together various setter methods to set the dialog characteristics
String s=error.getMessage();
if(error.networkResponse==null)
s="سرعت کم اتصال";
else
s+="\nResponse:\n\t"+error.networkResponse.toString();
builder.setMessage(s).setTitle("خطا:");
// 3. Get the AlertDialog from create()
AlertDialog dg = builder.create();
dg.setButton(AlertDialog.BUTTON_POSITIVE, "تلاش مجدد", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
ProfileFragment.this.PAProfileInfo();
} });
dg.setButton(AlertDialog.BUTTON_NEGATIVE, "انصراف", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
getActivity().finish();
} });
dg.show();
hideProgress();
//getWindow().clearFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE);
}
});
DataContainer.getObject().getRequestQueue().add(request);
}
private void PAProfileEdit() {
String url="http://RO.nirasoftware.com:8888/WS/WSPAProfileEdit.aspx?"+
"CustomerCode="+ DataContainer.getObject().getCustomerCode() +
"&TokenID="+ DataContainer.getObject().getTokenID() +
"&Type=JSON&VS="+DataContainer.getObject().getVersion()+
"&FullName="+et_name.getText().toString()+
"&Email=" + et_email.getText().toString()+
"&Phone="+et_phone.getText().toString();
showProgress();
StringRequest request = new StringRequest(Request.Method.GET,url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject NRS=(new JSONObject(response)).getJSONObject("NRS");
if(NRS.getJSONObject("Error").getInt("ErrCode")==0){
Toast.makeText(getActivity(),NRS.getJSONObject("Error").getString("ErrFa"), Toast.LENGTH_SHORT).show();
((ProfileActivity)getActivity()).setTv_name(et_name.getText().toString());
DataContainer.getObject().setName(et_name.getText().toString());
((ProfileActivity)getActivity()).setTv_email(et_email.getText().toString());
DataContainer.getObject().setEMail(et_email.getText().toString());
((ProfileActivity)getActivity()).setTv_phone(et_phone.getText().toString());
DataContainer.getObject().setPhoneNo(et_phone.getText().toString());
hideProgress();
}else{
Toast.makeText(getActivity(),NRS.getJSONObject("Error").getString("ErrFa"), Toast.LENGTH_SHORT).show();
hideProgress();
}
} catch (JSONException e) {
Toast.makeText(getActivity(),"Error in json received", Toast.LENGTH_LONG).show();
hideProgress();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
//VolleyLog.d(TAG, "Error: " + error.getMessage());
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity(),R.style.MyDialogTheme);
// 2. Chain together various setter methods to set the dialog characteristics
String s=error.getMessage();
/* if(error.networkResponse!=null)
//TODO #$# s+="\nResponse:\n\t"+error.networkResponse.toString();
else*/
s="سرعت کم اتصال";
builder.setMessage(s).setTitle("خطا:");
// 3. Get the AlertDialog from create()
AlertDialog dg = builder.create();
dg.setButton(AlertDialog.BUTTON_POSITIVE, "تلاش مجدد", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
PAProfileEdit();
} });
dg.show();
hideProgress();
//getWindow().clearFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE);
}
});
DataContainer.getObject().getRequestQueue().add(request);
}
private void showProgress() {
pDilog_Counter++;
if(pDilog_Counter>1)
return;
pDialog = new ProgressDialog(getActivity(),R.style.AppCompatAlertDialogStyle);
pDialog.setMessage("لطفا منتظر بمانید....");
pDialog.show();
getActivity().getWindow().setFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE,
WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE);
}
private void hideProgress() {
pDilog_Counter--;
if(pDilog_Counter>0)
return;
pDialog.hide();
pDialog.dismiss();
getActivity().getWindow().clearFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE);
}
#Override
public boolean onBackPressed() {
return false;
}
}
BaseFragment
public abstract class BaseFragment extends Fragment {
public abstract boolean onBackPressed();
}
You have to give each fragment a unique TAG it will help you to easily retrieve
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.container, new PlaceholderFragment(), "First Fragment")
.commit();
Retrieve(e.g. in on back pressed)
Fragment fragment = getSupportFragmentManager().findFragmentByTag("FirstFragment");
if (fragment == null) {
fragment = new PlaceholderFragment();
}
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.container, fragment, "FirstFragment")
.commit();
Fainally i found solution I find the current fragment's tag which show in viepager and compare whit AddressFragment class
#Override
public void onBackPressed() {
BaseFragment fragment =
(BaseFragment) getSupportFragmentManager().findFragmentByTag(
"android:switcher:"+R.id.viewpager+":"+viewPager.getCurrentItem());
if(fragment instanceof AddressFragment) // could be null if not instantiated yet
{
if(!fragment.onBackPressed())
super.onBackPressed();
}else
super.onBackPressed();

Content not updating on changing tabs in viewpager - Tablayout

I am storing dynamic ids from arraylist to each tabs that are created dynamically and
I have used ViewPagerOnTabSelectedListener , and it is getting id of the tab that is clicked and stores it in a sharedpreference.
I am using that id from sharedpreference into fragment get the customlist in each tab based on that id.
NOw, the problem is the customlist is not getting refreshed on tab click , but it has already fetched old values , its not getting updated as per the id from the sharedpreference
public class ScrollableTabsActivity extends AppCompatActivity {
private Toolbar toolbar;
private TabLayout tabLayout;
private ViewPager viewPager;
ConnectionClass connectionClass;
ArrayList<String> al,idal,pidal;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_scrollable_tabs);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowTitleEnabled(false);
viewPager = (ViewPager) findViewById(R.id.viewpager);
tabLayout = (TabLayout) findViewById(R.id.tabs);
connectionClass = new ConnectionClass();
al = new ArrayList<String>();
idal = new ArrayList<String>();
pidal = new ArrayList<String>();
ScrollableTabsActivity.DoLogin doLogin = new ScrollableTabsActivity.DoLogin();
doLogin.execute("");
}
private void setupTags() {
int i;
for(i=0;i<al.size();i++) {
/* Tag t= new Tag();
t.setId(idal.get(i));
tabLayout.getTabAt(i).setTag(t);
*/
tabLayout.getTabAt(i).setTag(idal.get(i));
}
tabLayout.setOnTabSelectedListener(new TabLayout.ViewPagerOnTabSelectedListener(viewPager){
#Override
public void onTabSelected(TabLayout.Tab tab) {
super.onTabSelected(tab);
// CharSequence numTab = ((Tag)tab.getTag()).getId();
CharSequence numTab = tab.getTag().toString();
SharedPreferences preferences2 = getSharedPreferences("AUTHENTICATION_FILE_NAME2", Context.MODE_WORLD_WRITEABLE);
SharedPreferences.Editor editor2 = preferences2.edit();
editor2.putString("tabselected",numTab.toString());
editor2.putString("Authentication_Status", "true");
editor2.apply();
}
});
}
private void setupViewPager(ViewPager viewPager) {
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
int i;
for(i=0;i<al.size();i++){
adapter.addFrag(new MainActivity(), al.get(i),idal.get(i));
}
viewPager.setAdapter(adapter);
}
class ViewPagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
private final List<String> mFragmentId = 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,String id) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
mFragmentId.add(id);
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
public int getItemPosition(Object object) {
return POSITION_NONE;
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Take appropriate action for each action item click
switch (item.getItemId()) {
case R.id.action_cart:
cart();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
/**
* Launching new activity
* */
private void cart() {
Intent i = new Intent(ScrollableTabsActivity.this, Cart.class);
startActivity(i);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public void onBackPressed() {
super.onBackPressed();
Vibrator v = (Vibrator) getApplicationContext().getSystemService(Context.VIBRATOR_SERVICE);
v.vibrate(500);
MainActivity m= new MainActivity();
m.vacatelist();
}
public class DoLogin extends AsyncTask<String,String,String>
{
String z = "";
Boolean isSuccess = false;
#Override
protected void onPreExecute() {
}
#Override
protected void onPostExecute(String r) {
if(isSuccess) {
SharedPreferences preferences2 = getSharedPreferences("AUTHENTICATION_FILE_NAME2", Context.MODE_WORLD_WRITEABLE);
SharedPreferences.Editor editor2 = preferences2.edit();
editor2.putString("tabselected",idal.get(0).toString());
editor2.putString("Authentication_Status", "true");
editor2.apply();
setupViewPager(viewPager);
tabLayout.setupWithViewPager(viewPager);
setupTags();
}
else {
Toast.makeText(ScrollableTabsActivity.this,r, Toast.LENGTH_SHORT).show();
}
}
#Override
protected String doInBackground(String... params) {
try {
Connection con = connectionClass.CONN();
if (con == null) {
z = "Error in connection with SQL server";
} else {
String query = "SELECT ID,Category_ItemName,Pi_Category_ID FROM [dbo].[MainMenuDetail] where Pi_Category_ID=0 and Delete_category=0";
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(query);
while (rs.next())
{
idal.add(rs.getString("ID"));
al.add(rs.getString("Category_ItemName"));
pidal.add(rs.getString("Pi_Category_ID"));
}
z = "Successful";
isSuccess=true;
}
}
catch (Exception ex)
{
isSuccess = false;
z = "Exceptions";
}
return z;
}
}
}
public class MainActivity extends android.support.v4.app.Fragment {
// Log tag
private static final String TAG = MainActivity.class.getSimpleName();
ConnectionClass connectionClass;
// Movies json url
String url="http://i.imgur.com/mQPXunb.png";
private List<Movie> movieList = new ArrayList<Movie>();
private ListView listView;
private CustomListAdapter adapter;
private List templist = new ArrayList();
String image_url = "http://app.dartenogroup.com/admin/img/";
String image_url2="";
NetworkImageView img;
String restid;
Movie movie;
String tabselected;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.activity_main, container, false);
}
#Override
public void onViewCreated(View view,Bundle savedInstanceState){
super.onViewCreated(view,savedInstanceState);
SharedPreferences prfs = getActivity().getSharedPreferences("AUTHENTICATION_FILE_NAME", Context.MODE_PRIVATE);
restid = prfs.getString("restid", "");
SharedPreferences prfs2 = getActivity().getSharedPreferences("AUTHENTICATION_FILE_NAME2", Context.MODE_PRIVATE);
tabselected = prfs2.getString("tabselected", "");
Toast.makeText(getActivity(), tabselected, Toast.LENGTH_SHORT).show();
connectionClass = new ConnectionClass();
listView = (ListView) view.findViewById(R.id.list);
adapter = new CustomListAdapter(getActivity(), movieList);
listView.setAdapter(adapter);
img = (NetworkImageView) view.findViewById(R.id.thumbnail);
// changing action bar color
//getActionBar().setBackgroundDrawable(
// new ColorDrawable(Color.parseColor("#ffffff")));
DoLogin doLogin = new DoLogin();
doLogin.execute("");
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Intent i2 = new Intent(getActivity(), ViewProduct.class);
TextView tv=(TextView)view.findViewById(R.id.itemid);
i2.putExtra("value",tv.getText().toString());
startActivity(i2);
}
});
}
/**
* On selecting action bar icons
* */
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Take appropriate action for each action item click
switch (item.getItemId()) {
case R.id.action_cart:
cart();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
/**
* Launching new activity
* */
private void cart() {
Intent i = new Intent(getActivity(), Cart.class);
startActivity(i);
}
public class DoLogin extends AsyncTask<String,String,String>
{
String z = "";
Boolean isSuccess = false;
#Override
protected void onPreExecute() {
movieList.clear();
templist.clear();
}
#Override
protected void onPostExecute(String r) {
if(isSuccess) {
updatelist();
Vibrator v = (Vibrator) getActivity().getSystemService(Context.VIBRATOR_SERVICE);
v.vibrate(500);
}
else{
Toast.makeText(getActivity(),z,Toast.LENGTH_SHORT).show();
}
}
#Override
protected String doInBackground(String... params) {
try {
Connection con = connectionClass.CONN ();
if (con == null) {
z = "Error in connection with SQL server";
} else {
String query = "select * from [dbo].[MainMenuDetail] WHERE Delete_category = 0 AND Pi_Category_ID ='"+tabselected+"'" ;
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(query);
while (rs.next()) {
movie = new Movie();
movie.setId(rs.getString("ID"));
movie.setItemname(rs.getString("Category_ItemName"));
movie.setDescription(rs.getString("Category_SHortDesc"));
movie.setPrice(rs.getString("Category_Price"));
image_url2=rs.getString("show_Image");
String img= image_url+image_url2;
movie.setThumbnailUrl(img);
update();
}
z = "Successful";
isSuccess=true;
}
}
catch (Exception ex)
{
isSuccess = false;
z = "Exceptions";
}
return z;
}
}
public void updatelist(){
new Handler(Looper.getMainLooper()).post(new Runnable() {
#Override
public void run() {
movieList.addAll(templist);
adapter.notifyDataSetChanged();
}
});
}
public void refreshlist(){
new Handler(Looper.getMainLooper()).post(new Runnable() {
#Override
public void run() {
adapter.notifyDataSetChanged();
}
}); }
public void vacatelist(){
new Handler(Looper.getMainLooper()).post(new Runnable() {
#Override
public void run() {
movieList.clear();
}
});
}
public void update(){
templist.add(movie);
}
}
you can try this
#Override
public void onTabSelected(TabLayout.Tab tab) {
CharSequence numTab = tab.getTag().toString();
SharedPreferences preferences2 = getSharedPreferences("AUTHENTICATION_FILE_NAME2", Context.MODE_WORLD_WRITEABLE);
SharedPreferences.Editor editor2 = preferences2.edit();
editor2.putString("tabselected",numTab.toString());
editor2.putString("Authentication_Status", "true");
editor2.apply();
// super called last
super.onTabSelected(tab);
}
or store ViewPagerAdapter adapter "globally" on top of ScrollableTabsActivity (not only inside setupViewPager method)
ViewPagerAdapter adapter;
private void setupViewPager(ViewPager viewPager) {
adapter = new ViewPagerAdapter(getSupportFragmentManager());
//rest of your code
}
and then
#Override
public void onTabSelected(TabLayout.Tab tab) {
// your current code
adapter.notifyDataSetChanged(); //ViewPagerAdapter's adapter
}
There might be several Solution to this issue i.e.
1.) Load all your data at once if you have less data and less tabs and also you can increase
viewPager.setOffscreenPageLimit(noOfTabs);
2.) Update your fragment once it is visible to the user.
#Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
if (isVisibleToUser){
// load data
}
}
Hope that will be helpful.

RecyclerView in fragment through activity get position

so here is my problem, i have only one activity from i launch my viewpager fragment, in my viewpager i have 4 fragments containing recyclerViews. Every Fragment contains item populated by data on the net, when i click into one i get a WebView Fragment, but when i click on the backbutton i lost my poisiton, cause it's recreating the whole activity.
I don't know how to not recreate the activity and get back my old position, or recreating it but not changing the item's positions and have my old position back. Here's my code. Where i should put what ?! Some help would be very very well come.
Thank You !!
My Activity Class :
public class LauncherActivity extends AppCompatActivity implements ListFragment.OnNewSelectedInterface{
public static final String VIEWPAGER_FRAGMENT = "view_pager";
private ImageView mImageView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_launcher);
RelativeLayout relativeLayout = (RelativeLayout) findViewById(R.id.activity_launcher);
mImageView = (ImageView) findViewById(R.id.logoImageView);
mImageView.startAnimation(AnimationUtils.loadAnimation(this, R.anim.rotate_indefinitely));
if(!isNetworkAvailable()){
alertUserAboutError();
} else {
relativeLayout.postDelayed(new Runnable() {
#Override
public void run() {
ViewPagerFragment savedFragment = (ViewPagerFragment)
getSupportFragmentManager().findFragmentByTag(VIEWPAGER_FRAGMENT);
if(savedFragment == null) {
ViewPagerFragment viewPagerFragment = new ViewPagerFragment();
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.add(R.id.activity_launcher, viewPagerFragment, VIEWPAGER_FRAGMENT);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
}
}
}, 2000);
}
}
#Override
public void onListNewSelected(int index, ArrayList<Articles> articles) {
WebViewFragment webViewFragment = new WebViewFragment();
Bundle bundle = new Bundle();
bundle.putInt(ViewPagerFragment.KEY_NEW_INDEX, index);
bundle.putParcelableArrayList(ListFragment.KEY_LIST, articles);
webViewFragment.setArguments(bundle);
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.activity_launcher, webViewFragment, WebViewFragment.WEBVIEWFRAGMENT);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
}
private boolean isNetworkAvailable() {
ConnectivityManager manager = (ConnectivityManager)
getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = manager.getActiveNetworkInfo();
boolean isAvailable = false;
if (networkInfo != null && networkInfo.isConnected()) {
isAvailable = true;
}
return isAvailable;
}
private void alertUserAboutError() {
AlertDialogFragment alertDialogFragment = new AlertDialogFragment();
alertDialogFragment.show(getFragmentManager(), "error_dialog");
}
}
My ViewPagerClass :
public class ViewPagerFragment extends Fragment {
public static final String KEY_NEW_INDEX = "key_new_index";
private ViewPager mViewPager;
private TabLayout mTabLayout;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
final View view = inflater.inflate(R.layout.fragment_view_pager, container, false);
final OldFactFragment oldFactFragment = new OldFactFragment();
final SportFragment sportFragment = new SportFragment();
final BuzzFragment buzzFragment = new BuzzFragment();
final NewsFragment newsFragment = new NewsFragment();
mViewPager = (ViewPager) view.findViewById(R.id.viewPager);
mTabLayout = (TabLayout) view.findViewById(R.id.tabLayout);
mViewPager.setOffscreenPageLimit(4);
mViewPager.setAdapter(new FragmentPagerAdapter(getChildFragmentManager()) {
#Override
public Fragment getItem(int position) {
if(position == 0){
return oldFactFragment;
} else if (position == 1) {
return newsFragment;
} else if (position == 2){
return sportFragment;
} else return buzzFragment;
}
#Override
public CharSequence getPageTitle(int position) {
if(position == 0){
return "Pastly";
} else if (position == 1) {
return "politic";
} else if (position == 2){
return "sport";
} else return "buzz";
}
#Override
public int getCount() {
return 4;
}
});
mTabLayout.setupWithViewPager(mViewPager);
return view;
}
}
My ListFragment(Parent's class of the 4 Fragments in the ViewPager) :
public abstract class ListFragment extends Fragment {
public static final String KEY_LIST = "key_list";
public interface OnNewSelectedInterface {
void onListNewSelected(int index, ArrayList<Articles> articles);
}
protected static final String TAG = ListFragment.class.getSimpleName();
protected ArrayList<Articles> mArticlesList;
protected ItemAdapter mArticleAdapter;
protected RecyclerView mRecyclerView;
protected OnNewSelectedInterface mListener;
protected RecyclerView.LayoutManager mManager;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
mListener = (OnNewSelectedInterface) getActivity();
View view = inflater.inflate(R.layout.fragment_list, container, false);
mRecyclerView = (RecyclerView) view.findViewById(R.id.recyclerview);
getInfos(getUrl());
return view;
}
protected abstract String[] getUrl();
private void getInfos(String[] url) {
if (isNetworkAvailable()) {
OkHttpClient client = new OkHttpClient();
for (int i = 0; i < getUrl().length; i++) {
Request request = new Request.Builder().url(url[i]).build();
client.newCall(request).enqueue(new Callback() {
#Override
public void onResponse(Call call, Response response) throws IOException {
try {
String jsonData = response.body().string();
if (response.isSuccessful()) {
Log.v(TAG, jsonData);
getMultipleUrls(jsonData);
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
getCurrentArticles(mArticlesList);
}
});
} else {
alertUserAboutError();
}
} catch (IOException | JSONException e) {
e.printStackTrace();
}
}
#Override
public void onFailure(Call call, IOException e) {
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
alertUserAboutError();
}
});
}
});
}
} else{
alertUserAboutError();
}
}
private void getMultipleUrls(String jsonData) throws JSONException {
if (mArticlesList == null) {
mArticlesList = getArticleForecast(jsonData);
} else {
mArticlesList.addAll(getArticleForecast(jsonData));
}
}
private void getCurrentArticles(ArrayList<Articles> articles) {
mArticleAdapter = new ItemAdapter(getActivity(), articles, mListener);
mRecyclerView.setAdapter(mArticleAdapter);
mManager = new LinearLayoutManager(getActivity());
mRecyclerView.setLayoutManager(mManager);
}
private boolean isNetworkAvailable() {
ConnectivityManager manager = (ConnectivityManager) getActivity().
getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = manager.getActiveNetworkInfo();
boolean isAvailable = false;
if (networkInfo != null && networkInfo.isConnected()) {
isAvailable = true;
}
return isAvailable;
}
private void alertUserAboutError() {
AlertDialogFragment alertDialogFragment = new AlertDialogFragment();
alertDialogFragment.show(getActivity().getFragmentManager(), "error_dialog");
}
private ArrayList<Articles> getArticleForecast(String jsonData) throws JSONException {
JSONObject forecast = new JSONObject(jsonData);
JSONArray articles = forecast.getJSONArray("articles");
ArrayList<Articles> listArticles = new ArrayList<>(articles.length());
for (int i = 0; i < articles.length(); i++) {
JSONObject jsonArticle = articles.getJSONObject(i);
Articles article = new Articles();
String urlImage = jsonArticle.getString("urlToImage");
article.setTitle(jsonArticle.getString("title"));
article.setDescription(jsonArticle.getString("description"));
article.setImageView(urlImage);
article.setArticleUrl(jsonArticle.getString("url"));
listArticles.add(i, article);
}
return listArticles;
}
}
And my ItemAdapter (Adapter Class) :
public class ItemAdapter extends RecyclerView.Adapter<ItemAdapter.ArticleViewHolder> {
private final ListFragment.OnNewSelectedInterface mListener;
protected ArrayList<Articles> mArticlesList;
protected Context mContext;
private int mPosition;
private int lastPosition = -1;
public ItemAdapter(Context contexts, ArrayList<Articles> mArticleLi, ListFragment.OnNewSelectedInterface listener){
mContext = contexts;
mArticlesList = mArticleLi;
mListener = listener;
}
#Override
public ArticleViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.list_item_linear, parent, false);
view.findViewById(R.id.textView).setSelected(true);
ArticleViewHolder articleViewHolder = new ArticleViewHolder(view);
articleViewHolder.setIsRecyclable(false);
return articleViewHolder;
}
#RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
#Override
public void onBindViewHolder(ArticleViewHolder holder, int position) {
mPosition = position;
holder.bindArticle(mArticlesList.get(position));
setAnimation(holder.itemView, position);
holder.mImageView.setClipToOutline(true);
}
private void setAnimation(View viewToAnimate, int position) {
if (position > lastPosition) {
Animation animation = AnimationUtils.loadAnimation(viewToAnimate.getContext(), android.R.anim.slide_in_left);
viewToAnimate.startAnimation(animation);
lastPosition = position;
}
}
#Override
public int getItemCount() {
return mArticlesList.size();
}
public class ArticleViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener, View.OnLongClickListener{
private TextView mTitle, mArticle;
private ImageView mImageView;
private ArticleViewHolder(View itemView) {
super(itemView);
mTitle = (TextView) itemView.findViewById(R.id.textView);
mArticle = (TextView) itemView.findViewById(R.id.showTextView);
mImageView = (ImageView) itemView.findViewById(R.id.imageView2);
itemView.setOnClickListener(this);
itemView.setOnLongClickListener(this);
}
private void bindArticle(Articles article) {
mTitle.setText(article.getTitle());
mArticle.setText(article.getDescription());
mArticle.setVisibility(View.INVISIBLE);
Glide.with(mContext).load(article.getImageView()).into(mImageView);
}
#Override
public void onClick(View view) {
mListener.onListNewSelected(getLayoutPosition(), mArticlesList);
}
#Override
public boolean onLongClick(View view) {
String desc = mArticlesList.get(getAdapterPosition()).getDescription();
mArticle.setVisibility(View.VISIBLE);
mArticle.setText(desc);
mArticle.postDelayed(new Runnable() {
public void run() {
mArticle.setVisibility(View.INVISIBLE);
}
}, 3000);
return true;
}
}
}
In Your method onListNewSelected You are Replacing the new fragment with the old one as stated in this line
fragmentTransaction.replace(R.id.activity_launcher, webViewFragment, WebViewFragment.WEBVIEWFRAGMENT);
From Google Documentaion
Replace an existing fragment that was added to a container. This is essentially the same as calling remove(Fragment) for all currently added fragments that were added with the same containerViewId and then add(int, Fragment, String) with the same arguments given here.
So you are removing the old Fragment then adding the new one, When you are back to get the old fragment, It is not already there it will be created from scratch, So the position is already gone with the removed fragment.
While using the add method, Will add the new fragment above the previous one, when you go back the previous one already there with its state "Position"

Update the row item data of recyclerview

The fragment consists of View Pager which shows the product count that
needs to be updated when the product is deleted or added .
public class SubCategoryFragment extends BaseFragment implements OnItemClickListener
{
private View rootView;
private MasterCategory subCategory;
private RecyclerView subCategoryRecyclerView;
private SubCategoryListAdapter subCategoryListAdapter;
private ArrayList<MasterCategory> superSubCategories;
private String iconImageURL;
private ArrayList<MerchantOrder> merchantorder;
/*private IRequestComplete iRequestComplete;*/
private int categoryId;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
super.onCreateView(inflater, container, savedInstanceState);
return rootView = inflater.inflate(R.layout.fragment_category_list, container, false);
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState)
{
super.onActivityCreated(savedInstanceState);
initialiseUI();
}
initialise fragment
protected void initialiseUI()
{
categoryId = getArguments().getInt("categoryId");
iconImageURL = (String) getArguments().getSerializable("iconImageURL");
subCategory = (MasterCategory) getArguments().getSerializable("data");
subCategoryRecyclerView = (RecyclerView) rootView.findViewById(R.id.category_list_rc_view);
rootView.findViewById(R.id.dashboard_progressbar_newlyadded).setVisibility(View.GONE);
subCategoryRecyclerView.setHasFixedSize(true);
LinearLayoutManager mLayoutManager = new LinearLayoutManager(context);
subCategoryRecyclerView.setLayoutManager(mLayoutManager);
superSubCategories = subCategory.getCategories();
rootView.findViewById(R.id.dashboard_progressbar_newlyadded).setVisibility(View.GONE);
if (superSubCategories != null && !superSubCategories.isEmpty())
{
subCategoryListAdapter = new SubCategoryListAdapter(superSubCategories, iconImageURL);
subCategoryRecyclerView.setAdapter(subCategoryListAdapter);
subCategoryListAdapter.setmOnItemClickListener(this);
updateListView();
}
else
{
rootView.findViewById(R.id.text_no_order_error).setVisibility(View.VISIBLE);
((TextView) rootView.findViewById(R.id.text_no_order_error)).setText("No Category found!");
}
}
Update the listview
private void updateListView()
{
if (subCategoryListAdapter == null)
{
subCategoryListAdapter = new SubCategoryListAdapter(superSubCategories,iconImageURL);
subCategoryRecyclerView.setAdapter(subCategoryListAdapter);
}
else
{
subCategoryListAdapter.notifyDataSetChanged();
}
subCategoryListAdapter.notifyDataSetChanged();
}
the itemclick opens up a fragment which displays the product details
#Override
public void onItemClick(View view, int position)
{
/*MasterCategory superSubCategories = subCategoryListAdapter.getSuperSubCategory(position);
Bundle bundle = new Bundle();
bundle.putSerializable("data", superSubCategories);
SuperSubCategoryProductsFragment superSubCategoryProductsFragment = new SuperSubCategoryProductsFragment();
superSubCategoryProductsFragment.setArguments(bundle);
manageFragment(superSubCategoryProductsFragment, SuperSubCategoryProductsFragment.class.getName(), CategoryDetailsFragment.class.getName(), bundle);*/
/*ArrayList<MasterCategory> superSubCategories = subCategoryListAdapter.getSuperSubCategory(position).getCategories();
if (null != superSubCategories){
Bundle bundle = new Bundle();
bundle.putSerializable("data", superSubCategories);
SuperSubCategoryListFragment categoryDetailsFragment = new SuperSubCategoryListFragment();
categoryDetailsFragment.setArguments(bundle);
manageFragment(categoryDetailsFragment, SuperSubCategoryListFragment.class.getName(), SubCategoryFragment.class.getName(), null);
}*/
MasterCategory superSubCategories = subCategoryListAdapter.getSuperSubCategory(position);
superSubCategories.getSubCategoryCount();
superSubCategories.getProductCount();
subCategoryListAdapter.notifyDataSetChanged();
if (superSubCategories.isHasChildCategory())
{
Bundle bundle = new Bundle();
bundle.putSerializable("data", superSubCategories);
Intent intent = new Intent(context, BaseFragmentActivity.class);
intent.putExtra("toolbarTitle", superSubCategories.getName());
intent.putExtra("FragmentClassName", SuperSubCategoryFragment.class.getName());
intent.putExtra("data", bundle);
startActivity(intent);
}
else
{
Intent intent = new Intent(context, BaseFragmentActivity.class);
Bundle bundle = new Bundle();
bundle.putInt("categoryId", superSubCategories.getCategoryId());
bundle.putString("categoryName", superSubCategories.getName());
bundle.putBoolean("isSubCatProducts", !superSubCategories.isHasChildCategory());
bundle.putInt("ProductCount", superSubCategories.getProductCount());
intent.putExtra("toolbarTitle", superSubCategories.getName());
intent.putExtra("FragmentClassName", SubCategoryProductsFragment.class.getName());
intent.putExtra("data", bundle);
startActivity(intent);
}
}
#Override
public void onPause()
{
super.onPause();
}
#Override
public void onResume()
{
super.onResume();
}
#Override
public void onAttachedToRecyclerView(RecyclerView recyclerView)
{
super.onAttachedToRecyclerView(subCategoryRecyclerView);
subCategoryRecyclerView.getAdapter().notifyDataSetChanged();
}
}
This is my Adapter attached to the fragment
public class SubCategoryListAdapter extends RecyclerView.Adapter<SubCategoryListAdapter.ViewHolder> implements View.OnClickListener {
private static final String TAG = SubCategoryListAdapter.class.getSimpleName();
private ArrayList<MasterCategory> superSubCategories;
private ImageLoader imageloader;
private com.amoda.androidlib.intf.OnItemClickListener mOnItemClickListener;
private String iconImageURL;
#Override
public void onClick(View view)
{
if (mOnItemClickListener != null)
mOnItemClickListener.onItemClick(view, (Integer) view.getTag());
}
public class ViewHolder extends RecyclerView.ViewHolder
{
public TextView name;
public TextView productCount;
public NetworkImageView image;
public ViewHolder(View itemLayoutView)
{
super(itemLayoutView);
productCount = (TextView) itemLayoutView.findViewById(R.id.product_count);
name = (TextView) itemLayoutView.findViewById(R.id.name);
image = (NetworkImageView) itemLayoutView.findViewById(R.id.image);
}
}
public SubCategoryListAdapter(ArrayList<MasterCategory> superSubCategories, String iconImageURL)
{
this.superSubCategories = superSubCategories;
imageloader = Global.getInstance().getImageLoader();
this.iconImageURL = iconImageURL;
}
#Override
public SubCategoryListAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType)
{
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.super_category_list_row, parent, false);
ViewHolder vh = new ViewHolder(v);
return vh;
}
#Override
public void onBindViewHolder(final ViewHolder holder, final int position)
{
holder.name.setText("" + superSubCategories.get(position).getName());
holder.image.setDefaultImageResId(R.drawable.logo_amoda);
holder.image.setImageUrl(iconImageURL, imageloader);
if(!superSubCategories.get(position).isHasChildCategory())
{
holder.productCount.setText("" + superSubCategories.get(position).getProductCount());
}
else
{
holder.productCount.setText("");
holder.productCount.setBackgroundResource(R.drawable.icn_right_arrow);
}
holder.itemView.setTag(position);
holder.itemView.setOnClickListener(this);
}
public void setmOnItemClickListener(com.amoda.androidlib.intf.OnItemClickListener mOnItemClickListener)
{
this.mOnItemClickListener = mOnItemClickListener;
}
#Override
public int getItemCount()
{
if (superSubCategories != null)
return superSubCategories.size();
else
return 0;
}
public MasterCategory getSuperSubCategory(int position)
{
return superSubCategories.get(position);
}
}
This is my View pager in my activity
private void showSubCategoryTabs()
{
setToolbarTitle(category != null ? category.getName() : "");
try
{
mPromotionalImage.setDefaultImageResId(R.drawable.nodeals_img);
mPromotionalImage.setImageUrl(category.getImageUrl(), imageLoader);
}
catch (Exception e)
{
e.printStackTrace();
}
tabContent = new ArrayList<String>();
for (MasterCategory subCategories : category.getCategories())
{
/*Check if the sub-sub category has super-sub category or not.*/
if (null != subCategories.getCategories())
tabContent.add(subCategories.getName());
}
mViewPager.setAdapter(mSectionsPagerAdapter);
final TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setTabMode(TabLayout.MODE_SCROLLABLE);
mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener()
{
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels)
{
}
#Override
public void onPageSelected(int position)
{
Fragment fragment = ((SectionsPagerAdapter) mViewPager.getAdapter()).getFragment(position);
if (fragment != null)
{
fragment.onResume();
}
}
#Override
public void onPageScrollStateChanged(int state)
{
}
});
}
public class SectionsPagerAdapter extends FragmentStatePagerAdapter
{
private SectionsPagerAdapter sectionspageradapter;
private FragmentManager fragmentManager=null;
private Bundle bundle=new Bundle();
public SectionsPagerAdapter(FragmentManager fm)
{
super(fm);
fragmentManager=fm;
}
#Override
public Object instantiateItem(ViewGroup container,int position)
{
Object obj=super.instantiateItem(container,position);
if(obj instanceof Fragment)
{
Fragment f=(Fragment)obj;
String tag=f.getTag();
f.onResume();
}
return obj;
}
#Override
public Fragment getItem(int position)
{
MasterCategory subCategories = category.getCategories().get(position);
if (subCategories.isHasChildCategory())
{
SubCategoryFragment subCategoryFragment = new SubCategoryFragment();
Bundle bundle = new Bundle();
bundle.putSerializable("iconImageURL", category.getIconImageUrl());
bundle.putSerializable("data", category.getCategories().get(position));
subCategoryFragment.setArguments(bundle);
return subCategoryFragment;
}
else
{
SubCategoryProductsFragment subCategoryProductsFragment = new SubCategoryProductsFragment();
Bundle bundle = new Bundle();
bundle.putInt("categoryId", subCategories.getCategoryId());
bundle.putString("categoryName", subCategories.getName());
bundle.putBoolean("isSubCatProducts", true);
subCategoryProductsFragment.setArguments(bundle);
return subCategoryProductsFragment;
}
}
#Override
public int getCount()
{
return tabContent.size();
}
#Override
public CharSequence getPageTitle(int position)
{
Locale l = Locale.getDefault();
return tabContent.get(position);
}
public Fragment getFragment(int position)
{
String tag = String.valueOf(mMerchantSubCategories.get(position));
return fragmentManager.findFragmentByTag(tag);
}
}
#Override
public void onResume()
{
if (!EventBus.getDefault().isRegistered(this))
EventBus.getDefault().register(this);
super.onResume();
}
#Override
protected void onPause()
{
super.onPause();
}
#Override
public void onStop()
{
super.onStop();
//*Unregister event bus when the app goes in background*//*
if (EventBus.getDefault().isRegistered(this))
EventBus.getDefault().unregister(this);
}
#Override
public void onDestroy()
{
super.onDestroy();
if (EventBus.getDefault().isRegistered(this))
EventBus.getDefault().unregister(this);
}
public void onError(VolleyError volleyError)
{
UIHelper.stopProgressDialog(mProgressDialog);
Functions.Application.VolleyErrorCheck(this, volleyError);
}
just add this method to your viewPager adapter and your problem is solved.
#Override
public int getItemPosition(Object object) {
return POSITION_NONE;
}
this is override method of viewPager.
when you swipe one fragment to another it will automatically refresh page.
try this approach.. maybe its work for you..
put this code in your SubCategoryListAdepter
public void delete(int position) { //removes the row
superSubCategories.remove(position);
notifyItemRemoved(position);
}
make onClickListener to your ViewHolder:
suppose you click on your text and this row will be deleted.
#Override
public void onClick(View v) {
if(v.getId() == R.id.name){
//calls the method above to delete
delete(getAdapterPosition());
}
now you can also add data like this way.. thats working fine at runtime.. no need to refresh your page.

Categories

Resources