How to clear the data in recyclerview when relaunch the fragment? - android

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");
}
}

Related

How to update textview of viewpager adpater's fragment which inside the fragment?

I need to update the textview which is inside view pager adpater's fragment
I have 2 fragments inside viewpager adapter.
and adapter itself is within the fragment.
Main fragment is initialize from MainActivity.
I used Greenrobot approach.for updating textview values on runtime.i get that value but UI is flickering means not getting good UI.
So Shall i used another approach please suggest me.
Adapter Code:-
public class SamplePagerAdapter extends FragmentPagerAdapter {
private final Random random = new Random();
private int mSize = 2;
private int heart_rate;
FragmentManager fm;
public SamplePagerAdapter(FragmentActivity activity, FragmentManager supportFragmentManager, int heart) {
super(supportFragmentManager);
fm = supportFragmentManager;
heart_rate = heart;
}
#Override
public int getCount() {
return mSize;
}
#Override
public Fragment getItem(int position) {
Fragment f = null;
if (position == 0) {
f = new MyFragment();
} else if (position == 1) {
f = new SecondFragment();
}
return f;
}
public int getItemPosition(Object object) {
return POSITION_NONE;
}
private boolean loadFragment(Fragment fragment) {
//switching fragment
if (fragment != null) {
fm.beginTransaction()
.replace(R.id.fragment_container, fragment)
.addToBackStack(null)
.commit();
return true;
}
return false;
}
}
//code for loading main Fragment:-MeasureFragment
private boolean loadFragment(Fragment fragment) {
//switching fragment
if (fragment != null) {
Bundle bundle = new Bundle();
bundle.putString("ble_address",bleAddress);
fragment.setArguments(bundle);
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.fragment_container,fragment)
.addToBackStack(null)
.commit();
return true;
}
return false;
}
//also add measure fragment code:-
public class MeasureFragment extends Fragment implements ISmctAlgoCallback, IBleOperateCallback {
protected boolean measureSwitch = false;
private EcgAlgo ecgAlgo;
private BluetoothLeService mBluetoothLeService;
protected ProgressDialog mProgressDialog;
protected boolean isContecting = false;
private TextView btn_start;
private TextView tv_heartrate, tv_time, tv_pauseorresume;
private RelativeLayout linear, linear1;
private LinearLayout linear_pause, linear_stop;
private CountDownTimer timer;
private int count = 0;
private boolean running;
private Handler handler;
Runnable runnable;
ImageView iv_pauseorresume;
private boolean onclick = true;
private boolean isstop = false;
private String bleAddress;
View view1, view2, view3, view4, view5;
TextView tv_toolbar_title, tv_alarm_setting, tv_battery_percentage;
private int heart_rate;
SamplePagerAdapter samplePagerAdapter;
private FragmentActivity myContext;
ViewPager viewpager;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_measure, container, false);
bleAddress = getArguments().getString("ble_address");
viewpager = (ViewPager) view.findViewById(R.id.viewpager);
CircleIndicator indicator = (CircleIndicator) view.findViewById(R.id.indicator);
btn_start = (TextView) view.findViewById(R.id.btn_start);
linear = (RelativeLayout) view.findViewById(R.id.linear);
linear1 = (RelativeLayout) view.findViewById(R.id.linear1);
linear_pause = (LinearLayout) view.findViewById(R.id.linear_pause);
linear_stop = (LinearLayout) view.findViewById(R.id.linear_stop);
tv_heartrate = (TextView) view.findViewById(R.id.tv_heart_rate);
tv_toolbar_title = (TextView) view.findViewById(R.id.tv_toolbar_title);
tv_alarm_setting = (TextView) view.findViewById(R.id.tv_alarm_setting);
tv_battery_percentage = (TextView) view.findViewById(R.id.tv_battery_percentage);
view1 = (View) view.findViewById(R.id.view1);
view2 = (View) view.findViewById(R.id.view2);
view3 = (View) view.findViewById(R.id.view3);
view4 = (View) view.findViewById(R.id.view4);
view5 = (View) view.findViewById(R.id.view5);
iv_pauseorresume = (ImageView) view.findViewById(R.id.iv_pauseorresume);
tv_pauseorresume = (TextView) view.findViewById(R.id.btn_pause);
tv_time = (TextView) view.findViewById(R.id.time);
ecgAlgo = new EcgAlgo();
ecgAlgo.setISmctAlgoCallback(this);
handler = new Handler();
samplePagerAdapter = new SamplePagerAdapter(getActivity(), getChildFragmentManager(), heart_rate);
viewpager.setAdapter(samplePagerAdapter);
indicator.setViewPager(viewpager);
viewpager.setCurrentItem(0);
linear.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (isstop) {
measureSwitch = true;
linear1.setVisibility(View.VISIBLE);
linear.setVisibility(View.GONE);
handler.post(runnable = new Runnable() {
#Override
public void run() {
int hours = count / 3600;
int minutes = (count % 3600) / 60;
int sec = count % 60;
String time = String.format("%02d:%02d:%02d", hours, minutes, sec);
tv_time.setText(time);
if (running) {
count++;
}
handler.postDelayed(this, 1000);
}
});
} else {
connectBle();
running = true;
}
}
});
linear_stop.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
ecgAlgo.clearECGParam();
isstop = true;
measureSwitch = false;
count = 0;
handler.removeCallbacks(runnable);
linear1.setVisibility(View.GONE);
linear.setVisibility(View.VISIBLE);
}
});
linear_pause.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (onclick) {
iv_pauseorresume.setImageResource(R.drawable.resume1);
tv_pauseorresume.setText("Resume");
running = false;
onclick = false;
} else {
onclick = true;
running = true;
iv_pauseorresume.setImageResource(R.drawable.pause);
tv_pauseorresume.setText("Pause");
}
}
});
return view;
}
private void connectBle() {
if (TextUtils.isEmpty(bleAddress)) {// 蓝牙地址为空
showToast(R.string.ble_address_empty);
} else if (mBluetoothLeService != null && !isContecting) {// 蓝牙未连接
showDialog();
mBluetoothLeService.connect(bleAddress);
measureSwitch = true;
} else if (mBluetoothLeService == null) {// 连接服务
connectBleService();
} else {// 其它
disDialog();
showToast(R.string.ble_connect_fail);
}
}
/**
* 连接蓝牙服务
*/
public void connectBleService() {
Intent gattServiceIntent = new Intent(getActivity(), BluetoothLeService.class);
getActivity().bindService(gattServiceIntent, mServiceConnection, BIND_AUTO_CREATE);
}
#Override
public void bleData(short key, short value) {
// TODO Auto-generated method stub
switch (key) {
case SmctConstant.KEY_BLE_CONNECT_STATE:// 连接状态改变
if (SmctConstant.VALUE_BLE_CONNECTED == value) {// 已连接
// hasReConnectCount = 0;
//updateNotification(getString(R.string.notification_nomal));
} else if (SmctConstant.VALUE_BLE_DISCONNECTED == value) {// 连接断开
disDialog();
if (isContecting) {//如果已连接 提示设备以断开连接
showToast(R.string.ble_connect_disconnect);
} else {//没有连接 提示连接失败
//showToast(R.string.ble_connect_fail);
}
isContecting = false;
//changeButtonSate(isContecting);
//changeSwitchView(false);
} else if (SmctConstant.VALUE_BLE_SERVICE_DISCOVERED == value) {// 发现服务
if (mBluetoothLeService != null) {
mBluetoothLeService.setCharacteristic(mBluetoothLeService.getSupportedGattServices(),
SmctConstant.UUID_KEY_DATA_FFE2);
}
disDialog();
isContecting = true;
//changeButtonSate(isContecting);
//changeSwitchView(false);
showToast(R.string.ble_connect_success);
}
break;
case SmctConstant.KEY_DEVICE_POWER_LEVEL:// 电量
//refrashPowerLevel(value);
//Log.d("power leve", "" + value);
break;
case SmctConstant.KEY_DEVICE_ELECTRODE_DROP:// 电极脱落
if (measureSwitch)
showToast("Elctrode Dropout!!!");
break;
case SmctConstant.KEY_ECG_DATA:// ecg数据
// 正在测量中
if (measureSwitch) {
//refrashEcgData(value);
//Log.d("Ecg data", "" + value);
//算法计算
ecgAlgo.addECGParam(value);
}
break;
case SmctConstant.KEY_BODY_POSE:// 姿态
if (value == SmctConstant.VALUE_POSE_WALK) {
//refrashPose("go");
Log.d("pose", "go");
} else if (value == SmctConstant.VALUE_POSE_FALL_DOWN) {
showToast("Falls!!!!!!");
Log.d("pose", "Falls");
} else if (value == SmctConstant.VALUE_POSE_LIE_LOW) {
//refrashPose("Flat lay");
Log.d("pose", "Flat lay");
} else if (value == SmctConstant.VALUE_POSE_STAND) {
//refrashPose("Flat lay");
Log.d("pose", "Standing");
} else if (value == SmctConstant.VALUE_POSE_SIDE_DECUBITUS) {
Log.d("pose", "Standing");
}
break;
}
}
#Override
public void bleData(short key, float[] value) {
if (SmctConstant.KEY_ACC_DATA == key) {
//refreshAccData(value);
}
}
/**
* 算法数据
*/
#Override
public void algoData(final int key, final int value) {
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
switch (key) {
case SmctConstant.KEY_ALGO_HEART_RATE:// 心率
//tv_heartrate.setText(String.valueOf(value));
//arc_progress.setProgress(value);
//heart_rate=value;
// Bundle bundle = new Bundle();
//bundle.putInt("heart_rate", value);
//fragment.setArguments(bundle);
heart_rate = value;
Bundle bundle=new Bundle();
bundle.putInt("heart_rate",value);
samplePagerAdapter.getItem(0).setArguments(bundle);
//notifyViewPagerDataSetChanged();
break;
case SmctConstant.KEY_ALGO_ARRHYTHMIA:// 心律失常
//tvArr.setText(formatString(R.string.arrhythmia, value));
break;
}
}
});
}
public ServiceConnection mServiceConnection = new ServiceConnection() {
#Override
public void onServiceConnected(ComponentName componentName, IBinder service) {
mBluetoothLeService = ((BluetoothLeService.LocalBinder) service).getService();
if (!mBluetoothLeService.initialize()) {
// LogUtil.e("smctservice", "Unable to initialize Bluetooth");
// mHandler.sendEmptyMessage(MSG_BLE_UNINIT);
} else {
mBluetoothLeService.setBleOperate(MeasureFragment.this);
connectBle();
}
}
#Override
public void onServiceDisconnected(ComponentName componentName) {
// LogUtil.e("smctservice", "onServiceDisconnected");
mBluetoothLeService = null;
}
};
private void notifyViewPagerDataSetChanged() {
Log.d(TAG, "\nnotifyDataSetChanged()");
samplePagerAdapter.notifyDataSetChanged();
}
protected void disDialog() {
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
if (mProgressDialog != null) {
mProgressDialog.dismiss();
linear.setVisibility(View.GONE);
linear1.setVisibility(View.VISIBLE);
//new MyCountDownTimer(System.currentTimeMillis(),1000).start();
}
handler.post(runnable = new Runnable() {
#Override
public void run() {
int hours = count / 3600;
int minutes = (count % 3600) / 60;
int sec = count % 60;
String time = String.format("%02d:%02d:%02d", hours, minutes, sec);
tv_time.setText(time);
if (running) {
count++;
}
handler.postDelayed(this, 1000);
}
});
}
});
}
protected void showToast(String msg) {
ToastUtils.showToast(getActivity(), msg);
}
/**
* 统一显示toast管理
*/
protected void showToast(int id) {
ToastUtils.showToast(getActivity(), getResources().getString(id));
}
/**
* 显示连接蓝牙dialog
*/
protected void showDialog() {
if (mProgressDialog != null && mProgressDialog.isShowing()) {
mProgressDialog.dismiss();
mProgressDialog = null;
}
mProgressDialog = new ProgressDialog(getActivity());
mProgressDialog.setMessage(getResources().getString(R.string.text_conn_ble));
mProgressDialog.setCanceledOnTouchOutside(false);
mProgressDialog.show();
}
}
And need to update textview already discuss.in this fragment.
public class MyFragment extends Fragment {
private int heart_rate;
private ArcProgress arc_progress;
private TextView tv_heartrate;
private Handler handler;
private Runnable runnable;
private View view;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle saveBundle) {
view = inflater.inflate(R.layout.ecg_layout, container, false);
arc_progress = (ArcProgress) view.findViewById(R.id.arc_progress);
tv_heartrate = (TextView) view.findViewById(R.id.tv_heart_rate);
handler = new Handler();
handler.post(runnable = new Runnable() {
#Override
public void run() {
Log.d("heartrate", "" + heart_rate);
arc_progress.setProgress(heart_rate);
tv_heartrate.setText(String.valueOf(heart_rate));
handler.postDelayed(this, 1000);
}
});
return view;
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
}
}

Why RecyclerView CustomAdaper Filter and onViewRecycled() both not working together in android?

My Application need filter on customAdapter, so i implement Filter in CustomAdapter
In CustomAdapter i put Google Map. When Adapter is recycled google map pin and map view is changed for that solution i use onViewRecycled() method and in that i set Latitude and Longitude and set Marker on Google Map view.
But problem is that when i implement Filter logic then application is crash and give me ArrayIndexOutOfBound Exception that error point me in onViewRecycled() method.
Please Help me to solve this Problem.
My Adapter and Activity code is below:
PostListAdapter.java
public class PostListAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> implements Filterable{
Context mcontext;
LayoutInflater inflater;
View view;
RecyclerViewHolder recyclerViewHolder;
FragmentManager fm;
MapView map;
GPSTracker gps;
private double latitude=0.0, longitude=0.0;
LatLng latlongs;
Geocoder geocoder;
List<Address> addressList;
GoogleMap thisMap;
String mapTitle = null;
String mapSnnipet = null;
boolean isAgreePost;
List<GetPostCallBack> getPostCallBackList;
List<GetPostCallBack> getPostCallBackListFiltered=new ArrayList<>();
Dialog dialog;
String User_Id = "";
double latitudeForMarker=0.0, longitudeForMarker=0.0;
public PostListAdapter(Context mcontext, FragmentManager fm, List<GetPostCallBack> getPostCallBackList) {
inflater = null;
this.mcontext = mcontext;
this.fm = fm;
this.getPostCallBackList = getPostCallBackList;
this.getPostCallBackListFiltered.addAll(getPostCallBackList);
User_Id = Functions.getStringPref(mcontext, FindExperience.USER_ID);
Log.d("TAG", "PostListAdapter: " + User_Id);
inflater = (LayoutInflater) this.mcontext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
gps = new GPSTracker(mcontext);
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
view = LayoutInflater.from(parent.getContext()).inflate(R.layout.row_layout_home, parent, false);
recyclerViewHolder = new RecyclerViewHolder(view);
return recyclerViewHolder;
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, final int position) {
recyclerViewHolder = (RecyclerViewHolder) holder;
thisMap = recyclerViewHolder.gMap;
if (!getPostCallBackList.get(position).getProfilePicture().equals("")) {
Picasso.with(mcontext).load(getPostCallBackList.get(position).getProfilePicture()).placeholder(android.R.drawable.ic_menu_gallery).into(recyclerViewHolder.ivPostUserImg);
}
recyclerViewHolder.tvPostUserName.setText(getPostCallBackList.get(position).getFullName());
recyclerViewHolder.tvPostQuote.setText(getPostCallBackList.get(position).getUserNote());
recyclerViewHolder.tvPostCreatedDate.setText(getPostCallBackList.get(position).getPostDate());
recyclerViewHolder.tvPostTitle.setText(getPostCallBackList.get(position).getPostTitle());
recyclerViewHolder.tvPostCategorySubCategory.setText(getPostCallBackList.get(position).getCatName() + "/" + getPostCallBackList.get(position).getSubCatName());
recyclerViewHolder.tvPostContent.setText(getPostCallBackList.get(position).getPostContent());
recyclerViewHolder.btnAgree.setText("AGREE (" + getPostCallBackList.get(position).getTotalLike() + ")");
recyclerViewHolder.btnDisagree.setText("DISAGREE (" + getPostCallBackList.get(position).getTotalDislike() + ")");
final Activity activity = (Activity) mcontext;
recyclerViewHolder.ReadMore.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(mcontext, PostDetailsActivity.class);
i.putExtra("Details", getPostCallBackList.get(position));
activity.startActivity(i);
activity.overridePendingTransition(R.anim.left_in, R.anim.left_out);
}
});
recyclerViewHolder.btnAgree.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
Intent i = new Intent(mcontext, AgreeListActivity.class);
activity.startActivity(i);
activity.overridePendingTransition(R.anim.left_in, R.anim.left_out);
return true;
}
});
recyclerViewHolder.btnAgree.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
apiCallForUserAgreeDisAgree(getPostCallBackList.get(position).getPostId(), User_Id, "1");
}
});
recyclerViewHolder.btnDisagree.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
apiCallForUserAgreeDisAgree(getPostCallBackList.get(position).getPostId(), User_Id, "0");
}
});
recyclerViewHolder.btnDisagree.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
Intent i = new Intent(mcontext, DisAgreeListActivity.class);
activity.startActivity(i);
activity.overridePendingTransition(R.anim.left_in, R.anim.left_out);
return true;
}
});
recyclerViewHolder.btnComment.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(mcontext, CommentListActivity.class);
activity.startActivity(i);
activity.overridePendingTransition(R.anim.left_in, R.anim.left_out);
}
});
}
//Recycling GoogleMap for list item
#Override
public void onViewRecycled(RecyclerView.ViewHolder holder) {
// Cleanup MapView here?
if (recyclerViewHolder.gMap != null) {
int position = recyclerViewHolder.getPosition();
recyclerViewHolder.gMap.clear();
recyclerViewHolder.gMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
latitude=0.0;
longitude=0.0;
if (!(getPostCallBackList.get(position).getLangitude().equals("") && getPostCallBackList.get(position).getLongitude().equals(""))) {
latitude = Double.parseDouble(getPostCallBackListFiltered.get(position).getLangitude());
longitude = Double.parseDouble(getPostCallBackListFiltered.get(position).getLongitude());
Log.d("TAG", "onBindViewHolder: recycled : " + latitude + " " + longitude);
latlongs = new LatLng(latitude, longitude);
// For zooming automatically to the location of the marker
// CameraPosition cameraPosition = new CameraPosition.Builder().target(latlongs).zoom(14).build();
geocoder = new Geocoder(mcontext, Locale.getDefault());
try {
addressList = geocoder.getFromLocation(latitude, longitude, 1);
if (addressList != null && addressList.size() > 0) {
Address address = addressList.get(0);
StringBuilder sb = new StringBuilder();
StringBuilder sb1 = new StringBuilder();
for (int i = 0; i < address.getMaxAddressLineIndex(); i++) {
sb1.append(address.getAddressLine(i)).append("\n");
mapSnnipet = sb1.toString();
}
sb.append(address.getLocality());
mapTitle = sb.toString();
}
Log.d("TAG", "onMapReady: " + addressList.toString());
} catch (IOException e) {
e.printStackTrace();
}
MarkerOptions a = new MarkerOptions().position(latlongs).title(mapTitle).snippet(mapSnnipet).icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_ORANGE));
recyclerViewHolder.gMap.addMarker(a);
recyclerViewHolder.gMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latlongs, 18.0f));
}
}
}
public void apiCallForUserAgreeDisAgree(String post_id, String user_id, String status) {
if (NetworkUtils.getConnectivityStatus(mcontext) != 0) {
Log.d("TAG", "apiCallForAddPost: User_id : " + user_id);
Log.d("TAG", "apiCallForAddPost: Post id : " + post_id);
Log.d("TAG", "apiCallForAddPost: status : " + status);
API api = App.retrofit.create(API.class);
final Call<UserAgreeCallBack> userAgreeCallBackCall = api.isAgree(post_id, user_id, status);
userAgreeCallBackCall.enqueue(new Callback<UserAgreeCallBack>() {
#Override
public void onResponse(Call<UserAgreeCallBack> call, Response<UserAgreeCallBack> response) {
if (response.code() == 200) {
if (response.body().getStatus().equalsIgnoreCase("success")) {
if (NetworkUtils.getConnectivityStatus(mcontext) != 0) {
dialog = ProgressDialog.show(mcontext, "", "Please Wait.....");
dialog.show();
API api = App.retrofit.create(API.class);
final Call<List<GetPostCallBack>> getPostCallBackCall = api.getAllPost();
getPostCallBackCall.enqueue(new Callback<List<GetPostCallBack>>() {
#Override
public void onResponse(Call<List<GetPostCallBack>> call, Response<List<GetPostCallBack>> response) {
if (dialog != null && dialog.isShowing()) {
dialog.dismiss();
}
if (response.code() == 200) {
updateEmployeeListItems(response.body());
}
}
#Override
public void onFailure(Call<List<GetPostCallBack>> call, Throwable t) {
if (dialog.isShowing() && dialog != null) {
dialog.dismiss();
}
Toast.makeText(mcontext, t.getLocalizedMessage(), Toast.LENGTH_LONG).show();
Log.d("TAG", "onFailure: " + t.getLocalizedMessage());
}
});
} else {
Toast.makeText(mcontext, "Please check your internet connection", Toast.LENGTH_SHORT).show();
}
}
}
}
#Override
public void onFailure(Call<UserAgreeCallBack> call, Throwable t) {
Toast.makeText(mcontext, t.getLocalizedMessage(), Toast.LENGTH_LONG).show();
Log.d("TAG", "onFailure: " + t.getLocalizedMessage());
}
});
} else {
Toast.makeText(mcontext, "Please check your internet connection", Toast.LENGTH_SHORT).show();
}
}
public void updateEmployeeListItems(List<GetPostCallBack> employees) {
final GetPostCallBack diffCallback = new GetPostCallBack(this.getPostCallBackList, employees);
final DiffUtil.DiffResult diffResult = DiffUtil.calculateDiff(diffCallback);
this.getPostCallBackList.clear();
this.getPostCallBackList.addAll(employees);
diffResult.dispatchUpdatesTo(this);
}
#Override
public int getItemCount() {
return getPostCallBackList == null ? 0 : getPostCallBackList.size();
}
private Filter fRecords;
#Override
public Filter getFilter() {
if(fRecords == null) {
fRecords=new RecordFilter();
}
return fRecords;
}
class RecyclerViewHolder extends RecyclerView.ViewHolder implements OnMapReadyCallback {
GoogleMap gMap;
MapView map;
#BindView(R.id.tvReadMore)
TextView ReadMore;
#BindView(R.id.btnAgree)
Button btnAgree;
#BindView(R.id.btnDisagree)
Button btnDisagree;
#BindView(R.id.btnComment)
Button btnComment;
#BindView(R.id.ivPostUserImg)
CircularImageView ivPostUserImg;
#BindView(R.id.tvPostUserName)
TextView tvPostUserName;
#BindView(R.id.tvPostQuote)
TextView tvPostQuote;
#BindView(R.id.tvPostCreatedDate)
TextView tvPostCreatedDate;
#BindView(R.id.tvPostTitle)
TextView tvPostTitle;
#BindView(R.id.tvPostCategorySubCategory)
TextView tvPostCategorySubCategory;
#BindView(R.id.tvPostContent)
TextView tvPostContent;
public RecyclerViewHolder(View itemView) {
super(itemView);
ButterKnife.bind(this, itemView);
map = (MapView) view.findViewById(R.id.mapAdapter);
if (map != null) {
map.onCreate(null);
map.onResume();
map.getMapAsync(this);
}
}
#Override
public void onMapReady(GoogleMap googleMap) {
MapsInitializer.initialize(getApplicationContext());
gMap = googleMap;
final int position = getPosition();
if (gps.canGetLocation()) {
latitude=0.0;
longitude=0.0;
if (!(getPostCallBackList.get(position).getLangitude().equals("") && getPostCallBackList.get(position).getLongitude().equals(""))) {
latitude = Double.parseDouble(getPostCallBackList.get(position).getLangitude());
longitude = Double.parseDouble(getPostCallBackList.get(position).getLongitude());
Log.d("TAG", "onBindViewHolder: " + latitude + " " + longitude);
latlongs = new LatLng(latitude, longitude);
// For zooming automatically to the location of the marker
// CameraPosition cameraPosition = new CameraPosition.Builder().target(latlongs).zoom(14).build();
geocoder = new Geocoder(mcontext, Locale.getDefault());
try {
addressList = geocoder.getFromLocation(latitude, longitude, 1);
if (addressList != null && addressList.size() > 0) {
Address address = addressList.get(0);
StringBuilder sb = new StringBuilder();
StringBuilder sb1 = new StringBuilder();
for (int i = 0; i < address.getMaxAddressLineIndex(); i++) {
sb1.append(address.getAddressLine(i)).append("\n");
mapSnnipet = sb1.toString();
}
sb.append(address.getLocality());
mapTitle = sb.toString();
}
Log.d("TAG", "onMapReady: " + addressList.toString());
} catch (IOException e) {
e.printStackTrace();
}
MarkerOptions a = new MarkerOptions().position(latlongs).title(mapTitle).snippet(mapSnnipet).icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_ORANGE));
if (gMap != null) {
gMap.addMarker(a);
gMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latlongs, 18.0f));
gMap.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener() {
#Override
public boolean onMarkerClick(Marker marker) {
if (marker != null){
latitudeForMarker = Double.parseDouble(getPostCallBackList.get(position).getLangitude());
longitudeForMarker = Double.parseDouble(getPostCallBackList.get(position).getLongitude());
Log.d("TAG", "onMarkerClick: on viewcreated : http://maps.google.com/maps?daddr="+latitudeForMarker+","+longitudeForMarker);
// Intent intent = new Intent(android.content.Intent.ACTION_VIEW,
// Uri.parse("google.navigation:q="+mapSnnipet));
Intent intent = new Intent(android.content.Intent.ACTION_VIEW,
Uri.parse("http://maps.google.com/maps?daddr="+latitudeForMarker+","+longitudeForMarker));
mcontext.startActivity(intent);
return true;
}
return false;
}
});
}
}
}
}
}
//filter class
private class RecordFilter extends Filter {
#Override
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults results = new FilterResults();
//Implement filter logic
// if edittext is null return the actual list
if (constraint == null || constraint.length() == 0) {
//No need for filter
// getPostCallBackList.clear();
// getPostCallBackList.addAll(getPostCallBackListFiltered);
results.values = getPostCallBackListFiltered;
results.count = getPostCallBackListFiltered.size();
} else {
//Need Filter
// it matches the text entered in the edittext and set the data in adapter list
ArrayList<GetPostCallBack> fRecords = new ArrayList<>();
for (GetPostCallBack s : getPostCallBackListFiltered) {
if (s.getFullName().toLowerCase().contains(constraint.toString().toLowerCase().trim())) {
fRecords.add(s);
}
}
results.values = fRecords;
results.count = fRecords.size();
}
return results;
}
#Override
protected void publishResults(CharSequence constraint,FilterResults results) {
//it set the data from filter to adapter list and refresh the recyclerview adapter
getPostCallBackList = (ArrayList<GetPostCallBack>) results.values;
notifyDataSetChanged();
}
}
}
HomeActivity.java
public class HomeActivity extends FooterController implements FragmentManager.OnBackStackChangedListener {
#BindView(R.id.recyclerHome)
RecyclerView recyclerHome;
#BindView(R.id.fab)
Button fab;
#BindView(R.id.toolbar)
Toolbar toolbar;
#BindView(R.id.actvLocationFilter)
AutoCompleteTextView actvLocationFilter;
public static ImageView ivSearch;
#BindView(R.id.etSearch)
EditText etSearch;
public static TextView tvTitle;
public static TextView tvBack;
#BindView(R.id.tvPost)
TextView tvPost;
//#BindView(R.id.ivDrawer)
public static ImageView ivDrawer;
#BindView(R.id.drawer_layout)
DrawerLayout drawer;
#BindView(R.id.navList)
ListView mDrawerList;
private ArrayAdapter<String> drawerAdapter;
LinearLayoutManager linearLayoutManager;
PostListAdapter adapter;
private boolean isLoading = false;
private boolean isLastPage = false;
Dialog dialog;
API api;
FragmentManager fm;
GPSTracker gps;
Boolean buttonStateOpen=false;
public static int tabPosisiton=0;
FindExperienceDatabase db;
List<GetPostCallBack> getPostList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
ButterKnife.bind(this);
setBottomBar(R.id.bottomBar,false);
bindWidgets();
setCustomActionBar();
addDrawerItems();
openDrawer();
fm = getSupportFragmentManager();
Functions.checkNetworkConnection(HomeActivity.this);
apiCallForGetPost();
mDrawerList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
fm = getSupportFragmentManager();
// fm.popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE);
switch (position){
case 0:
fm.beginTransaction().replace(R.id.container, new ProfileFragment()).addToBackStack(null).commit();
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
break;
case 1:
fm.beginTransaction().replace(R.id.container, new SettingFragment()).addToBackStack(null).commit();
break;
default:
break;
}
drawer.closeDrawer(Gravity.RIGHT);
}
});
public void apiCallForGetPost(){
getPostList = new ArrayList<>();
if (NetworkUtils.getConnectivityStatus(HomeActivity.this)!=0) {
dialog = ProgressDialog.show(this, "", "Please Wait.....");
dialog.show();
API api = App.retrofit.create(API.class);
final Call<List<GetPostCallBack>> getPostCallBackCall = api.getAllPost();
getPostCallBackCall.enqueue(new Callback<List<GetPostCallBack>>() {
#Override
public void onResponse(Call<List<GetPostCallBack>> call, Response<List<GetPostCallBack>> response) {
if (dialog != null && dialog.isShowing()) {
dialog.dismiss();
}
if (response.code()==200){
getPostList = response.body();
setRecyclerViewAdapter(getPostList);
}
}
#Override
public void onFailure(Call<List<GetPostCallBack>> call, Throwable t) {
if (dialog.isShowing() && dialog != null) {
dialog.dismiss();
}
Toast.makeText(HomeActivity.this, t.getLocalizedMessage(), Toast.LENGTH_LONG).show();
Log.d("TAG", "onFailure: " + t.getLocalizedMessage());
}
});
} else {
Toast.makeText(HomeActivity.this, "Please check your internet connection", Toast.LENGTH_SHORT).show();
}
}
#OnClick(R.id.iv_search)
public void search(){
if (etSearch.getVisibility()==View.GONE) {
etSearch.setVisibility(View.VISIBLE);
etSearch.setOnEditorActionListener(new TextView.OnEditorActionListener() {
#Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
if (actionId == EditorInfo.IME_ACTION_DONE) {
etSearch.clearFocus();
InputMethodManager in = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
in.hideSoftInputFromWindow(etSearch.getWindowToken(), 0);
etSearch.setVisibility(View.GONE);
return true;
}
return false;
}
});
etSearch.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
adapter.getFilter().filter(s.toString()); // Perform Filter on Adapter
}
#Override
public void afterTextChanged(Editable s) {
}
});
}
else if (etSearch.getVisibility()==View.VISIBLE){
InputMethodManager in = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
in.hideSoftInputFromWindow(etSearch.getWindowToken(), 0);
etSearch.setVisibility(View.GONE);
}
}
public void setRecyclerViewAdapter(List<GetPostCallBack> getPostList){
adapter = new PostListAdapter(HomeActivity.this,fm,getPostList);
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
recyclerHome.setLayoutManager(mLayoutManager);
recyclerHome.smoothScrollToPosition(0);
recyclerHome.setAdapter(adapter);
}
public void openDrawer(){
getSupportFragmentManager().addOnBackStackChangedListener(this);
ivDrawer.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
drawer.openDrawer(Gravity.RIGHT);
buttonStateOpen=true;
}
});
}
private void addDrawerItems() {
String[] osArray = { "Profile", "Settings" };
drawerAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, osArray);
mDrawerList.setAdapter(drawerAdapter);
}
#Override
public void onBackStackChanged() {
shouldDisplayHomeUp();
Log.d("TAG", "onBackStackChanged: ");
}
public void shouldDisplayHomeUp(){
//Enable Up button only if there are entries in the back stack
Log.d("TAG", "shouldDisplayHomeUp: "+getSupportFragmentManager().getBackStackEntryCount());
boolean canback = getSupportFragmentManager().getBackStackEntryCount() > 0;
getSupportActionBar().setDisplayHomeAsUpEnabled(canback);
}
}
Use the ViewHolder "holder", which is passed on to your Override function
public void onViewRecycled(RecyclerView.ViewHolder holder)
It will work as intended.

Using searchview in actionbar in fragments

I am displaying a userlist and I am using serachview in my actionbar to search. When I am using the searchView in activity, it works fine but when I use it for fragment, searchview doesn't work. It does not search in the listview.
Below is my code.
UserListFragment.java
public class UsersListFragment extends Fragment {
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
Activity activity;
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
private static final String TAG = "UsersListFragment";
private OnFragmentInteractionListener mListener;
private ListView listView;
private List<UserData> users;
private CustomAdapter adapter;
SharedPreferences.Editor preferenceEditor;
Timer myTimer;
View view;
ActionBar actionBar;
private static final String PREFRENCES_NAME = "setPreferences";
private ProgressDialog progressBar;
String partnerKeyValue;
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* #param param1 Parameter 1.
* #param param2 Parameter 2.
* #return A new instance of fragment UsersListFragment.
*/
// TODO: Rename and change types and number of parameters
public static UsersListFragment newInstance(String param1, String param2) {
UsersListFragment fragment = new UsersListFragment();
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);
progressBar = new ProgressDialog(getActivity());
progressBar.setCancelable(false);
progressBar.setMessage("Loading...");
progressBar.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progressBar.setProgress(0);
Log.i(TAG, "UsersListFragment onCreate");
users = new ArrayList<>();
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
SharedPreferences preferenceSettings = getActivity().getSharedPreferences(PREFRENCES_NAME,Context.MODE_PRIVATE);
preferenceEditor = preferenceSettings.edit();
preferenceEditor.putString("refresh","userlistview");
preferenceEditor.commit();
FirebaseUtil uts = new FirebaseUtil(getContext());
uts.startListeningNotification(Global.getInstance().ownerId, new CallBack() {
#Override
public void onCallback(Map<String, Object> response, String Success) {
Log.i(TAG, Success);
setHasOptionsMenu(true);
String partnerKey = (String) response.get("key");
if (partnerKey != null) {
Map<String, Object> typeCheck = (Map<String, Object>) response.get("value");
String type = (String) typeCheck.get("type");
if (type.equals("chat")) {
String key1 = Global.getInstance().ownerId;
String key2 = partnerKey;
partnerKeyValue = partnerKey;
if (key2 != null) {
String currentPartner = Global.getInstance().partnerId;
if (currentPartner.length() > 0) {
if (currentPartner.equals(partnerKey)) {
} else {
Global.getInstance().unreadMessageUsers.add(partnerKey);
}
Global.getInstance().unreadMessageUsers.add(partnerKey);
} else {
}
}
}
}
}
});
}
#Override
public void onStart() {
super.onStart();
Log.i(TAG, "UsersListFragment onStart");
}
#Override
public void onResume() {
super.onResume();
Log.i(TAG, "UsersListFragment onResume");
}
#Override
public void onPause() {
super.onPause();
Log.i(TAG, "UsersListFragment onStart");
}
#Override
public void onStop() {
super.onStop();
Log.i(TAG, "UsersListFragment onStop");
}
#Override
public void onDestroyView() {
super.onDestroyView();
}
#Override
public void onDestroy() {
super.onDestroy();
FirebaseUtil util = new FirebaseUtil(getContext());
util.updateUserStatus(Global.getInstance().ownerId, "4");
Log.i(TAG, "UsersListFragment onDestroy");
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
actionBar = ((AppCompatActivity) getActivity()).getSupportActionBar();
if(actionBar!=null) {
actionBar.setDisplayUseLogoEnabled(true);
actionBar.setDisplayShowHomeEnabled(true);
actionBar.setDisplayHomeAsUpEnabled(false);
actionBar.setLogo(R.drawable.ic_logo);
ColorDrawable colorDrawable = new ColorDrawable(Color.parseColor("#006EAD"));
actionBar.setBackgroundDrawable(colorDrawable);
}
Toast.makeText(getActivity(), String.valueOf( Global.getInstance().unreadMessageUsers.size()) , Toast.LENGTH_SHORT).show();
int vd = users.size();
view = inflater.inflate(R.layout.fragment_userslist, container, false);
listView = (ListView) view.findViewById(R.id.userdisplay);
adapter = new CustomAdapter(getActivity(),R.layout.program_list, users );
listView.setAdapter(adapter);
if (users.size()==0){
usersList();
}else {
adapter.notifyDataSetChanged();
}
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
UserData data = users.get(position);
Global.getInstance().someData = data.getId();
Global.getInstance().partnerId = data.getId();
int i = 0;
for (Iterator<String> iter = Global.getInstance().unreadMessageUsers.iterator(); iter.hasNext(); ) {
String element = iter.next();
if (element.equals(data.getId().toString())) {
iter.remove();
}
}
data.setUnreadMessageCount(0);
users.remove(position);
users.add(position, data);
Toast.makeText(getActivity().getApplicationContext(),String.valueOf(Global.getInstance().unreadMessageUsers.size()),Toast.LENGTH_LONG).show();
Fragment fragmentOne = new ChatFragment();
android.support.v4.app.FragmentTransaction ft = getActivity().getSupportFragmentManager().beginTransaction();
Bundle args = new Bundle();
args.putString(ChatFragment.DATA_RECEIVE, data.getName());
fragmentOne .setArguments(args);
ft.addToBackStack(null);
ft.replace(R.id.framecontainerMain, fragmentOne).commit();
}
});
// Inflate the layout for this fragment
return view;
}
public void usersList () {
SharedPreferences preferenceSettings = getActivity().getSharedPreferences(PREFRENCES_NAME,Context.MODE_PRIVATE);
preferenceEditor = preferenceSettings.edit();
//get the data from userlist api
final String URL = "url";
String token = preferenceSettings.getString("authToken","");
final String userId = preferenceSettings.getString("userId","");
HashMap<String, String> params = new HashMap<String, String>();
params.put("user_id",userId);
params.put("auth_token",token);
progressBar.show();
JsonObjectRequest myRequest = new JsonObjectRequest(Request.Method.POST, URL,new JSONObject(params),
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.i(TAG, "onResponse:" +response);
String success = null;
try {
success = response.getString("success");
} catch (JSONException e) {
e.printStackTrace();
}
if(success == "true") {
JSONArray Array = null;
try {
//get the users
} else {
users.add(data);
}
}
Log.i(TAG, "arraylist");
adapter.notifyDataSetChanged();
onlineUsers();
myTimer = new Timer();
myTimer.schedule(new TimerTask() {
#Override
public void run() {
TimerMethod();
}
}, 0, 5000);
progressBar.dismiss();
} catch (JSONException e) {
e.printStackTrace();
}
JSONObject Obj;
} else {
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
progressBar.dismiss();
VolleyLog.e("Error: ", error.getMessage());
Log.i(TAG, "onErrorResponse:" +error.networkResponse);
}
});
ApplicationController.getInstance().addToRequestQueue(myRequest);
myRequest.setRetryPolicy(new DefaultRetryPolicy(
5000,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
}
public void sortingArray(){
if (users.size()>0) {
synchronized (this) {
if (Global.getInstance().unreadMessageUsers.size() > 0) {
System.out.println("\nExample 3 - Count all with Map");
Map<String, Integer> map = new HashMap<String, Integer>();
for (String temp : Global.getInstance().unreadMessageUsers) {
Integer count = map.get(temp);
map.put(temp, (count == null) ? 1 : count + 1);
}
System.out.println("\nSorted Map");
Map<String, Integer> unreadCount = new TreeMap<String, Integer>(map);
for (String key : unreadCount.keySet()) {
int count_unread = unreadCount.get(key);
int i = 0;
for (UserData obj : users) {
UserData user = obj;
if (user.getId().equals(key)) {
user.setUnreadMessageCount(count_unread);
users.remove(i);
users.add(i, user);
break;
}
i++;
}
}
}
synchronized (this) {
if (Global.getInstance().userStatus.size() > 0) {
try {
for (Object dict : Global.getInstance().userStatus) {
Map<String, Object> val = (Map<String, Object>) dict;
String key = val.keySet().iterator().next();
val.get(key).toString().trim();
int statusValue;
if (val.get(key).toString().equals("")) {
statusValue = 4;
} else {
statusValue = Integer.valueOf(val.get(key).toString());
}
int i = 0;
for (UserData obj : users) {
UserData user = obj;
if (user.getId().equals(key)) {
user.setOnlineStatus(statusValue);
users.remove(i);
users.add(i, user);
break;
}
i++;
}
}
}catch (ConcurrentModificationException e){
e.printStackTrace();
}
}
}
Log.i(TAG, users.get(0).getName());
if (users.size() > 0) {
Collections.sort(users, new Comparator<UserData>() {
#Override
public int compare(UserData o1, UserData o2) {
if (o1.getOnlineStatus() > o2.getOnlineStatus()) {
return 1;
} else if (o1.getOnlineStatus() < o2.getOnlineStatus()) {
return -1;
} else {
return 0;
}
}
});
}
if (users.size() > 0) {
Collections.sort(users, new Comparator<UserData>() {
#Override
public int compare(UserData o1, UserData o2) {
if (o1.getUnreadMessageCount() > o2.getUnreadMessageCount()) {
return -1;
} else if (o1.getUnreadMessageCount() < o2.getUnreadMessageCount()) {
return 1;
} else {
return 0;
}
}
});
Global.getInstance().userStatus.clear();
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getActivity().getApplicationContext(), "any mesage", Toast.LENGTH_LONG).show();
adapter.notifyDataSetChanged();
}
});
}
}
}
}
public void TimerMethod() {
synchronized(this) {
SharedPreferences preferenceSettings = getActivity().getSharedPreferences("setPreferences", Context.MODE_PRIVATE);
String checkView = preferenceSettings.getString("refresh", "");
if (checkView.equals("userlistview")) {
if (Global.getInstance().userStatus.size() > 0) {
sortingArray();
}
} else {
preferenceEditor = preferenceSettings.edit();
preferenceEditor.putString("refresh", "userlistview");
preferenceEditor.commit();
if (Global.getInstance().unreadMessageUsers.size() > 0){
sortingArray();
}
}
}
}
public void onlineUsers (){
String value;
for (UserData data : users) {
value = data.getId();
FirebaseUtil online = new FirebaseUtil(getContext());
online.onlineUsers(value, new CallBack() {
#Override
public void onCallback(Map<String, Object> response, String Success) {
if (response == null) {
} else {
Global.getInstance().userStatus.add(response);
}
}
});
}
}
#Override
public void onCreateOptionsMenu(Menu menu,MenuInflater inflater) {
inflater.inflate(R.menu.menu_userlist,menu);
MenuItem item = menu.findItem(R.id.menuSearch);
SearchView searchView = (SearchView)item.getActionView();
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
adapter.getFilter().filter(newText);
return false;
}
});
super.onCreateOptionsMenu(menu,inflater);
}
private void logoutUser(){
Intent I = new Intent(getActivity(), LoginActivity.class);
startActivity(I);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menuSearch :
return true;
case R.id.menuLogout :
logoutUser();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
if (mListener != null) {
String val = "'";
mListener.onFragmentInteraction(val);
}
}
public void initlizeval(Context context) {
mListener = (OnFragmentInteractionListener) context;
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentInteractionListener) {
mListener = (OnFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentInteractionListener");
}
}
#Override
public void onDetach() {
super.onDetach();
myTimer.cancel();
mListener = null;
}
/**
* This interface must be implemented by activities that contain this
* fragment to allow an interaction in this fragment to be communicated
* to the activity and potentially other fragments contained in that
* activity.
* <p>
* See the Android Training lesson <a href=
* "http://developer.android.com/training/basics/fragments/communicating.html"
* >Communicating with Other Fragments</a> for more information.
*/
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
void onFragmentInteraction(String val);
}
}
menu_userlist.xml
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item android:id="#+id/menuSearch"
android:title="#string/search"
android:icon="#drawable/ic_search"
app:actionViewClass="android.widget.SearchView"
app:showAsAction="always">
</item>
<item android:id="#+id/menuLogout"
android:title="#string/logout"
android:icon="#drawable/ic_logout"
android:tint="#android:color/white"
app:showAsAction="always">
</item>
</menu>
CustomAdapter.java
import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.List;
public class CustomAdapter extends ArrayAdapter<UserData> {
private Activity activity;
private List<UserData> messages;
public CustomAdapter(Activity context, int resource, List<UserData> objects) {
super(context, resource, objects);
this.activity = context;
this.messages = objects;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
packagename.CustomAdapter.ViewHolder holder;
LayoutInflater inflater = (LayoutInflater) activity.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
int layoutResource = 0; // determined by view type
UserData data = getItem(position);
int viewType = getItemViewType(position);
layoutResource = R.layout.program_list;
if (convertView != null) {
holder = (com.your.package.CustomAdapter.ViewHolder) convertView.getTag();
} else {
convertView = inflater.inflate(layoutResource, parent, false);
holder = new com.your.package.CustomAdapter.ViewHolder(convertView);
convertView.setTag(holder);
}
//set message content
holder.msg.setText(data.getName());
holder.id = data.geId();
holder.roleMsg.setText(data.getRole());
return convertView;
}
#Override
public int getViewTypeCount() {
// return the total number of view types. this value should never change
// at runtime
return 2;
}
#Override
public int getItemViewType(int position) {
// return a value between 0 and (getViewTypeCount - 1)
return position % 2;
}
private class ViewHolder {
private TextView msg;
private String id;
private TextView roleMsg;
public ViewHolder(View v) {
msg = (TextView) v.findViewById(R.id.textView1);
roleMsg = (TextView) v.findViewById(R.id.textView2);
}
}
}
HomeActivity.java
public class HomeActivity extends AppCompatActivity implements UsersListFragment.OnFragmentInteractionListener {
private UsersListFragment mItemsFragment;
private ChatFragment mFragmentOne;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
VideoFragment fragmentTwo ;
LinearLayout layout1 = (LinearLayout) findViewById(R.id.framecontainer);
layout1.setVisibility(View.VISIBLE);
LinearLayout layout2 = (LinearLayout) findViewById(R.id.framecontainerTab);
layout2.setVisibility(View.VISIBLE);
mItemsFragment = new UsersListFragment();
mItemsFragment.initlizeval(this);
android.support.v4.app.FragmentTransaction fts = getSupportFragmentManager().beginTransaction();
fts.add(R.id.framecontainer, mItemsFragment).commit();
//Instantiate some stuff here like view components
Fragment fragmentOne = new ChatFragment();
android.support.v4.app.FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.add(R.id.framecontainerTab, fragmentOne).commit();
}else{
LinearLayout layout1 = (LinearLayout) findViewById(R.id.framecontainer);
layout1.setVisibility(View.GONE);
LinearLayout layout2 = (LinearLayout) findViewById(R.id.framecontainerTab);
layout2.setVisibility(View.GONE);
layout2.removeAllViews();
mItemsFragment = new UsersListFragment();
mItemsFragment.initlizeval(this);
setFragment(mItemsFragment);
}
}
public void setFragment(Fragment frag)
{
android.support.v4.app.FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
}
public void attemptLogin1() {
String test = "one";
String tested = "fail";
}
#Override
public void onFragmentInteraction(String uri) {
LinearLayout layout1 = (LinearLayout) findViewById(R.id.framecontainer);
layout1.setVisibility(View.GONE);
LinearLayout layout2 = (LinearLayout)findViewById(R.id.framecontainerTab);
layout2.setVisibility(View.GONE);
findViewById(R.id.framecontainerVideo);
Toast.makeText(getApplicationContext(), "bullet", Toast.LENGTH_SHORT).show();
}
#Override
protected void onPause() {
super.onPause();
}
#Override
protected void onResume() {
super.onResume();
}
#Override
public void onBackPressed() {
super.onBackPressed();
Fragment fragmentOne = new ChatFragment();
LinearLayout layout1 = (LinearLayout) findViewById(R.id.framecontainer);
layout1.setVisibility(View.VISIBLE);
LinearLayout layout2 = (LinearLayout) findViewById(R.id.framecontainerTab);
layout2.setVisibility(View.VISIBLE);
}
#Override
protected void onStart() {
super.onStart();
getDelegate().onStart();
}
}
I have written setHasOptionsMenu(true); in onCreate of UserFragment.java
The logout functionality works fine but the search isn't working.
I have tried various options given on Stackoverflow as well as from other resource, but nothing worked. :(
Any help is appreciated.
Thanks in advance.
Create Constructor in your fragment. Pass Context object inside fragment constructor.which allows your activity as global access.
Remove this line and it will work
case R.id.menuSearch:
return true;

Android OutOfMemory error in Fragment onSaveInstanceState

I have a Fragment with RecyclerView, which holds items with ImageView (basically like gallery app). Images are displayed using async task to do the work in separate thread. Images are displayed from base64 encoded string. Images are also cached with lrucache.
Problem
Everything works fine until i rotate the device 3rd or 4th time. The device crashes with out of memory error in onSaveInstanceState method.
Question
Any ideas how to prevent the OutOfMemory error? Thanks in advance
Code
Activity
public class TabsActivity extends BaseActivity implements ViewPager.OnPageChangeListener,
ActivityActions, TabLayout.OnTabSelectedListener {
private static final String TAG = TabsActivity.class.getSimpleName();
private static final String STATE_TAB_LAYOUT = "STATE_TAB_LAYOUT";
private static final String STATE_TOOLBAR = "STATE_TOOLBAR";
public static final String ACTION_TASKS = "ACTION_TASKS";
public static final String ACTION_MESSAGES = "ACTION_MESSAGES";
public static final int REQUEST_TASK_UPDATE = 1;
public static final int REQUEST_MESSAGE_UPDATE = 2;
private Toolbar toolbar;
private TabLayout tabLayout;
private ViewPager viewPager;
private FloatingActionButton createButton;
private PrefsManager prefsManager;
private ViewPagerAdapter adapter;
private LocalBroadcastManager broadcastManager;
private NotificationReceiver notificationReceiver;
private FragmentManager.OnBackStackChangedListener backStackChangedListener;
#Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tabs);
prefsManager = PrefsManager.getInstance(this);
notificationReceiver = new NotificationReceiver();
backStackChangedListener = new FragmentManager.OnBackStackChangedListener() {
#Override
public void onBackStackChanged() {
if (getSupportFragmentManager().getBackStackEntryCount() == 0) {
onSettingsFragmentStateChanged(false);
}
}
};
tabLayout = (TabLayout) findViewById(R.id.tab_layout);
toolbar = (Toolbar) findViewById(R.id.toolbar);
viewPager = (ViewPager) findViewById(R.id.view_pager);
createButton = (FloatingActionButton) findViewById(R.id.floating_action_button);
createButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
KeyboardUtils.hideSoftwareInput(TabsActivity.this);
if (adapter.getCurrentTab(viewPager.getCurrentItem()) == Tab.TASKS) {
createNewTask();
} else {
createNewConversation();
}
}
});
setSupportActionBar(toolbar);
toolbar.setNavigationIcon(R.drawable.ic_action_back);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onBackPressed();
}
});
final String action = getIntent().getAction();
adapter = new ViewPagerAdapter(getSupportFragmentManager());
adapter.setAdapterListener(new ExtendedPagerAdapter.AdapterListener() {
#Override
public void onAdapterInstantiated() {
if (savedInstanceState == null && action != null) {
if (action.equals(ACTION_TASKS)) {
onPageSelected(viewPager.getCurrentItem());
} else {
viewPager.setCurrentItem(1);
}
}
}
});
viewPager.addOnPageChangeListener(this);
viewPager.setAdapter(adapter);
tabLayout.setupWithViewPager(viewPager);
tabLayout.setOnTabSelectedListener(this);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_TASK_UPDATE) {
if (resultCode == Activity.RESULT_OK) {
((TasksFragment) adapter.getFragment(Tab.TASKS)).onTasksUpdated();
}
} else if (requestCode == REQUEST_MESSAGE_UPDATE) {
TabFragment tabFragment = adapter.getFragment(Tab.MESSAGES);
if (resultCode == Activity.RESULT_OK) {
if (tabFragment != null) {
((MessagesFragment) tabFragment).onNewMessagesReceived();
}
} else {
((MessagesFragment) tabFragment).initData();
}
}
super.onActivityResult(requestCode, resultCode, data);
}
#Override
protected void onResume() {
broadcastManager = LocalBroadcastManager.getInstance(this);
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(BroadcastConfig.ACTION_NEW_MESSAGE);
intentFilter.addAction(BroadcastConfig.ACTION_USER_STATUS);
broadcastManager.registerReceiver(notificationReceiver, intentFilter);
getSupportFragmentManager().addOnBackStackChangedListener(backStackChangedListener);
super.onResume();
}
#Override
protected void onPause() {
broadcastManager.unregisterReceiver(notificationReceiver);
getSupportFragmentManager().removeOnBackStackChangedListener(backStackChangedListener);
super.onPause();
}
#Override
protected void onRestoreInstanceState(Bundle inState) {
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setTitle(inState.getString(STATE_TOOLBAR));
}
if (!inState.getBoolean(STATE_TAB_LAYOUT)) {
onSettingsFragmentStateChanged(true);
}
super.onRestoreInstanceState(inState);
}
#Override
public void onSaveInstanceState(Bundle outState) {
outState.putBoolean(STATE_TAB_LAYOUT, tabLayout.getVisibility() == View.VISIBLE);
outState.putString(STATE_TOOLBAR, toolbar.getTitle().toString());
super.onSaveInstanceState(outState);
}
#Override
public void onBackPressed() {
MenuItem menuItem = toolbar.getMenu().findItem(R.id.action_search);
if (menuItem != null && !((SearchView) menuItem.getActionView()).isIconified()) {
((SearchView) menuItem.getActionView()).onActionViewCollapsed();
return;
}
if (popSupportBackStack(SettingsFragment.class.getSimpleName())) {
return;
}
setResult(RESULT_OK);
finish();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_contacts, menu);
SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
SearchView searchView = (SearchView) menu.findItem(R.id.action_search).getActionView();
searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
adapter.getFragment(viewPager.getCurrentItem()).onSearchPhraseChanged(newText);
return true;
}
});
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_settings:
onSettingsClick();
break;
case R.id.action_refresh:
onRefreshClick();
break;
default:
break;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onPageSelected(int position) {
if (adapter.isInstantiated()) {
onToolbarTitleChanged(adapter.getPageTitle(position).toString());
onToolbarSubtitleChanged(UserStatus.NONE);
}
}
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageScrollStateChanged(int state) {
}
#Override
public void onTabSelected(TabLayout.Tab tab) {
if (adapter.getCurrentTab(tab.getPosition()).getFragmentTitle()
== Tab.ATTACHMENT_HISTORY.getFragmentTitle()) {
createButton.hide();
}
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(final TabLayout.Tab tab) {
createButton.hide(new FloatingActionButton.OnVisibilityChangedListener() {
#Override
public void onHidden(FloatingActionButton fab) {
fab.show();
}
});
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
#Override
public void requestDisplayDetails(Intent intent, int requestCode) {
startActivityForResult(intent, requestCode);
}
#Override
public void refreshTasks() {
adapter.getFragment(Tab.TASKS).onRefresh();
}
#Override
public void refreshMessages() {
adapter.getFragment(Tab.MESSAGES).onRefresh();
}
#Override
public boolean isNetworkAvailable() {
return checkNetworkAvailability();
}
private void createNewTask() {
startActivityForResult(new Intent(this, CreateTaskActivity.class), REQUEST_TASK_UPDATE);
}
private void createNewConversation() {
MessagesFragment fragment = (MessagesFragment) adapter.getFragment(Tab.MESSAGES);
startActivityForResult(new Intent(TabsActivity.this, MessageDetailsActivity.class)
.setAction(MessageDetailsActivity.ACTION_CREATE_MESSAGE)
.putExtra(MessageDetailsActivity.EXTRA_EXIST_CONV,
fragment.getCreatedConversations()), REQUEST_MESSAGE_UPDATE);
}
private void setTabLayoutVisible(boolean visible) {
int visibility = visible ? View.VISIBLE : View.GONE;
tabLayout.setVisibility(visibility);
}
private void onRefreshClick() {
if (checkNetworkAvailability()) {
adapter.getFragment(viewPager.getCurrentItem()).onRefresh();
}
}
private void onSettingsClick() {
getSupportFragmentManager()
.beginTransaction()
.add(R.id.fragment_container, new SettingsFragment(), SettingsFragment.class.getSimpleName())
.addToBackStack(SettingsFragment.class.getSimpleName())
.commit();
onSettingsFragmentStateChanged(true);
}
private void onSettingsFragmentStateChanged(boolean visibleState) {
if (visibleState) {
isFragmentDialog = true;
onToolbarTitleChanged(getString(R.string.title_settings));
setTabLayoutVisible(false);
createButton.hide();
} else {
onPageSelected(viewPager.getCurrentItem());
setTabLayoutVisible(true);
if (adapter.getCurrentTab(viewPager.getCurrentItem()) != Tab.ATTACHMENT_HISTORY) {
createButton.show();
}
}
}
public void onToolbarTitleChanged(String title) {
toolbar.setTitle(title);
}
public void onToolbarSubtitleChanged(UserStatus userStatus) {
if (userStatus != null) {
toolbar.setSubtitle(userStatus.getText());
toolbar.setSubtitleTextColor(userStatus.getColor());
}
}
public void onLogoutConfirmed() {
HttpRequestManager.logout(prefsManager.getPhpSessId(), App.getPhoneId(this), prefsManager.getUserId(),
new HttpCallback<LogoutResponse>() {
#Override
public void onResponse(LogoutResponse logoutResponse) {
prefsManager.reset();
DBManager.delete(TabsActivity.this, DeleteTask.DeleteType.ALL, new Callback<Boolean>() {
#Override
public void onResponseReceived(Boolean params) {
startActivity(new Intent(TabsActivity.this, LoginActivity.class)
.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK));
finish();
}
});
}
});
}
private class NotificationReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (action.equals(BroadcastConfig.ACTION_NEW_MESSAGE) || action.equals(BroadcastConfig.ACTION_USER_STATUS)) {
TabFragment childFragment = adapter.getFragment(Tab.MESSAGES);
if (childFragment != null) {
((MessagesFragment) childFragment).onNewMessagesReceived();
}
}
}
}
private class ViewPagerAdapter extends ExtendedPagerAdapter {
private final List<Tab> tabs = Tab.getAllTabs();
private final List<TabFragment> fragments = new ArrayList<>();
public ViewPagerAdapter(FragmentManager fragmentManager) {
super(fragmentManager);
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
fragments.add((TabFragment) super.instantiateItem(container, position));
return fragments.get(fragments.size() - 1);
}
#Override
public Fragment getItem(int position) {
Log.e(TAG, "CreatingFragment: " + tabs.get(position).getFragmentClass().getCanonicalName());
return Fragment.instantiate(TabsActivity.this, tabs.get(position).getFragmentClass().getCanonicalName());
}
#Override
public CharSequence getPageTitle(int position) {
return getString(tabs.get(position).getFragmentTitle());
}
#Override
public int getCount() {
return tabs.size();
}
public Tab getCurrentTab(int position) {
return tabs.get(position);
}
public TabFragment getFragment(int position) {
if (getCount() > position) {
return fragments.get(position);
}
return null;
}
public TabFragment getFragment(Tab tab) {
for (TabFragment tabFragment : fragments) {
if (tab.getFragmentClass() == tabFragment.getClass()) {
return tabFragment;
}
}
return null;
}
}
}
Fragment
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
swipeRefresh = (SwipeRefresh) inflater.inflate(R.layout.fragment_recycler_view, container, false);
galleryView = (RecyclerView) swipeRefresh.findViewById(R.id.recycler_view);
return swipeRefresh;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
swipeRefresh.setOnRefreshListener(this);
galleryView.setHasFixedSize(true);
galleryView.setLayoutManager(new GridLayoutManager(getContext(), getSpanCount()));
galleryView.setAdapter(adapter = new Adapter(attachments));
if (savedInstanceState == null) {
onRefresh();
} else {
onRestoreInstanceState(savedInstanceState);
}
}
#Override
public void onSaveInstanceState(Bundle outState) {
try {
outState.putString(STATE_ATTACHMENTS, Json.fromObject(attachments)); //Crashes here after 3rd or 4th rotate
} catch (JsonProcessingException e) {
Log.e(TAG, "Error while saving attachments", e);
}
super.onSaveInstanceState(outState);
}
#Override
public void onSearchPhraseChanged(String phrase) {
}
#Override
public void onRefresh() {
swipeRefresh.setRefreshing(true);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
initSampleData();
}
}, 3000);
}
private void onRestoreInstanceState(Bundle savedInstanceState) {
try {
attachments = Json.toCollection(savedInstanceState.getString(STATE_ATTACHMENTS),
ArrayList.class, Attachment.class);
adapter.notifyDataSetChanged();
} catch (IOException e) {
Log.e(TAG, "Error while restoring attachments", e);
}
}
private void initSampleData() {
swipeRefresh.setRefreshing(false);
String image = "";
File path = new File(Environment.getExternalStorageDirectory(), "image.txt");
byte[] bytes = new byte[(int) path.length()];
try {
FileInputStream fileInputStream = new FileInputStream(path);
fileInputStream.read(bytes);
image = new String(bytes);
} catch (FileNotFoundException e) {
Log.e(TAG, "Error while finding file to read from", e);
} catch (IOException e) {
Log.e(TAG, "Error while writing from file to string", e);
}
Attachment attachment = new Attachment(image);
attachments.clear();
for (int i = 0; i < 100; i++) {
attachment.setFileName(String.valueOf(i));
attachments.add(attachment);
}
adapter.notifyDataSetChanged();
}
private int getSpanCount() {
DisplayMetrics displayMetrics = context.getResources().getDisplayMetrics();
float width = displayMetrics.widthPixels / displayMetrics.density;
float height = displayMetrics.heightPixels / displayMetrics.density;
int size;
if (Math.min(width, height) >= 600) {
size = Math.round(width / THUMBNAIL_SIZE_TABLET);
} else {
size = Math.round(width / THUMBNAIL_SIZE_PHONE);
}
return size < 7 ? size : 6;
}
private class ViewHolder extends BaseHolder<Attachment> implements View.OnClickListener {
private ImageView imageView;
public ViewHolder(ViewGroup viewGroup, int layoutRes) {
super(viewGroup, layoutRes);
imageView = (ImageView) itemView;
}
#Override
public void bind(Attachment attachment) {
itemView.setOnClickListener(this);
if (attachment.getImage() != null && !attachment.getImage().isEmpty()) {
DisplayThumbnailRequest.loadBitmap(attachment, imageView);
}
}
#Override
public void onClick(View v) {
// TODO: 2016-01-15 Open image in fullscreen
}
}
private class Adapter extends RecyclerView.Adapter<ViewHolder> {
private List<Attachment> attachments;
public Adapter(List<Attachment> attachments) {
this.attachments = attachments;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
return new ViewHolder(parent, R.layout.adapter_item_attachment_history);
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
holder.bind(attachments.get(position));
}
#Override
public int getItemCount() {
return attachments.size();
}
}
AsyncTask
public class DisplayThumbnailRequest extends AsyncHttpTask<Attachment, Void, Bitmap> {
private static final String TAG = DisplayThumbnailRequest.class.getSimpleName();
private WeakReference<ImageView> imageViewRef;
private Attachment attachment;
public DisplayThumbnailRequest(ImageView imageView) {
this.imageViewRef = new WeakReference<>(imageView);
}
#Override
protected void onPreExecute() {
if (imageViewRef != null) {
ImageView imageView = imageViewRef.get();
if (imageView != null) {
if (imageView.getVisibility() != View.VISIBLE) {
imageView.setVisibility(View.VISIBLE);
}
imageView.setImageResource(R.mipmap.ic_launcher);
}
}
}
#Override
protected Bitmap doInBackground(Attachment... params) {
attachment = params[0];
Bitmap bitmap = BitmapCache.getBitmap(attachment.getFileName());
if (bitmap == null) {
bitmap = BitmapUtils.fromBase64(attachment.getImage());
BitmapCache.addBitmap(attachment.getFileName(), bitmap);
}
return bitmap;
}
#Override
protected void onPostExecute(Bitmap bitmap) {
if (imageViewRef != null && bitmap != null) {
ImageView imageView = imageViewRef.get();
if (imageView != null) {
imageView.setImageBitmap(bitmap);
}
}
}
#Override
protected void onResponseReceived() {
}
public Attachment getAttachment() {
return attachment;
}
public static void loadBitmap(Attachment attachment, ImageView imageView) {
if (cancelDownloadRequest(attachment, imageView)) {
DisplayThumbnailRequest request = new DisplayThumbnailRequest(imageView);
AsyncBitmapDrawable drawable = new AsyncBitmapDrawable(App.getRes(), null, request);
imageView.setImageDrawable(drawable);
request.execute(attachment);
}
}
private static boolean cancelDownloadRequest(Attachment attachment, ImageView imageView) {
DisplayThumbnailRequest request = getDownloadTask(imageView);
if (request != null) {
String filePath = request.getAttachment().getFileName();
if (filePath == null || filePath.isEmpty() || !filePath.equals(attachment.getFileName())) {
request.cancel(true);
} else {
return false;
}
}
return true;
}
private static DisplayThumbnailRequest getDownloadTask(ImageView imageView) {
if (imageView != null) {
Drawable drawable = imageView.getDrawable();
if (drawable instanceof AsyncBitmapDrawable) {
return ((AsyncBitmapDrawable) drawable).getDisplayThumbnailRequest();
}
}
return null;
}
}
BitmapCache
public class BitmapCache {
private static final String TAG = BitmapCache.class.getSimpleName();
private static final int MAX_MEMORY = (int)((Runtime.getRuntime().maxMemory() / 1024) / 4);
private static LruCache<String, Bitmap> lruCache = new LruCache<String, Bitmap>(MAX_MEMORY) {
#Override
protected int sizeOf(String key, Bitmap value) {
return value.getByteCount() / 1024;
}
};
public static void addBitmap(String key, Bitmap bitmap) {
if (getBitmap(key) == null) {
lruCache.put(key, bitmap);
}
}
public static Bitmap getBitmap(String key) {
return lruCache.get(key);
}
}
BitmapUtils.fromBase64
public static Bitmap fromBase64(String string) {
if (string != null && !string.isEmpty()) {
byte[] decodedString = Base64.decode(string, Base64.DEFAULT);
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length, options);
options.inSampleSize = getInSampleSize(options, Metrics.dp2px(100), Metrics.dp2px(100));
options.inJustDecodeBounds = false;
return BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length, options);
}
return null;
}
EDIT
I tried reducing arraylist size which is saved in onSavedInstanceState from 100 to 50 and OOM error is not being displayed (despite how many times you rotate the device). Can it be, that saved instance is too long (if it list has 100 items) and it floods the memory?
The problem is located in your
onRefresh() method.
Your should remove all calbacks from handler if activity is beeing stopped.
Try this:
private Handler handler = new Handler();
#Override
public void onRefresh() {
swipeRefresh.setRefreshing(true);
handler.postDelayed(new Runnable() {
#Override
public void run() {
initSampleData();
}
}, 3000);
}
#Override
protected void onStop() {
super.onStop();
handler.removeCallbacksAndMessages(null);
}

PullToRefreshAttacher.OnRefreshListener cannot be resolved to a type

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.

Categories

Resources