I have viewpager with couple of fragments inside. I need to get confirmation when user presses back button. However, it doesn't get called unless I visit last page.
public class Create_Safety_CheckList_MainFragment extends Fragment
implements View.OnClickListener, Observer {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
view = inflater.inflate(R.layout.fragment_create_safety_checklist_pager_main, container, false);
initializeUI();
return view;
}
private void initializeUI() {
setHeader(getResources().getString(R.string.safety_check_list_checklist_screen_name));
addFragments();
mPager = (ViewPager) view.findViewById(R.id.viewPager_home_screen_activity);
mPagerAdapter = new ScreenSlidePagerAdapter(getChildFragmentManager());
mPager.setOffscreenPageLimit(fragmentArrayList.size());
mPager.setOnPageChangeListener(onPageChangeListener);
mPager.setAdapter(mPagerAdapter);
// mPager.setOnTouchListener(new View.OnTouchListener() {
//
// #Override
// public boolean onTouch(View v, MotionEvent event) {
// v.getParent().requestDisallowInterceptTouchEvent(true);
// return false;
// }
// });
customTextViewChecklistName = (CustomTextView) view.findViewById(R.id.textView_New_Checklist_Name);
if (createChecklistObservationModel.getChecklistName() != null)
customTextViewChecklistName.setText(createChecklistObservationModel.getChecklistName());
}
private void addFragments() {
createChecklistAdditionalTabFragment = new CreateChecklistAdditionalTabFragment();
fragmentArrayList.add(createChecklistAdditionalTabFragment);
Bundle bundle = getArguments();
if (bundle != null) {
if (bundle.containsKey("***")) {
String response = spcl_databaseHandler.getSpecificChecklistAdditionals(bundle.getString("checklistID"));
try {
JSONObject jsonObject = new JSONObject(response);
JSONObject dataJsonObject = jsonObject.getJSONObject("Data");
JSONArray checkListAdditionalFieldDtoJsonArray = dataJsonObject.getJSONArray("***");
int additionalsLength = checkListAdditionalFieldDtoJsonArray.length();
if (additionalsLength > 0) {
dataJsonObject.getJSONArray("***").toString());
additionalInfoFragment = new Additional_Information_Fragment();
fragmentArrayList.add(additionalInfoFragment);
}
JSONArray jsonGroupsArray = dataJsonObject.getJSONArray("***");
int groupsLength = jsonGroupsArray.length();
for (int i = 0; i < groupsLength; i++) {
JSONObject groupJsonObject = (JSONObject) jsonGroupsArray.get(i);
JSONArray questionsJsonArray = groupJsonObject.getJSONArray("Questions");
int questionsLength = questionsJsonArray.length();
for (int j = 0; j < questionsLength; j++) {
checklistGroupsDiscussionQuestionOneFragment = new ChecklistGroupsDiscussionQuestionOneFragment();
checklistGroupsDiscussionQuestionOneFragment.setArguments(bundle1);
fragmentArrayList.add(checklistGroupsDiscussionQuestionOneFragment);
}
JSONArray subGroupsJsonArray = groupJsonObject.getJSONArray("SubGroups");
int subGroupsJsonArrayLength = subGroupsJsonArray.length();
for (int j = 0; j < subGroupsJsonArrayLength; j++) {
JSONObject subGroupObject = subGroupsJsonArray.getJSONObject(j);
JSONArray subGroupQuestionsJsonArray = subGroupObject.getJSONArray("Questions");
int subGroupQuestionsJsonArrayLength = subGroupQuestionsJsonArray.length();
for (int k = 0; k < subGroupQuestionsJsonArrayLength; k++) {
checklistGroupsDiscussionQuestionOneFragment = new ChecklistGroupsDiscussionQuestionOneFragment(); fragmentArrayList.add(checklistGroupsDiscussionQuestionOneFragment);
}
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
questionsFragment = new Other_Questions_Fragment();
membersFragment = new Inspection_Members_Fragment();
fragmentArrayList.add(questionsFragment);
fragmentArrayList.add(membersFragment);
}
private void setHeader(String headerTitle) {
}
ViewPager.OnPageChangeListener onPageChangeListener = new ViewPager.OnPageChangeListener() {
#Override
public void onPageSelected(int pageNumber) {
}
#Override
public void onPageScrolled(int pageNumber, float positionOffset,
int positionOffsetPixels) {
// mPager.getParent().requestDisallowInterceptTouchEvent(true);
showArrows(pageNumber);
}
#Override
public void onPageScrollStateChanged(int state) {
}
};
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.imageView_Next:
break;
case R.id.imageView_Previous:
break;
case R.id.textView_Cancel :
callToCloseDialog();
break;
default:
break;
}
}
private void callToCloseDialog() {
if (SystemClock.elapsedRealtime() - mLastClickTime < 1000) {
return;
}
mLastClickTime = SystemClock.elapsedRealtime();
final AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setMessage(getResources().getString(R.string.cancel_dialog_message))
.setTitle("Warning");
builder.setPositiveButton(getResources().getString(R.string.cancel_dialog_yes_button), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// User clicked OK button
getActivity().getSupportFragmentManager().popBackStackImmediate(getResources().getString(R.string.new_checklist_fragment), FragmentManager.POP_BACK_STACK_INCLUSIVE);
}
});
builder.setNegativeButton(getResources().getString(R.string.cancel_dialog_no_button), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// User clicked cancel button
dialog.dismiss();
}
});
AlertDialog alert = builder.create();
alert.show();
}
#Override
public void update(Observable observable, Object o) {
}
/**
* A simple pager adapter that represents 3 objects, in sequence.
*/
private class ScreenSlidePagerAdapter extends FragmentStatePagerAdapter {
public ScreenSlidePagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
return fragmentArrayList.get(position);
}
#Override
public int getCount() {
return fragmentArrayList.size();
}
}
private void showArrows(int pageNumber) {
}
#Override
public void onResume() {
super.onResume();
EventBus.getDefault().register(this);
getView().setFocusableInTouchMode(true);
getView().requestFocus();
getView().setOnKeyListener(new View.OnKeyListener() {
#Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
callToCloseDialog();
return true;
}
});
}
#Override
public void onPause() {
EventBus.getDefault().unregister(this);
super.onPause();
}
#Subscribe
public void onEvent(QuestionResponsesModel questionResponsesModel){
}
}
Kept only code for Viewpager & fragments loading.
By Default Fragment Don't have any back Pressed event, so you have to manage it by Activity onBackPressed() method using below code.
Override onBackPressed() method in your Activity and Apply Check for it.
#Override
public void onBackPressed() {
// put condition here
if("Your Fragment is Visible"){
//Apply confirmation check here
}
else{
super.onBackPressed();
}
}
You can override this method in activity and listen backpress
public class MainActivity extends Activity {
...
#Override
public boolean dispatchKeyEvent(KeyEvent event)
{
int action = event.getAction();
int keyCode = event.getKeyCode();
switch (keyCode)
{
case KeyEvent.KEYCODE_BACK:
if (action == KeyEvent.ACTION_DOWN)
{
Log.v("myApp", "Back button pressed.");
return true;
}
default:
return false;
}
return false;
}
}
Related
I have scrren 1 which display form to select a branch.. then we press submit we open screen 2 which display all items in selected branch from screen 1 .. screen 1 & screen 2 are fragments.
The problem now is when i return back from screen 2 to screen 1 and change the branch then i resubmit .. the list of items in screen 2 displays items from previous selected branch first then display items from new selected branch under it .. it is something like caching the data but with adding new data also !!
i tried many ways but i can't find where the issue
This is my code to open screen fragment 2 when re-submit:
CarsFragment fragment = new CarsFragment ();
fragment.setArguments(args);
((MainActivity) context).getSupportFragmentManager().beginTransaction().replace(R.id.nav_host_fragment, fragment).addToBackStack(null).commit();
I tried to remove fragment on destroy view but with no point !
#Override
public void onDestroyView() {
super.onDestroyView();
getActivity().getSupportFragmentManager().beginTransaction().remove(this).commit();
setHasOptionsMenu(false);
}
How to fix that or i have to convert it to activity??
This is my all code of fragment screen 2 :
public class CarsFragment extends Fragment implements OnMapReadyCallback, OnNetworkListener, ClusterManager.OnClusterItemClickListener<Car> {
private CarsViewModel carsViewModel;
private FragmentCarsBinding mBinding;
SupportMapFragment mapFragment;
private GoogleMap mMap;
private static final String TAG = "CarsFragment";
public static CarsAdapter carsAdapter;
private Snackbar snack;
private NetworkChangeReceiver mNetworkReceiver;
private final int PAGE_ROWS = 25;
private int currentView = 1; // list = 0 , gallery = 1 , mapView = 2
private int city1Id = 0;
private int city2Id = 0;
private int city1Type = 0;
private int city2Type = 0;
private Long receiptDateTime;
private String daysNum;
private int customerType;
private double lat;
private double lng;
private String branchesIDs;
private String makersIDs;
private String categoriesIDs;
private int minModel;
private int maxModel;
private String kms;
private String rentTypes;
private int minPrice;
private int maxPrice;
private String ratings;
private ClusterManager<Car> mClusterManager;
private ArrayList<Car> favList = new ArrayList<>();
private MutableLiveData<Integer> favNumber = new MutableLiveData<>();
LinearLayoutManager linearLayoutManager;
private boolean isLoading = false;
private boolean isLastPage = false;
private List<Car> carList;
// private int TOTAL_PAGES = 5;
private int currentPage = 0;
Bundle args;
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent intent = requireActivity().getIntent();
Log.e("onCreateView", "22222");
if (intent != null) {
city1Id = intent.getIntExtra("receiptPlace", 0);
city2Id = intent.getIntExtra("deliveryPlace", 0);
city1Type = intent.getIntExtra("receiptPlaceType", 0);
city2Type = intent.getIntExtra("deliveryPlaceType", 0);
receiptDateTime = intent.getLongExtra("receiptDateTime", 0);
daysNum = intent.getStringExtra("daysNum");
customerType = intent.getIntExtra("customerType", 0);
lat = intent.getDoubleExtra("lat", 0.0);
lng = intent.getDoubleExtra("lng", 0.0);
}
args = getArguments();
if (args != null) {
city1Id = args.getInt("receiptPlace", 0);
city2Id = args.getInt("deliveryPlace", 0);
city1Type = args.getInt("receiptPlaceType", 0);
city2Type = args.getInt("deliveryPlaceType", 0);
receiptDateTime = args.getLong("receiptDateTime", 0);
daysNum = args.getString("daysNum");
customerType = args.getInt("customerType", 0);
lat = args.getDouble("lat", 0.0);
lng = args.getDouble("lng", 0.0);
branchesIDs = args.getString("branchesIDs", "");
makersIDs = args.getString("makersIDs", "");
categoriesIDs = args.getString("categoriesIDs", "");
minModel = args.getInt("minModel", 0);
maxModel = args.getInt("maxModel", 0);
kms = args.getString("kms", "");
rentTypes = args.getString("rentTypes", "");
minPrice = args.getInt("minPrice", 0);
maxPrice = args.getInt("maxPrice", 0);
ratings = args.getString("ratings", "");
}
// getActivity().getSupportFragmentManager().beginTransaction().remove(this).commit();
}
public View onCreateView(#NonNull LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
carsViewModel = new ViewModelProvider(requireActivity()).get(CarsViewModel.class);
carsViewModel.setFragment(this);
mBinding = FragmentCarsBinding.inflate(inflater, container, false);
Log.e("onCreateView", "1111");
// carList.clear();
initViews();
Utility.showProgressDlg(getContext());
carsViewModel.loadCars(city1Id, city2Id, city1Type, city2Type, String.valueOf(receiptDateTime), Integer.parseInt(daysNum), customerType, lat, lng, PAGE_ROWS, currentPage, branchesIDs, makersIDs, categoriesIDs, minModel, maxModel, kms, rentTypes, minPrice, maxPrice, ratings);
mNetworkReceiver = new NetworkChangeReceiver();
mNetworkReceiver.setOnNetworkListener(this);
carList = new ArrayList<>();
// carList.clear();
getCars();
setHasOptionsMenu(true);
linearLayoutManager = new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false);
mBinding.carsListView.setLayoutManager(linearLayoutManager);
mBinding.carsListView.addOnScrollListener(new PaginationScrollListener(linearLayoutManager) {
#Override
protected void loadMoreItems() {
isLoading = true;
currentPage += 1;
carsViewModel.loadCars(city1Id, city2Id, city1Type, city2Type, String.valueOf(receiptDateTime), Integer.parseInt(daysNum), customerType, lat, lng, PAGE_ROWS, currentPage
, branchesIDs, makersIDs, categoriesIDs, minModel, maxModel, kms, rentTypes, minPrice, maxPrice, ratings);
}
#Override
public boolean isLastPage() {
return isLastPage;
}
#Override
public boolean isLoading() {
return isLoading;
}
});
mBinding.favRelativeLayout.setOnClickListener(view -> {
if (favNumber.getValue() > 0) {
Intent intent = new Intent(requireActivity(), FavActivity.class);
startActivity(intent);
}
});
favNumber.postValue(0);
favNumber.observe(requireActivity(), number -> {
mBinding.textNotify.setText(String.valueOf(number));
});
return mBinding.getRoot();
}
public void onPrepareOptionsMenu(#NonNull Menu menu) {
try {
MenuItem map = menu.findItem(R.id.mapView_badge);
if (map != null)
map.setVisible(Constants.IS_CARS_MAP_VIEW_ENABLED);
super.onPrepareOptionsMenu(menu);
} catch (Exception e) {
Log.e(TAG, "onPrepareOptionsMenu: ", e);
}
}
#Override
public void onCreateOptionsMenu(#NonNull Menu menu, #NonNull MenuInflater inflater) {
inflater.inflate(R.menu.main, menu);
super.onCreateOptionsMenu(menu, inflater);
// menu.clear();
}
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.gallery_view_badge:
if (currentView == 1 || currentView == 2) {
carsAdapter.setList(true);
item.setIcon(R.drawable.ic_gallery_view);
if (currentView == 2) {
mBinding.carsListView.setVisibility(View.VISIBLE);
mBinding.carsMap.setVisibility(View.GONE);
}
currentView = 0;
} else {
currentView = 1;
carsAdapter.setList(false);
item.setIcon(R.drawable.ic_table_view);
}
return true;
case R.id.mapView_badge:
if (currentView != 2) {
mBinding.carsListView.setVisibility(View.GONE);
mBinding.carsMap.setVisibility(View.VISIBLE);
setUpMapIfNeeded();
mapFragment.requireView().setVisibility(View.VISIBLE);
currentView = 2;
item.setIcon(R.drawable.ic_gallery_view);
} else {
mBinding.carsListView.setVisibility(View.VISIBLE);
mBinding.carsMap.setVisibility(View.GONE);
currentView = 1;
carsAdapter.setList(false);
item.setIcon(R.drawable.ic_map_view_white);
}
return true;
case R.id.filter_badge:
FilterationFragment fragment = new FilterationFragment ();
fragment.setArguments(args);
getActivity().getSupportFragmentManager().beginTransaction().add(R.id.nav_host_fragment, fragment).addToBackStack(null).commit();
return true;
default:
break;
}
return false;
}
private void initViews() {
mBinding.basicFilterTl.addTab(mBinding.basicFilterTl.newTab().setText(requireActivity().getString(R.string.near_to_you)));
mBinding.basicFilterTl.addTab(mBinding.basicFilterTl.newTab().setText(requireActivity().getString(R.string.low_price)));
//mBinding.basicFilterTl.addTab(mBinding.basicFilterTl.newTab().setText("Best Seller"));
mBinding.basicFilterTl.addTab(mBinding.basicFilterTl.newTab().setText(requireActivity().getString(R.string.newest)));
for (int i = 0; i < mBinding.basicFilterTl.getTabCount(); i++) {
View tab = ((ViewGroup) mBinding.basicFilterTl.getChildAt(0)).getChildAt(i);
ViewGroup.MarginLayoutParams p = (ViewGroup.MarginLayoutParams) tab.getLayoutParams();
p.setMargins(0, 0, 20, 0);
tab.requestLayout();
}
mBinding.basicFilterTl.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
switch (tab.getPosition()) {
case 0:
Collections.sort(carList, (car, t1) -> car.getKm().compareTo(t1.getKm()));
break;
case 1:
Collections.sort(carList, (car, t1) -> car.getPriceDaily().compareTo(t1.getPriceDaily()));
break;
case 2:
Collections.sort(carList, (car, t1) -> t1.getCarModel().compareTo(car.getCarModel()));
break;
}
carsAdapter.notifyDataSetChanged();
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
snack = Snackbar.make(requireActivity().findViewById(android.R.id.content), getResources().getString(R.string.no_internet_connection), Snackbar.LENGTH_INDEFINITE);
}
private void usingMapCluster() {
mClusterManager = new ClusterManager<Car>(requireActivity(), mMap);
mMap.setOnCameraIdleListener(mClusterManager);
mClusterManager.setRenderer(new CarRenderer(mMap, mClusterManager, getLayoutInflater(), requireActivity()));
mMap.setOnCameraIdleListener(mClusterManager);
mMap.setOnMarkerClickListener(mClusterManager);
mMap.setOnInfoWindowClickListener(mClusterManager);
mClusterManager.setOnClusterItemClickListener(this::onClusterItemClick);
mClusterManager.addItems(carList);
LatLngBounds.Builder builder = new LatLngBounds.Builder();
if (carList.size() > 5) {
for (int i = 0; i < 5; i++) {
builder.include(carList.get(i).getPosition());
}
} else {
for (Car car : carList) {
builder.include(car.getPosition());
}
}
mClusterManager.cluster();
mMap.moveCamera(CameraUpdateFactory.newLatLngBounds(builder.build(), 12));
}
private void getCars() {
if (isNetworkAvailable(requireActivity())) {
carsViewModel.carsMutableLiveData.observe(getViewLifecycleOwner(), cars ->
{
Log.e("getViewLifecycleOwner", String.valueOf(cars.getListOfData().size()));
if (cars.getListOfData().size() == 0)
isLastPage = true;
// carList.clear();
carList.addAll(cars.getListOfData());
setAdapter();
isLoading = false;
});
} else {
showSnackBar();
}
}
private void setAdapter() {
if (carsAdapter == null) {
carsAdapter = new CarsAdapter(requireActivity(), carList);
mBinding.carsListView.setAdapter(carsAdapter);
carsAdapter.setOnCarItemClickedListener(this::addItemToFav);
} else {
mBinding.carsListView.post(() -> {
carsAdapter.notifyItemInserted(carList.size() - 1);
});
}
}
public void showSnackBar() {
snack.getView().setBackgroundColor(ContextCompat.getColor(requireActivity(), R.color.red));
snack.show();
}
public void hideSnackBar() {
snack.dismiss();
}
private void setUpMapIfNeeded() {
// Do a null check to confirm that we have not already instantiated the map.
if (mMap == null) {
// Get the map and REGISTER for the ready callback.
mapFragment = (SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.cars_map);
mapFragment.getMapAsync(this::onMapReady);
mapFragment.getView().setVisibility(View.GONE);
} else {
mapFragment = (SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.cars_map);
onMapReady(mMap);
}
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
setUpMap(mMap);
}
public void setUpMap(GoogleMap googleMap) {
this.mMap = googleMap;
mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
if (ActivityCompat.checkSelfPermission(requireActivity(), android.Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(requireActivity(),
android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
mMap.setMyLocationEnabled(true);
mMap.setTrafficEnabled(false);
mMap.setIndoorEnabled(false);
mMap.setBuildingsEnabled(false);
mMap.getUiSettings().setMyLocationButtonEnabled(true);
mMap.getUiSettings().setZoomControlsEnabled(false);
if (carList != null && carList.size() > 0) {
usingMapCluster();
}
}
#Override
public void onNetworkConnected() {
hideSnackBar();
// getCars(3);
}
#Override
public void onNetworkDisconnected() {
showSnackBar();
}
#Override
public void onStart() {
super.onStart();
registerNetworkBroadcastForNougat();
}
#Override
public void onStop() {
super.onStop();
requireActivity().unregisterReceiver(mNetworkReceiver);
}
private void registerNetworkBroadcastForNougat() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
requireActivity().registerReceiver(mNetworkReceiver, new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
}
}
#Override
public boolean onClusterItemClick(Car item) {
FragmentTransaction ft = requireActivity().getSupportFragmentManager()
.beginTransaction();
CarInfoPopupFragment.newInstance(item).show(ft, "CarInfoPopupFragment");
return true;
}
private void makeFlyAnimation(ImageView targetView) {
LinearLayout destView = mBinding.favRelativeLayout;
new CircleAnimationUtil().attachActivity(requireActivity()).setTargetView(targetView).setMoveDuration(1000).setDestView(destView).setAnimationListener(new Animator.AnimatorListener() {
#Override
public void onAnimationStart(Animator animation) {
}
#Override
public void onAnimationEnd(Animator animation) {
}
#Override
public void onAnimationCancel(Animator animation) {
}
#Override
public void onAnimationRepeat(Animator animation) {
}
}).startAnimation();
}
private void addItemToFav(Car car, ImageView imageView) {
boolean isAdded = false;
mBinding.favButtonIV.setBackground(getContext().getResources().getDrawable(R.drawable.ic_heart_on));
if (favList.size() > 0) {
for (Car mCar : favList) {
if (mCar.getCarKindId().equals(car.getCarKindId())) {
isAdded = true;
break;
} else {
isAdded = false;
}
}
if (!isAdded) {
makeFlyAnimation(imageView);
favList.add(car);
favNumber.postValue(favNumber.getValue() + 1);
}
} else {
makeFlyAnimation(imageView);
favList.add(car);
favNumber.postValue(favNumber.getValue() + 1);
}
SharedPref.putPrefFavLists(requireActivity(), favList);
}
#Override
public void onResume() {
super.onResume();
// carList.clear();
// carsAdapter.notifyDataSetChanged();
Fragment f = this;
this.getView().setFocusableInTouchMode(true);
this.getView().requestFocus();
this.getView().setOnKeyListener( new View.OnKeyListener()
{
#Override
public boolean onKey( View v, int keyCode, KeyEvent event )
{
if( keyCode == KeyEvent.KEYCODE_BACK )
{
Log.e("cleeeaar", "dekdjeojdoe");
carList.clear();
carsAdapter.removeList(carList);
carsAdapter.notifyDataSetChanged();
mBinding.carsListView.setAdapter(carsAdapter);
getActivity().getSupportFragmentManager().beginTransaction().remove(f).commit();
Log.e("cleeeaar222", "dekdjeojdoe");
// carsAdapter.removeList(carList);
// carsAdapter.notifyDataSetChanged();
return false;
}
return false;
}
} );
favList = SharedPref.getPrefFavList(requireActivity());
if (favList.size() > 0) {
mBinding.favButtonIV.setBackground(getContext().getResources().getDrawable(R.drawable.ic_heart_on));
}
favNumber.postValue(favList.size());
}
#Override
public void onDetach() {
super.onDetach();
setHasOptionsMenu(false);
Log.e("fragmentonpause111", "kfrjfj1111");
}
#Override
public void onDestroyView() {
super.onDestroyView();
getActivity().getSupportFragmentManager().beginTransaction().remove(this).commit();
setHasOptionsMenu(false);
}
#Override
public void onPause() {
super.onPause();
setHasOptionsMenu(false);
Log.e("fragmentonpause", "kfrjfj");
}
}
How to make it automatically view pager in few seconds?
I have tried several ways but still failed when viewpager changes
Error message is "Attempt to invoke interface method 'int java.util.List.size()' on a null object reference"
private Handler handler;
private int delay = 5000; //milliseconds
private int page = 0;
private HomeSliderPagerAdapter myAdapter;
Runnable runnable = new Runnable() {
public void run() {
if (myAdapter.getCount() == page) {
page = 0;
} else {
page++;
}
viewPager.setCurrentItem(page, true);
handler.postDelayed(this, delay);
}
};
on ActivityCreated
handler = new Handler();
viewPager = (ViewPager) getActivity().findViewById(R.id.vPager);
sliderImg = new ArrayList<>();
volleyObjectResult = new VolleyObjectResult() {
#Override
public void resSuccess(String requestType, JSONObject response) {
try {
//String images = response.getString("images");
JSONArray jsonArray = response.getJSONArray("banner");
for (int i=0; i<jsonArray.length(); i++) {
SliderUtil sliderUtil = new SliderUtil();
try {
JSONObject jsonObject = jsonArray.getJSONObject(i);
sliderUtil.setSliderImgUrl(jsonObject.getString("IMAGES"));
Log.e(TAG, "Test -> " + jsonObject.getString("IMAGES"));
}catch(Exception e){
e.printStackTrace();
}
sliderImg.add(sliderUtil);
}
HomeSliderPagerAdapter hspa = new HomeSliderPagerAdapter(sliderImg, getActivity());
hspa.notifyDataSetChanged();
viewPager.setAdapter(hspa);
viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
page = position;
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
}catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void resError(String requestType, VolleyError error) {
Toast.makeText(getActivity(), "Network connection problem", Toast.LENGTH_LONG).show();
}
};
volleyObjectService = new VolleyObjectService(volleyObjectResult, getActivity());
volleyObjectService.postJsonObject("GETCALL", requestUrl, data);
}
Result:
when the image changes it will force close with an error message "Attempt to invoke interface method 'int java.util.List.size()' on a null object reference"
Use View Pager custom adapter
public class SliderPagerAdapter extends PagerAdapter {
private LayoutInflater layoutInflater;
Activity activity;
List<ImageSliderModel> imageSliderModels;
public SliderPagerAdapter(Activity activity, List<ImageSliderModel> imageSliderModels) {
this.activity = activity;
this.imageSliderModels = imageSliderModels;
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
layoutInflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = layoutInflater.inflate(R.layout.layout_slider, container, false);
ImageView im_slider = (ImageView) view.findViewById(R.id.im_slider);
String url = imageSliderModels.get(position).getImage();
Glide.with(activity).load(imageSliderModels.get(position).getImage()).into(im_slider);
container.addView(view);
return view;
}
#Override
public int getCount() {
return imageSliderModels.size();
}
#Override
public boolean isViewFromObject(View view, Object obj) {
return view == obj;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
View view = (View) object;
container.removeView(view);
}
And in Activity call view pager and adapter
mvViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int i, float v, int i1) {
}
#Override
public void onPageSelected(int i) {
addBottomDots(i, ll_dots);
page = i;
}
#Override
public void onPageScrollStateChanged(int i) {
}
});
h.postDelayed(new Runnable() {
#Override
public void run() {
try {
if (sliderPagerAdapter.getCount() == page) {
page = 0;
} else {
page++;
}
}catch (Exception ignored)
{
}
mvViewPager.setCurrentItem(page);
h.postDelayed(this, 4000);
}
}, 1000);
And pass list to Custom adapter like this.
sliderPagerAdapter = new SliderPagerAdapter((Activity) HomeScreen.this, imageSliderModels);
mvViewPager.setAdapter(sliderPagerAdapter);
sliderPagerAdapter.notifyDataSetChanged();
private void setTimer()
{
CountDownTimer countDownTimer = new CountDownTimer(5000,2000) {
#Override
public void onTick(long millisUntilFinished) {
}
#Override
public void onFinish() {
if(viewPager.getCurrentItem() < arrayList.size() - 1)
{
viewPager.setCurrentItem(viewPager.getCurrentItem() + 1);
}
else {
viewPager.setCurrentItem(0);
}
countDownTimer.start();
}
};
countDownTimer.start();
}
I created a new project tabbed view. I want three layout on my main screen 1st home 2nd category 3rd favorite. I have code of Home activity which is fragment activity the code is here
public class HomeFragment extends android.support.v4.app.Fragment {
public HomeFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_home, container, false);
}
}
and I have another activity which is video playlist. I want to show the playlist activity in my home fragment page but I am too confused and new to Android I don't have idea what to do.
The code of video playlist is here. How can I call this code in my homeFragment class? I tried too many ways but got too confused.
Code is here which I want to implement in my home section
public ProgressBar nextBar;
List<String> next_title;
List title;
List vid;
List<String> next_vid;
ArrayList<Videos> videos=new ArrayList<Videos>();
Videos video;
ArrayList<Videos> toclear=new ArrayList<Videos>();
List<Videos> fav = new ArrayList<Videos>();
InterstitialAd mInterstitialAd;
ListView listview;
Toolbar toolbar,favourite;
int menu_id;
LinearLayout layout, no_fav;
private HttpHandler parserVideo;
String nextPageToken;
String apiKey = "AIzaSyDD73ZAzcR6bXa1qOv8YZY3fFmNwfTPs48";
String url;
Main_activity_adapter search;
Main_activity_adapter adapter;
String url_home= "https://www.googleapis.com/youtube/v3/playlistItems?part=snippet&maxResults=15&playlistId=PLQGGrzFoybiOks7f2BReNzNwkRw3cN6RB&key="+apiKey+"";
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.video_sec);
nextBar = (ProgressBar) findViewById(R.id.nextProgress);
layout = (LinearLayout) findViewById(R.id.linlaHeaderProgress);
url = url_home;
listview = (ListView) findViewById(R.id.listview);
no_fav = (LinearLayout)findViewById(R.id.no_favourit);
no_fav.setVisibility(View.GONE);
parserVideo = new HttpHandler();
getVideosPlaylist videosplaylist = new getVideosPlaylist();
videosplaylist.execute();
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
listview.setOnScrollListener(this);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
final MenuItem myActionMenuItem = menu.findItem( R.id.action_search);
final SearchView searchView = (SearchView) myActionMenuItem.getActionView();
final String toolbar_name = toolbar.getTitle().toString();
MenuItemCompat.setOnActionExpandListener(myActionMenuItem, new MenuItemCompat.OnActionExpandListener() {
#Override
public boolean onMenuItemActionExpand(MenuItem item) {
return true;
}
#Override
public boolean onMenuItemActionCollapse(MenuItem item) {
updateList();
return true;
}
});
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
#Override
public boolean onQueryTextChange(String s) {
if (!s.isEmpty()) {
setSearch();
search.getFilter().filter(s);
}
return false;
}
});
return true;
}// end of toolbar control
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
return super.onOptionsItemSelected(item);
}
public void updateList(){
adapter = new Main_activity_adapter(this, videos, false);
listview.setAdapter(adapter);
listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
Videos v = (Videos) adapter.getItemAtPosition(arg2);
Intent n = new Intent(Videos_activity.this, PlayingVideo.class);
n.putExtra("vid", v.getVid().toString());
n.putExtra("title", v.getTitle().toString());
startActivity(n);
}
}
);
}
JSONObject jp_obj;
JSONArray jar_array;
#Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
}
#Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
String toolbar_check = toolbar.getTitle().toString();
switch(view.getId()){
case R.id.listview:
final int lastItem = firstVisibleItem + visibleItemCount;
if (lastItem == totalItemCount) {
if(toolbar_check!="Favourites") {
OnScrollList onscroll = new OnScrollList();
onscroll.execute();
}
}
}
}
class getVideosPlaylist extends AsyncTask<String, String, String> {
#Override
protected String doInBackground(String... params) {
jp_obj = parserVideo.getJsonFromYoutube(url);
try {
if (jp_obj.has("nextPageToken")) {
nextPageToken = jp_obj.getString("nextPageToken");
}
jar_array = new JSONArray(jp_obj.getString("items"));
if(jp_obj != null) {
JSONObject c = jar_array.getJSONObject(0);
String json_check = c.getJSONObject("snippet").getString("title");
if (json_check == null) {
} else {
title = new ArrayList<String>(jar_array.length());
vid = new ArrayList<>(jar_array.length());
for (int j = 0; j < jar_array.length(); j++) {
c = jar_array.getJSONObject(j);
String str = c.getJSONObject("snippet").getString("title");
str = new String(str.replaceAll("\\['\\]", ""));
String link = c.getJSONObject("snippet").getJSONObject("resourceId").getString("videoId");
video = new Videos(str, link);
videos.add(video);
}
}
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onCancelled(){
super.onCancelled();
}
#Override
protected void onPreExecute() {
layout.setVisibility(View.VISIBLE);
super.onPreExecute();
}
#Override
protected void onPostExecute(String s) {
updateList();
layout.setVisibility(View.GONE);
cancel(true);
super.onPostExecute(s);
}
}
class OnScrollList extends AsyncTask<String,String,String>{
#Override
protected String doInBackground(String... params) {
if (nextPageToken!=null){
String nextPage = "&pageToken="+nextPageToken+"";
JSONObject next = parserVideo.getJsonFromYoutube(url+nextPage);
try {
JSONArray array = new JSONArray(next.getString("items"));
if (next != null) {
JSONObject c = array.getJSONObject(0);
String json_check = c.getJSONObject("snippet").getString("title");
if (json_check == null) {
} else {
next_title = new ArrayList<String>(array.length());
next_vid = new ArrayList<String>((array.length()));
for (int j = 0; j < array.length(); j++) {
c = array.getJSONObject(j);
String str = c.getJSONObject("snippet").getString("title");
str = new String(str.replaceAll("\'", ""));
next_title.add(str);
String nextLink = c.getJSONObject("snippet").getJSONObject("resourceId").getString("videoId");
next_vid.add(nextLink);
video = new Videos(str, nextLink);
toclear.add(video);
}
}
}if (next.has("nextPageToken")){
nextPageToken = next.getString("nextPageToken");
}else if(!next.has("nextPageToken")){
nextPageToken = null;}
} catch (JSONException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onCancelled(){
super.onCancelled();
}
#Override
protected void onPostExecute(String s) {
videos.addAll(toclear);
adapter.notifyDataSetChanged();
nextBar.setVisibility(View.GONE);
toclear.clear();
cancel(true);
super.onPostExecute(s);
}
#Override
protected void onPreExecute() {
nextBar.setVisibility(View.VISIBLE);
super.onPreExecute();
}
}
public void setSearch()
{
search = new Main_activity_adapter(Videos_activity.this, videos, true);
listview.setAdapter(search);
listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
Videos v = (Videos)search.getItemAtPosition(arg2);
Intent n = new Intent(Videos_activity.this, PlayingVideo.class);
n.putExtra("vid", v.getVid().toString());
n.putExtra("title", v.getTitle().toString());
startActivity(n);
}
}
);
}
public void favouritList(){
Main_activity_adapter favourit_adapter = new Main_activity_adapter(this, videos, false);
listview.setAdapter(favourit_adapter);
listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
Videos v = (Videos) adapter.getItemAtPosition(arg2);
Intent n = new Intent(Videos_activity.this, PlayingVideo.class);
n.putExtra("vid", v.getVid().toString());
n.putExtra("title", v.getTitle().toString());
startActivity(n);
}
}
);
}
Define variable like public static String test=""; in Activity then in Fragment get it like String test1=ActivityName.test; now you have value of test into test1
First of all, you need to understand that Activity contains fragments, not vice versa. So one way to make your idea come true is to make your activity contain three fragments:
1)Home
2)Category
3)Favorite
To send data from activity to fragment usually use Bundle object.
Then create the instance of the fragment and put bundle there by setArguments(yourBundle) method.
It is the main idea, if you want details then read official documentation and use search on SOF.
use a Bundle:
Fragment fragment = new YourFragment();
Bundle bundle = new Bundle();
bundle.putString("yourArg","yourType"); //this could be String, int, float,etc
fragment.setArguments(bundle);
getSupportFragmentManager().beginTransaction().replace(R.id.yourContainer,fragment).commit();
and in your Fragment's onCreateView:
Bundle bundle = getArguments();
am building an open source project, here is its link
http://slidese.github.io/slidese/2013/11/25/update_listview_item.html
I've imported all library projects which it is using into eclipse. All are fine except PullToRefresh library. it is giving me the error "PullToRefreshAttacher.OnRefreshListener cannot be resolved to a type" where fragment implements it
2nd error is at
mPullToRefreshAttacher.addRefreshableView(mListview, this);
it says "The method addRefreshableView(View, ViewDelegate) in the type PullToRefreshAttacher is not applicable for the arguments (ListView, ContentFragment)"
3rd error is at
#Override
public void onRefreshStarted(View view) {
Intent intent = new Intent(getActivity(), DownloaderService.class);
intent.putExtra(DownloaderService.EXTRA_USER_INITIATED, true);
getActivity().startService(intent);
}
It is asking me to remove override annotation. here is complete code of fragment.
public class ContentFragment extends Fragment implements PullToRefreshAttacher.OnRefreshListener {
private final String TAG = "ContentFragment";
public static final String CONTENT_MODE = "content_mode";
public static final int MODE_ADFREE = 0;
public static final int MODE_PREMIUM = 1;
private StartActivity mListener;
private PullToRefreshAttacher mPullToRefreshAttacher;
private UpdaterAsyncTask mUpdater;
private int mScrollState = OnScrollListener.SCROLL_STATE_IDLE;
ListView mListview;
Button mPlayButton;
ContentAdapter mAdapter;
int mMode;
Map<String, UpdateHolder> mUpdates = new HashMap<String, UpdateHolder>();
public ContentFragment() {
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mListener = (StartActivity) activity;
Log.d(TAG, "Attached podcast list fragment");
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString() + " must be the StartActivity");
}
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_content, null);
mListview = (ListView) view.findViewById(android.R.id.list);
mListview.setEmptyView(view.findViewById(R.id.empty_list_view));
mListview.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE_MODAL);
mListview.setMultiChoiceModeListener(new MultiChoiceModeListener() {
#Override
public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
return false;
}
#Override
public void onDestroyActionMode(ActionMode mode) {
}
#Override
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
MenuInflater inflater = mode.getMenuInflater();
inflater.inflate(R.menu.contextual_menu_content, menu);
return true;
}
#Override
public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
if (item.getItemId() == R.id.action_delete) {
SparseBooleanArray checked = mListview.getCheckedItemPositions();
Content[] params = new Content[checked.size()];
int index = 0;
int first = mListview.getFirstVisiblePosition();
int last = mListview.getLastVisiblePosition();
for (int i = 0; i < mListview.getCount(); i++) {
if (checked.get(i)) {
params[index++] = (Content)mListview.getItemAtPosition(i);
if (i >= first && i <= last) {
View view = mListview.getChildAt(i-first);
Animation animation = AnimationUtils.loadAnimation(getActivity(), android.R.anim.slide_out_right);
animation.setDuration(200);
//animation.setFillAfter(true);
animation.setStartOffset(100 * (index) );
view.startAnimation(animation);
}
}
}
new AsyncTask<Content, Void, Void>() {
#Override
protected Void doInBackground(Content... params) {
for (Content content : params) {
File file = Utils.getFilepath(content.getFilename());
file.delete();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
mAdapter.notifyDataSetChanged();
}
}.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, params);
mode.finish();
return true;
}
return false;
}
#Override
public void onItemCheckedStateChanged(ActionMode mode, int position, long id, boolean checked) {
}
});
mListview.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View view, int position, long id) {
Content content = mAdapter.getItem(position);
mListener.showContentDetails(content);
}
});
mListview.setOnScrollListener(new OnScrollListener() {
#Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
mScrollState = scrollState;
}
#TargetApi(Build.VERSION_CODES.JELLY_BEAN)
#Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
}
});
mPullToRefreshAttacher = ((StartActivity) getActivity()).getPullToRefreshAttacher();
mPullToRefreshAttacher.addRefreshableView(mListview, this);
mMode = getArguments().getInt(CONTENT_MODE);
return view;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
#Override
public void onPause() {
super.onPause();
if (mUpdater != null)
mUpdater.stop();
}
#Override
public void onResume() {
super.onResume();
updateAdapter();
mUpdater = new UpdaterAsyncTask();
mUpdater.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, (Void)null);
}
public void refresh() {
updateAdapter();
}
public void replaceCurrentlyPlayingContent() {
GlobalContext.INSTANCE.replaceCurrentlyPLayingContent(mAdapter.getObjects(), mListener.getCurrentTrack());
}
private void updateAdapter() {
Log.d(TAG, "updateAdapter");
//new FetchContentAsyncTask(mMode).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
final String mp3 = mListener.getSavedStateMp3();
final boolean isPlaying = mListener.getSavedStateIsPlaying();
final boolean isPaused = mListener.getSavedStateIsPaused();
List<Content> listOfContent = GlobalContext.INSTANCE.getCachedContent(mMode, mp3, isPlaying, isPaused);
mAdapter = new ContentAdapter(getActivity(), R.layout.list_item_card, listOfContent);
mListview.setAdapter(mAdapter);
}
#Override
public void onRefreshStarted(View view) {
Intent intent = new Intent(getActivity(), DownloaderService.class);
intent.putExtra(DownloaderService.EXTRA_USER_INITIATED, true);
getActivity().startService(intent);
}
private class UpdaterAsyncTask extends AsyncTask<Void, Void, Void> {
boolean isRunning = true;
public void stop() {
isRunning = false;
}
#Override
protected Void doInBackground(Void... params) {
while (isRunning) {
/*
Map<String, UpdateHolder> map = gatherMetadata();
publishProgress(map);
*/
updateCurrentAdapterContent();
publishProgress();
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onProgressUpdate(Void... params) {
super.onProgressUpdate();
if (mScrollState == OnScrollListener.SCROLL_STATE_IDLE) {
// http://stackoverflow.com/questions/2123083/android-listview-refresh-single-row
int start = mListview.getFirstVisiblePosition();
for(int i = start, j = mListview.getLastVisiblePosition(); i<=j; i++) {
View view = mListview.getChildAt(i-start);
if (((Content)mListview.getItemAtPosition(i)).dirty) {
Log.v(TAG, "Content is dirty");
mListview.getAdapter().getView(i, view, mListview);
}
}
}
}
}
private void updateCurrentAdapterContent() {
List<Content> listOfContent = mAdapter.getObjects();
Map<String, UpdateHolder> map = new HashMap<String, UpdateHolder>();
DownloadManager.Query q = new DownloadManager.Query();
q.setFilterByStatus(DownloadManager.STATUS_PENDING | DownloadManager.STATUS_RUNNING);
try {
Cursor cursor = ContentDownloadManager.INSTANCE.query(q);
while (cursor.moveToNext()) {
//long id = cursor.getLong(cursor.getColumnIndex(DownloadManager.COLUMN_ID));
String uri = cursor.getString(cursor.getColumnIndex(DownloadManager.COLUMN_URI));
int status = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_STATUS));
int downloaded = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR));
int total = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_TOTAL_SIZE_BYTES));
float progress = (float)downloaded/(float)total;
UpdateHolder holder = new UpdateHolder();
holder.progress = progress;
holder.status = status;
map.put(uri, holder);
}
cursor.close();
final Content currentContent = mListener.getCurrentTrack();
final boolean isPlaying = mListener.isPlaying();
final boolean isPaused = mListener.isPaused();
for (Content content : listOfContent) {
// First update any download progress we might have for this specific content item
UpdateHolder holder = map.get(content.mp3);
if (holder != null) {
if (content.downloadProgress != holder.progress) {
content.downloadProgress = holder.progress;
content.dirty = true;
}
if (content.downloadStatus != holder.status) {
content.downloadStatus = holder.status;
content.dirty = true;
}
}
else {
if (content.downloadProgress != 0f) {
content.downloadProgress = 0f;
content.dirty = true;
}
if (content.downloadStatus != -1) {
content.downloadStatus = -1;
content.dirty = true;
}
}
// Update with elapsed (to be done)
// File exists?
File file = Utils.getFilepath(content.getFilename());
if (content.exists != file.exists()) {
content.exists = file.exists();
content.dirty = true;
}
// Is this the currently playing content
if (currentContent != null && content.mp3.equals(currentContent.mp3)) {
if (content.isPlaying != isPlaying) {
content.isPlaying = isPlaying;
content.dirty = true;
}
if (content.isPaused != isPaused) {
content.isPaused = isPaused;
content.dirty = true;
}
}
else {
if (content.isPlaying != false) {
content.isPlaying = false;
content.dirty = true;
}
if (content.isPaused != false) {
content.isPaused = false;
content.dirty = true;
}
}
if (content.dirty) {
DatabaseManager.getInstance().createOrUpdateContent(content);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
public class UpdateHolder {
public String mp3;
public int status;
public boolean played;
public float progress;
public boolean exists = false;
public boolean isPlaying = false;
public boolean isPaused = false;
//public int elapsed;
//public int duration;
}
}
I couldn't find the issue in it. I'm stuck here for last 40 hours. Please help. Thank you!
Maybe you are using old version of the library. I found that PullToRefreshAttacher doesn't contain OnRefreshListener. (https://github.com/chrisbanes/ActionBar-PullToRefresh/blob/master/library/src/main/java/uk/co/senab/actionbarpulltorefresh/library/PullToRefreshAttacher.java)
Try to import uk.co.senab.actionbarpulltorefresh.library.listeners.OnRefreshListener; and use it instead of PullToRefreshAttacher.OnRefreshListener.
I would like to ask how can I detect when I try to back to another fragment.
So I have this code:
fragmentManager.replace(R.id.fragment_searched_data_xml, fragment).addToBackStack(null).commit();
that lets me back on that fragment. Now the question is:
when I press the back button from the current fragment so I can go back to initial fragment can I detect it??
public static class FragmentMainClass extends Fragment {
int i;
public FragmentMainClass() {
}
public FragmentMainClass(int i) {
this.i = i;
}
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View rootView = inflater.inflate(
R.layout.fragment_searched_data, container, false);
TextView sn = (TextView) rootView.findViewById(R.id.stop_name);
TextView sc = (TextView) rootView.findViewById(R.id.stop_code);
String prefix = getArguments().getString("bussStopName");
if (sn != null && sc != null) {
if (prefix.contains("/")) {
if (prefix.contains("/ ")) {
sn.setText(prefix.replace("\"", "").split("/ ")[0] + "\n" + prefix.replace("\"", "").split("/ ")[1]);
sc.setText(getArguments().getString("bussStopCode"));
} else {
sn.setText(prefix.replace("\"", "").split("/")[0] + "\n" + prefix.replace("\"", "").split("/")[1]);
sc.setText(getArguments().getString("bussStopCode"));
}
} else {
sn.setPadding(20, 40, 0, 0);
sn.setText(prefix.replace("\"", ""));
sc.setText(getArguments().getString("bussStopCode"));
}
}
final LinearLayout child = (LinearLayout) rootView
.findViewById(R.id.search_result_data_box);
LayoutParams params = (LayoutParams) child.getLayoutParams();
//child.setVisibility(View.GONE);
// params.height = 0;
widthListView = container.getWidth();
rootView.setTranslationX(-container.getWidth());
rootView.animate().setStartDelay(300).translationX(0)
.withEndAction(new Runnable() {
#Override
public void run() {
conreq = new ConnnectionRequest("97", getArguments().getString("bussStopCode"));
//expand(child);
initializeResultList(rootView);
// rootView.setVisibility(View.INVISIBLE);
}
});
return rootView;
}
public static void expand(final View v) {
final int targtetHeight = v.getMeasuredHeight();
v.getLayoutParams().height = 0;
v.setVisibility(View.VISIBLE);
Animation a = new Animation() {
#Override
protected void applyTransformation(float interpolatedTime,
Transformation t) {
v.getLayoutParams().height = interpolatedTime == 1 ? LayoutParams.WRAP_CONTENT
: (int) (targtetHeight * interpolatedTime);
v.requestLayout();
}
#Override
public boolean willChangeBounds() {
return true;
}
};
// 1dp/ms
a.setDuration((int) (targtetHeight / v.getContext().getResources()
.getDisplayMetrics().density));
v.startAnimation(a);
}
public void onActivityResult(int requestCode, int resultCode, Intent data)
{
}
public void initializeResultList(View v) {
result_list = (ListView) v.findViewById(R.id.list_view_results);
//(PullToRefreshListView) v.findViewById(R.id.list_view_results);;
final ResultDataCustomAdapter customAdapter = new ResultDataCustomAdapter(getActivity(), R.layout.pull_refresh_list_item, conreq.getCollectedData().getBusRouteSetData());
//prlv.prepareForRefresh();
((PullToRefreshListView) result_list).setOnRefreshListener(new OnRefreshListener() {
#Override
public void onRefresh() {
// Do work to refresh the list here.
new GetDataTask().execute();
}
});
result_list.setAdapter(customAdapter);
result_list.setVisibility(View.VISIBLE);
result_list.setOnItemClickListener(new OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> av, final View view,
final int i, long i2) {
view.animate().setDuration(500).translationX(widthListView).alpha(0).
withEndAction(new Runnable() {
#Override
public void run() {
//setResult(Activity.RESULT_OK,new Intent().putExtra("bussStopCode", data.get(i).getStopCode()).putExtra("bussStopName", data.get(i).getStopName()));
////int get 1
//data.remove(i);
int temporaryInteger = i;
//customAdapter.notifyDataSetChanged();
//view.setTranslationX(0);
Log.d("data",conreq.getCollectedData().getBusRouteSetData().get(temporaryInteger - 1).getRouteHeading());
Bundle bundle = new Bundle();
bundle.putString("busdestination", conreq.getCollectedData().getBusRouteSetData().get(temporaryInteger-1).getRouteHeading());
bundle.putString("busnumber", conreq.getCollectedData().getBusRouteSetData().get(temporaryInteger-1).getRouteNo());
Fragment fragment = new FragmentNextTripForStop();
fragment.setArguments(bundle);
FragmentTransaction fragmentManager = getFragmentManager().beginTransaction();
fragmentManager.setCustomAnimations(R.anim.left_right_anim_x_left,R.anim.left_right_anim_x_right);
fragmentManager.replace(R.id.fragment_searched_data_xml, fragment).addToBackStack(null).commit();
result_list.setVisibility(View.GONE);
// finish();
//overridePendingTransition(R.anim.right_left_anim_x_left,R.anim.right_left_anim_x_right);
}
});
}});
}
private class GetDataTask extends AsyncTask<Void, Void, String[]> {
#Override
protected String[] doInBackground(Void... params) {
// Simulates a background job.
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
;
}
return null;
}
#Override
protected void onPostExecute(String[] result) {
// Call onRefreshComplete when the list has been refreshed.
((PullToRefreshListView) result_list).onRefreshComplete();
super.onPostExecute(result);
}
}
}
While Adding your fragment into host layout add fragment into stack
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.home_fragment, fragment)
.addToBackStack(fragment.getTag())
.commit();
In your onBackPressed()
if (getSupportFragmentManager().getBackStackEntryCount() >= 0) {
getSupportFragmentManager().popBackStack();
}else{
super.onBackPressed();
}