Glide not reload the images from server - android-glide

I have a recyclerview that displays photos.
this is my adapter:
public class CustomerImageListAdapter extends RecyclerView.Adapter<CustomerImageListAdapter.Holder> {
private Context context;
private List<String> imageUrls;
public CustomerImageListAdapter(Context context, List<String> imageUrls) {
this.context = context;
this.imageUrls = imageUrls;
}
#NonNull
#Override
public Holder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View rootview = LayoutInflater.from(context).inflate(R.layout.customer_onitemclick_image_viewpager_item, parent, false);
return new Holder(rootview);
}
#Override
public void onBindViewHolder(#NonNull Holder holder, int position) {
Glide.with(context).load(imageUrls.get(position)).into(holder.imageView);
if (imageUrls.size() != 0) {
for (int i = 0; i < imageUrls.size(); i++) {
Log.i("urls", "onBindViewHolder: " + imageUrls.get(i));
}
}
}
#Override
public int getItemCount() {
return imageUrls.size();
}
class Holder extends RecyclerView.ViewHolder {
ImageView imageView;
public Holder(#NonNull View itemView) {
super(itemView);
imageView = itemView.findViewById(R.id.customer_onitemclick_image_viewpager_item_imageview);
}
}
public void setImageUrls(List<String> imageUrls1) {
imageUrls.addAll(imageUrls1);
notifyDataSetChanged();
}
}
when i set the "imageurls" in the constructor, recyclerview show the images perfectly;
imageListAdapter = new CustomerImageListAdapter(getContext(),urls);
but when i set in constructor "new ArrayList()" and use "setImagesUrls" method to update "imageurls",
then recyclerview don't show images .
imageListAdapter = new CustomerImageListAdapter(getContext(),new ArrayList<String>());
...
...
...
#Override{
public void onChanged(List<String> strings)
imageListAdapter.setImageUrls(strings);
}
While based on the "log" ,address of the images are received from the server.
#Override
public void onBindViewHolder(#NonNull Holder holder, int position)
{
Glide.with(context).load(imageUrls.get(position)).into(holder.imageView);
if (imageUrls.size() != 0) {
for (int i = 0; i < imageUrls.size(); i++) {
Log.i("urls", "onBindViewHolder: " + imageUrls.get(i));
}
}
}
thanks for your help

Related

Why are my floating action buttons not working properly in my ViewPager?

I have a ViewPager set up with my app and am trying to also set two floating action buttons, a left one and a right one, to do the same thing as the ViewPager, so that the user has a choice in terms of navigation. I'm trying to have it set so that the left button is invisible on the first page, and the right button is invisible on the last page, but the appearances of the buttons seem to be sporadic. I've tried debugging the app, and upon testing each situation, the appropriate code is executed, so I can't understand why this behavior is happening. Any help would be appreciated.
TestFragment:
public class TestFragment extends Fragment {
public static final String ARG_ID = "Id";
private int Id;
private String title;
private TextView titleTV;
private String description;
private TextView descriptionTV;
private int number;
private TextView numberTV;
private FloatingActionButton leftBtn;
private FloatingActionButton rightBtn;
public static TestFragment newInstance(int Id) {
Bundle args = new Bundle();
args.putSerializable(ARG_ID, Id);
TestFragment fragment = new TestFragment();
fragment.setArguments(args);
return fragment;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_test, container, false);
Id = getArguments().getInt(ARG_ID);
title = Test.testData[Id].getTitle();
description = Test.testData[Id].getDescription();
number = Test.testData[Id].getNumber();
titleTV = view.findViewById(R.id.title);
titleTV.setText(title);
descriptionTV = view.findViewById(R.id.description);
descriptionTV.setText(description);
numberTV = view.findViewById(R.id.number);
numberTV.setText(String.valueOf(number));
leftBtn = view.findViewById(R.id.left_btn);
rightBtn = view.findViewById(R.id.right_btn);
toggleButtons();
leftBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
testViewPager.setCurrentItem(--index);
toggleButtons();
}
});
rightBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
testViewPager.setCurrentItem(++index);
toggleButtons();
}
});
return view;
}
public void toggleButtons() {
if(index == 0) {
leftBtn.setVisibility(View.INVISIBLE);
}
else if(index == Test.testData.length - 1) {
rightBtn.setVisibility(View.INVISIBLE);
}
else {
leftBtn.setVisibility(View.VISIBLE);
rightBtn.setVisibility(View.VISIBLE);
}
}
}
TestPagerActivity:
public class TestPagerActivity extends AppCompatActivity {
public static int index;
public static ViewPager testViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test_pager);
index = (int) getIntent().getSerializableExtra(EXTRA_ID);
testViewPager = findViewById(R.id.test_view_pager);
FragmentManager fragmentManager = getSupportFragmentManager();
testViewPager.setAdapter(new FragmentStatePagerAdapter(fragmentManager) {
#Override
public Fragment getItem(int position) {
return TestFragment.newInstance(position);
}
#Override
public int getCount() {
return Test.testData.length;
}
});
for(int i = 0; i < Test.testData.length; i++) {
if(i == index) {
testViewPager.setCurrentItem(i);
break;
}
}
}
}

Retrieve data from Firebase in Recycler view using fragment take too much time

I am using two fragments in the main activity, In first fragment[FirstFragment] load data from firebase and show in Recycler view, In the second fragment[uploadUserCarInformation] take data from user and store at the firebase,
I am facing a problem when the application starts then first fragment load very quickly and data show but when replace the first fragment from the second fragment and when replacing back from the second fragment to the first fragment then take 4 to 5 minutes to load data from firebase in recyclerView.
Kindly tell me where I modify the code,
Main Activity
public class MainActivity extends AppCompatActivity {
FrameLayout simpleFrameLayout;
TabLayout tabLayout;
Fragment fragment1 = new FirstFragment();
Fragment fragment2 =new SecondFragment();
#SuppressLint("WrongViewCast")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// get the reference of FrameLayout and TabLayout
tabLayout=findViewById(R.id.simpleTabLayout);
simpleFrameLayout = (FrameLayout) findViewById(R.id.simpleFrameLayout);
FragmentManager fm = getSupportFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
ft.replace(R.id.simpleFrameLayout, fragment1);
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
ft.addToBackStack(null);
ft.commit();
// perform setOnTabSelectedListener event on TabLayout
tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
// get the current selected tab's position and replace the fragment accordingly
switch (tab.getPosition()) {
case 0:
tab.getIcon().setColorFilter(null);
fragmentReplace(fragment1,"fragment1");
break;
case 1:
fragmentReplace(fragment2,"fragment2");
break;
}
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
}
public void fragmentReplace(Fragment fragment,String fragmentName)
{
FragmentManager fm = getSupportFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
ft.replace(R.id.simpleFrameLayout, fragment);
Log.d("Running Fragment",fragmentName+ " is running");
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
ft.addToBackStack(null);
ft.commit();
}
}
FirstFragment
public class FirstFragment extends Fragment {
private RecyclerView mRecyclerView;
private ImageAdapter mAdapter;
private DatabaseReference mDatabaseRef;
private List<carInformation> mUpload;
View view;
public FirstFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//retrieveAndSendData();
Log.d("Lifecycle","onCreate called");
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
Log.d("Lifecycle","onCreateView called");
view=inflater.inflate(R.layout.fragment_first,container,false);
mRecyclerView=view.findViewById(R.id.recyler_view);
mRecyclerView.setHasFixedSize(true);
mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
return view;
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
Log.d("Lifecycle","onViewCreate called");
retrieveAndSendData();
}
public void retrieveAndSendData()
{
mUpload=new ArrayList<>();
mDatabaseRef= FirebaseDatabase.getInstance().getReference();
ValueEventListener valueEventListener=new ValueEventListener() {
#Override
//get firebase data using datasnapshot (read data)
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for(DataSnapshot postSnapshot : dataSnapshot.getChildren())
{
String key = postSnapshot.getKey();
DatabaseReference databaseReference=mDatabaseRef.child(key);
for (DataSnapshot child: postSnapshot.getChildren())
{
String userBookId = child.getKey();
if(userBookId.equals("city") )
{
break;
}
else
{
// Toast.makeText(getActivity(),userBookId,Toast.LENGTH_LONG).show();
databaseReference.child(userBookId).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
carInformation userInformationObj=dataSnapshot.getValue(carInformation.class);
mUpload.add(userInformationObj);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
}
}
mAdapter = new ImageAdapter(getActivity(),mUpload);
mRecyclerView.setAdapter(mAdapter);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Toast.makeText(getActivity(),databaseError.getMessage(),Toast.LENGTH_SHORT).show();
}
};
mDatabaseRef.addValueEventListener(valueEventListener);
}
uploadUserCarInformation
public class uploadUserCarInformation extends Fragment {
View view;
FirebaseAuth firebaseAuth;
DatabaseReference databaseReference;
StorageReference storageReference;
private StorageTask mUploadTask;
ImageView imageView;
static int PICK_IMAGE=1;
Spinner spin;
// mdatabase.push().getkey() -> generate uniqe id
RadioGroup radioGroupCondition,radioGroupTransmission,radioGroupSupported;
RadioButton radioButtonCondition,radioButtonTranmission,radioButtonSupported;
String radioButtonConditionString,radioButtonSupportedString,radioButtonTransmissionString;
Button addCar,signout;
int selectedIdCondition,selectedIdTransmission,selectedIdSupported;
String ownerName,carName,phoneNuberString,countryString;
TextInputLayout name,carNamePlusModel,phoneNumber,country;
carInformation car_Information=new carInformation();
private ProgressBar progressBar;
private Uri imageUri;
String[] bankNames=new String[374];
InputStream in;
int i=0;
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#RequiresApi(api = Build.VERSION_CODES.O)
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
view=inflater.inflate(R.layout.upload_user_car_information,container,false);
firebaseAuth=FirebaseAuth.getInstance();
storageReference=FirebaseStorage.getInstance().getReference("uploads");
name=view.findViewById(R.id.textFieldCarOwner);
carNamePlusModel=view.findViewById(R.id.textFieldCarNameModel);
phoneNumber=view.findViewById(R.id.textFieldPhoneNumber2);
addCar=view.findViewById(R.id.addCar);
signout=view.findViewById(R.id.sign_out);
progressBar=view.findViewById(R.id.progress_bar);
// progressBar.getProgressDrawable().setColorFilter(
// Color.RED, android.graphics.PorterDuff.Mode.SRC_IN);
radioGroupCondition=view.findViewById(R.id.radioGroupCarCondtion);
radioGroupSupported=view.findViewById(R.id.radioGroupCarSupport);
radioGroupTransmission=view.findViewById(R.id.radioGroupCarTransmission);
// progressBar=new ProgressBar(getActivity());
spin = view.findViewById(R.id.Countryspinner2);
imageView=(ImageView) view.findViewById(R.id.selectImage);
//imageView.setImageResource(R.drawable.select_image);
try
{
InputStream fr = this.getResources().openRawResource(R.raw.cities);
BufferedReader br = new BufferedReader(new InputStreamReader(fr));
ArrayList<String> lines=new ArrayList<String>();
String currentLine=br.readLine();
while(currentLine!=null)
{
lines.add(currentLine);
currentLine=br.readLine();
}
Collections.sort(lines);
fr.close(); //closes the stream and release the resources
for(String line : lines)
{
bankNames[i]=line;
// System.out.println(line);
i++;
}
}
catch(IOException e)
{
e.printStackTrace();
}
ArrayAdapter<String> aa=new ArrayAdapter<String>(getActivity(),android.R.layout.simple_spinner_item,bankNames);
aa.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
AdapterView.OnItemSelectedListener listener = new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
};
spin.setOnItemSelectedListener(listener);
spin.setAdapter(aa);
signout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
firebaseAuth.signOut();
Fragment fragment = new SecondFragment();
FragmentManager fm = getFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
ft.replace(R.id.simpleFrameLayout, fragment);
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
ft.commit();
}
});
imageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onFileChooser();
}
});
addCar.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(mUploadTask !=null && mUploadTask.isInProgress())
{
Toast.makeText(getActivity(),"Uploading Task",Toast.LENGTH_SHORT).show();
}
else
{
carImageAndDetailUploading();
}
}
});
return view;
}
#Override
public void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == PICK_IMAGE && resultCode == RESULT_OK && data != null && data.getData() != null)
{
imageUri = data.getData();
//A powerful image downloading and caching library and get image from library for Android
Picasso.with(getActivity()).load(imageUri).into(imageView);
}
}
private void carImageAndDetailUploading()
{
FirebaseUser user=firebaseAuth.getCurrentUser();
databaseReference= FirebaseDatabase.getInstance().getReference(user.getUid());
selectedIdCondition=radioGroupCondition.getCheckedRadioButtonId();
radioButtonCondition=view.findViewById(selectedIdCondition);
radioButtonConditionString=radioButtonCondition.getText().toString();
selectedIdSupported=radioGroupSupported.getCheckedRadioButtonId();
radioButtonSupported=view.findViewById(selectedIdSupported);
radioButtonSupportedString=radioButtonSupported.getText().toString();
selectedIdTransmission=radioGroupTransmission.getCheckedRadioButtonId();
radioButtonTranmission=view.findViewById(selectedIdTransmission);
radioButtonTransmissionString=radioButtonTranmission.getText().toString();
ownerName=name.getEditText().getText().toString().trim();
carName=carNamePlusModel.getEditText().getText().toString().trim();
phoneNuberString=phoneNumber.getEditText().getText().toString().trim();
countryString=spin.getSelectedItem().toString();
if(TextUtils.isEmpty(ownerName) || TextUtils.isEmpty(carName) || TextUtils.isEmpty(phoneNuberString) || TextUtils.isEmpty(countryString))
{
Toast.makeText(getActivity(),"Please fill the empty fields ",Toast.LENGTH_LONG).show();
return; //return stooping the function to execute further
}
else if(imageUri == null)
{
Toast.makeText(getActivity(),"No file Selected ",Toast.LENGTH_LONG).show();
return;
}
long phone=Long.parseLong(phoneNuberString);
car_Information.setCarName(carName);
car_Information.setOwnerName(ownerName);
car_Information.setUserPhoneNumber(phone);
car_Information.setCountry(countryString);
car_Information.setCarCondtion(radioButtonConditionString);
car_Information.setCarSupported(radioButtonSupportedString);
car_Information.setCarTransmission(radioButtonTransmissionString);
StorageReference fileReference=storageReference.child(System.currentTimeMillis()+ "." + getFileExtension(imageUri));
mUploadTask = fileReference.putFile(imageUri)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
//below code user can see 100 % progress bar for 5 sec
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
progressBar.setProgress(0);
}
},5000);
String uniqueKey=databaseReference.push().getKey();
Task<Uri> urlTask = taskSnapshot.getStorage().getDownloadUrl();
while (!urlTask.isSuccessful());
Uri downloadUrl = urlTask.getResult();
car_Information.setImageUrl(downloadUrl.toString());
car_Information.setUnique_key(uniqueKey);
// databaseReference.child("car details"+car_Information.getUnique_key());
// databaseReference.child("car details"+car_Information.getUnique_key()).setValue(car_Information);
databaseReference.child(car_Information.getUnique_key());
databaseReference.child(car_Information.getUnique_key()).setValue(car_Information);
Toast.makeText(getActivity(),"Successfully Upload",Toast.LENGTH_SHORT).show();
clear_editText();
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(getActivity(),e.getMessage(),Toast.LENGTH_SHORT).show();
}
})
.addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
#Override
public void onProgress(UploadTask.TaskSnapshot taskSnapshot) {
double progress=(100.0 * taskSnapshot.getBytesTransferred() / taskSnapshot.getTotalByteCount());
progressBar.setProgress((int) progress);
}
});
}
private void onFileChooser()
{
Intent intent =new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("image/*");
startActivityForResult(intent,PICK_IMAGE);
//startActivityForResult(Intent.createChooser(intent,"Select Picture"),PICK_IMAGE);
}
private String getFileExtension(Uri uri)
{
//this method for get file extension
ContentResolver cR=getActivity().getContentResolver();
MimeTypeMap mime=MimeTypeMap.getSingleton();
return mime.getExtensionFromMimeType(cR.getType(uri));
}
private void clear_editText()
{
name.getEditText().setText(" ");
carNamePlusModel.getEditText().setText(" ");
phoneNumber.getEditText().setText(" ");
}
}
enter image description here
enter image description here

onClick button in adapter

I have a button in the recyclerview, and I want when I click the button then it will go to the next page. I try like this in my adapter but my app currently force close and in logcat nothing happens..
CustomerAdapter.java
public class CustomerAdapter extends RecyclerView.Adapter<CustomerAdapter.CustomerViewHolder> {
ArrayList<Customer> datasSet;
public CustomerAdapter(ArrayList<Customer> tempData) {
this.datasSet = tempData;
}
#Override
public CustomerViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.activity_customer_index_row, parent, false);
return new CustomerViewHolder(itemView);
}
#Override
public void onBindViewHolder(CustomerAdapter.CustomerViewHolder holder, int position) {
Customer csModel = datasSet.get(position);
holder.name.setText(csModel.getCustNama());
holder.button.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
Log.i("ratri2", "onClick: sukses ");
Intent intent = new Intent(context, GenerateSpkActivity.class);
context.startActivity(intent);
}
});
}
#Override
public int getItemCount() {
return datasSet.size();
}
public class CustomerViewHolder extends RecyclerView.ViewHolder {
public TextView name;
public Button button;
public CustomerViewHolder(View itemView) {
super(itemView);
name = itemView.findViewById(R.id.customer_name);
button= itemView.findViewById(R.id.btnGenerate);
}
}
}

Fragment in ViewPager shows nothing while returning from another fragment

I have a ViewPager in the fragment named FragmentHome, and the viewpager contains fragments. Am using FragmentStatePagerAdapter for this. When the fragmentHome loads first the fragments in Viewpager show perfectly. I have another fragment named FragmentCountryList to select a country, according to that country the fragments in the viewpager to be refreshed/updated. Now The problem is after selecting the country, the country fragment is popped and returns to the FragmentHome, but, there nothing is showing in the view pager, if we scrolls the second page(fragment) can be viewed then scrolls back the first page(fragment) can be viewed.
Am new with the FragmentStatePagerAdapter, so i couldn't rectify the reason for this problem. Please Help. The code i used gives below
public class FragmentHome extends WeGrabBaseFragment {
private static String TAG = "FragmentHome";
private HomeDealsDataClass homeDealsDataClass;//1, homeDealsDataClass2;
private ViewPager viewPagerHome;
private ImageView imgViewDealIndicator;
private OnCitySelectedListener onCitySelectedListener;
private FragPageAdapter fragAdapt;
private ArrayList<HomeDealsDataClass> arrayListHomeData;
private FragmentHomeDetails fragmentHomeDetails1,fragmentHomeDetails2;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Activity = (WeGrabBaseActivity) this.getActivity();
}
#Override
public void onResume() {
super.onResume();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater
.inflate(R.layout.fragment_home, container, false);
((WeGrabMainActivity) Activity).showBottomBar();
((WeGrabMainActivity) Activity).setShowActionBar();
((WeGrabMainActivity) Activity).setHeading(PrefUtil.getCityName(Activity));
((WeGrabMainActivity) Activity).defaultButtonState();
viewPagerHome = (ViewPager) v.findViewById(R.id.viewPagerHome);
viewPagerHome.setOffscreenPageLimit(2);
imgViewDealIndicator = (ImageView) v.findViewById(R.id.imgViewDealIndicator);
Picasso.with(Activity).load(R.drawable.deals1).into(imgViewDealIndicator);
viewPagerHome.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
if (position == 0) {
Picasso.with(Activity).load(R.drawable.deals1).into(imgViewDealIndicator);
} else if (position == 1) {
Picasso.with(Activity).load(R.drawable.deals2).into(imgViewDealIndicator);
}
}
#Override
public void onPageSelected(int position) {
fragAdapt.notifyDataSetChanged();
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
onCitySelectedListener = new OnCitySelectedListener() {
#Override
public void onCitySelected() {
fetchFromWeb();
}
};
fetchFromWeb();
return v;
}
private void fetchFromWeb() {
if (Activity.isNetworkAvailable()) {
if (VolleyUtils.volleyEnabled) {
Activity.startSpinwheel(false, true);
JSONObject jsonObject = new JSONObject();
try {
if (!PrefUtil.isGPSLocation(Activity)) {
jsonObject.putOpt(AppConstants.COUNTRY_ID, PrefUtil.getCountryCode(Activity));
jsonObject.putOpt(AppConstants.CITY_ID, PrefUtil.getCityCode(Activity));
Log.e(TAG, "Not GPS Home : " + jsonObject.toString());
CommandFactory commandFactory = new CommandFactory();
commandFactory.sendPostCommand(
AppConstants.WEGRAB_HOME_URL, jsonObject);
} else {
/*jsonObject.putOpt(AppConstants.COUNTRY_NAME, PrefUtil.getCountryName(Activity));
jsonObject.putOpt(AppConstants.CITY_NAME, PrefUtil.getCityName(Activity));*/
jsonObject.putOpt(AppConstants.COUNTRY_ID, "112");
jsonObject.putOpt(AppConstants.CITY_ID, "6");
CommandFactory commandFactory = new CommandFactory();
Log.e(TAG, "In GPS Home : " + jsonObject.toString());
/*commandFactory.sendPostCommand(
AppConstants.WEGRAB_HOME_URL_GPS, jsonObject);*/
commandFactory.sendPostCommand(
AppConstants.WEGRAB_HOME_URL, jsonObject);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
#Override
public void onHomeDetailsPageDataLoadedSuccessfully(JSONObject jsonObject) {
super.onHomeDetailsPageDataLoadedSuccessfully(jsonObject);
Activity.stopSpinWheel();
try {
if (jsonObject != null) {
if (jsonObject != null) {
fragAdapt = new FragPageAdapter(getFragmentManager());
viewPagerHome.setAdapter(fragAdapt);
JSONArray jsonArray = jsonObject.getJSONArray(AppConstants.DEALS);
arrayListHomeData = new ArrayList<HomeDealsDataClass>();
if(jsonArray.length() > 0) {
viewPagerHome.setVisibility(View.VISIBLE);
for (int i = 0; i < jsonArray.length(); i++) {
arrayListHomeData.add(new HomeDealsDataClass(jsonArray.getJSONObject(i)));
}
fragAdapt.notifyDataSetChanged();
}else{
viewPagerHome.setVisibility(View.GONE);
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void onHomeDetailsPageDataLoadedFailed(JSONObject jsonObject) {
super.onHomeDetailsPageDataLoadedFailed(jsonObject);
Activity.stopSpinWheel();
}
private class FragPageAdapter extends FragmentStatePagerAdapter {
FragPageAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int pos) {
switch (pos) {
case 0:
Log.e(TAG,"Returns Fragment Home deals 1");
fragmentHomeDetails1 = FragmentHomeDetails.newInstance(arrayListHomeData.get(0));
return fragmentHomeDetails1;
case 1:
Log.e(TAG,"Returns Fragment Home deals 2");
fragmentHomeDetails2 = FragmentHomeDetails.newInstance(arrayListHomeData.get(1));
return fragmentHomeDetails2;
default:
return null;
}
}
#Override
public int getItemPosition(Object object) {
return POSITION_NONE;
}
#Override
public int getCount() {
if(arrayListHomeData != null)
return arrayListHomeData.size();
else
return 0;
}
}
}
I had this problem too before, after searching through SO answers, this helped me.
Basically try changing your PagerAdapter to extend FragmentStatePagerAdapter from FragmentPagerAdapter

FragmentStatePager instantiate my Fragment twice

I am using the following the custom viewPager with FragmentStatePagerAdapter to create a set of fragments for user to write the specific profile. The data of the user can be retrieved by SQL with respect to the position of the child page of the viewpager. When it comes to the execution , I see that the fragment is created twice whenever the first time to be load and swipe to the other uncached pages . I have found the referenceFragment Hash map to retrieve the current fragment to be load once only instead of two fragments to be loaded. COuld you please tell me the better way to load the fragment once only ?
The below is my working :
static SectionsPagerAdapter mSectionsPagerAdapter;
static CustomViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mSectionsPagerAdapter = new SectionsPagerAdapter(fm);
dotsCount = mSectionsPagerAdapter.getCount();
dots = new ImageView[dotsCount];
dots[0] = dot1;
dots[1] = dot2;
dots[2] = dot3;
dots[3] = dot4;
dots[4] = dot5;
dots[5] = dot6;
dots[6] = dot7;
setUiPageViewController();
isTablet= ReadExcel.isTabletDevice(this);
mViewPager = (CustomViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mSectionsPagerAdapter);
mViewPager.setEnabled(true);
mViewPager.setOffscreenPageLimit(0);
mViewPager.setOnPageChangeListener(viewPagerPageChangeListener);
public static class PlaceholderFragment extends Fragment {
private static final String ARG_SECTION_NUMBER = "section_number";
public static PlaceholderFragment newInstance(int sectionNumber) {
// PlaceholderFragment fragment = new PlaceholderFragment();
PlaceholderFragment fragment = ((SectionsPagerAdapter)mViewPager.getAdapter()).getFragment(sectionNumber);
if(fragment==null){
fragment = new PlaceholderFragment();
}
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setTag(String.valueOf(sectionNumber));
fragment.setArguments(args);
return fragment;
}
public String getFTag(){
return tag;
}
public void setTag(String tag) {
this.tag = tag;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
....}}
public class SectionsPagerAdapter extends FragmentStatePagerAdapter {
private Map<Integer, PlaceholderFragment> mPageReferenceMap = new HashMap<Integer, PlaceholderFragment>();
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public int getItemPosition(Object object) {
return PagerAdapter.POSITION_NONE;
}
#Override
public Fragment getItem(int position) {
for(int i = 0; i < fm.getBackStackEntryCount(); ++i) {
fm.popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE);
}
PlaceholderFragment pf = PlaceholderFragment.newInstance(position);
mPageReferenceMap.put(Integer.valueOf(position), pf);
return pf;
}
#SuppressWarnings("deprecation")
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
super.destroyItem(container, position, object);
mPageReferenceMap.remove(Integer.valueOf(position));
// mPageReferenceMap.remove(position);
}
public PlaceholderFragment getFragment(int key) {
return mPageReferenceMap.get(key);
}
#Override
public int getCount() {
return 7;
}
#Override
public CharSequence getPageTitle(int position) {
Locale l = Locale.getDefault();
switch (position) {
case 0:
return getString(R.string.title_section1).toUpperCase(l);
case 1:
return getString(R.string.title_section2).toUpperCase(l);
}
return null;
}
}

Resources