Я хочу обновить вкладку fragment
, но как мне это сделать?
Я пытался обновить, воссоздать, но это не работает.В промежутке это не освежает, и это только падает.Как обновить с интервалом?
Активность вкладок
public class TabActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener{
private SectionsPagerAdapter mSectionsPagerAdapter;
/**
* The {@link ViewPager} that will host the section contents.
*/
private ViewPager mViewPager;
RecyclerView recyclerView;
View rootView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
// Create the adapter that will return a fragment for each of the three
// primary sections of the activity.
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.container);
mViewPager.setAdapter(mSectionsPagerAdapter);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
mViewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
tabLayout.addOnTabSelectedListener(new TabLayout.ViewPagerOnTabSelectedListener(mViewPager));
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
getSupportActionBar().setTitle("Trolley Count");
}
@Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
@SuppressWarnings("StatementWithEmptyBody")
@Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.trolleycount) {
startActivity(new Intent(getApplicationContext(),TabActivity.class));
} else if (id == R.id.alerts) {
startActivity(new Intent(getApplicationContext(),alert.class));
} else if (id == R.id.logout) {
startActivity(new Intent(getApplicationContext(),MainActivity.class));
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
private static final String ARG_SECTION_NUMBER = "section_number";
public PlaceholderFragment() {
}
/**
* Returns a new instance of this fragment for the given section
* number.
*/
public static PlaceholderFragment newInstance(int sectionNumber) {
PlaceholderFragment fragment = new PlaceholderFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_tab, container, false);
return rootView;
}
}
/**
* A {@link FragmentPagerAdapter} that returns a fragment corresponding to
* one of the sections/tabs/pages.
*/
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int position) {
// getItem is called to instantiate the fragment for the given page.
// Return a PlaceholderFragment (defined as a static inner class below).
switch (position) {
case 0:
mSectionsPagerAdapter.notifyDataSetChanged();
return new tab1allterminal();
case 1:
return new tab2t1();
case 2:
return new tab3t2();
case 3:
return new tab4t3();
default:
return null;
}
}
@Override
public int getCount() {
// Show 3 total pages.
return 4;
}
@Override
public int getItemPosition(Object object) {
return POSITION_NONE;
}
}
}
Фрагмент вкладки 1
public class tab1allterminal extends Fragment implements Paginate.Callbacks {
public AdapterAdapter adapter;
public List<ListDataProvider> list;
public ListDataProvider listDataProvider;
RecyclerView recyclerView;
View rootView;
private boolean loading = false;
private int page = -1;
private Handler handler;
private Paginate paginate;
public int total_page=1;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
rootView = inflater.inflate(R.layout.fragment_tab1allterminal,container,false);
recyclerView=rootView.findViewById(R.id.recycler_view);
//Date currentTime = Calendar.getInstance().getTime();
handler = new Handler();
list = new ArrayList<>();
adapter = new AdapterAdapter(getActivity(), list);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false));
recyclerView.addItemDecoration(new GridSpacingItemDecoration(1, dpToPx(10), true));
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.setAdapter(adapter);
page = -1;
total_page=1;
setupPagination();
return rootView;
}
@Override
public void onLoadMore() {
Log.d("Paginate", "onLoadMore");
loading = true;
// Fake asynchronous loading that will generate page of random data after some delay
handler.postDelayed(fakeCallback, 1000);
}
@Override
public boolean isLoading() {
return loading;
}
@Override
public boolean hasLoadedAllItems() {
return page == total_page; // If all pages are loaded return true
}
private Runnable fakeCallback = new Runnable() {
@Override
public void run() {
page++;
getHostelsHttp();
loading = false;
}
};
protected void setupPagination() {
// If RecyclerView was recently bound, unbind
if (paginate != null) {
paginate.unbind();
}
loading = false;
paginate = Paginate.with(recyclerView, this)
.setLoadingTriggerThreshold(2)
.addLoadingListItem(true)
.setLoadingListItemCreator(new CustomLoadingListItemCreator())
.build();
}
private class CustomLoadingListItemCreator implements LoadingListItemCreator {
@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
View view = inflater.inflate(R.layout.cusom_loading, parent, false);
return new VH(view);
}
@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
VH vh = (VH) holder;
vh.tvLoading.setText(String.format("Total items loaded: %d.\nLoading more...", adapter.getItemCount()));
// This is how you can make full span if you are using StaggeredGridLayoutManager
if (recyclerView.getLayoutManager() instanceof StaggeredGridLayoutManager) {
StaggeredGridLayoutManager.LayoutParams params = (StaggeredGridLayoutManager.LayoutParams) vh.itemView.getLayoutParams();
params.setFullSpan(true);
}
}
}
static class VH extends RecyclerView.ViewHolder {
TextView tvLoading;
public VH(View itemView) {
super(itemView);
tvLoading = (TextView) itemView.findViewById(R.id.tv_loading_text);
}
}
/**
* RecyclerView item decoration - give equal margin around grid item
*/
public class GridSpacingItemDecoration extends RecyclerView.ItemDecoration {
private int spanCount;
private int spacing;
private boolean includeEdge;
public GridSpacingItemDecoration(int spanCount, int spacing, boolean includeEdge) {
this.spanCount = spanCount;
this.spacing = spacing;
this.includeEdge = includeEdge;
}
@Override
public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
int position = parent.getChildAdapterPosition(view); // item position
int column = position % spanCount; // item column
if (includeEdge) {
outRect.left = spacing - column * spacing / spanCount; // spacing - column * ((1f / spanCount) * spacing)
outRect.right = (column + 1) * spacing / spanCount; // (column + 1) * ((1f / spanCount) * spacing)
if (position < spanCount) { // top edge
outRect.top = spacing;
}
outRect.bottom = spacing; // item bottom
} else {
outRect.left = column * spacing / spanCount; // column * ((1f / spanCount) * spacing)
outRect.right = spacing - (column + 1) * spacing / spanCount; // spacing - (column + 1) * ((1f / spanCount) * spacing)
if (position >= spanCount) {
outRect.top = spacing; // item top
}
}
}
}
/**
* Converting dp to pixel
*/
private int dpToPx(int dp) {
Resources r = getResources();
return Math.round(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, r.getDisplayMetrics()));
}
private void getHostelsHttp() {
RequestQueue queue = Volley.newRequestQueue(getActivity());
Log.i("mytag", "start time: .");
StringRequest myReq = new StringRequest(Request.Method.POST,
Constants.URL_GET_DATA, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
try {
Log.e("tag", "response " + response);
JSONObject obj = new JSONObject(response);
JSONObject jsonObject = obj.getJSONObject("data");
JSONArray reqArr1 = jsonObject.getJSONArray("results");
Log.e("myTag","total_page: "+ jsonObject.getInt("total_page"));
total_page=jsonObject.getInt("total_page");
Log.e("myTag", "try block");
JSONObject resultsObj = null;
for (int i = 0; i < reqArr1.length() - 1; i++) {
Log.e("myTag", "for block");
resultsObj=reqArr1.getJSONObject(i);
Log.e("myTag", resultsObj.getString("dock_id"));
listDataProvider=new ListDataProvider(resultsObj.getString("dock_id"),
resultsObj.getString("dock_name"),resultsObj.getString("trolley_count"),
resultsObj.getString("flight_arrival"));
list.add(listDataProvider);
adapter.notifyDataSetChanged();
}
}
catch (JSONException e) {
}
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.i("myTag", error.toString());
}
}) {
@Override
protected Map<String, String> getParams() {
// Posting params to register url
Map<String, String> params = new HashMap<String, String>();
params.put("type", "all");
params.put("current_page", String.valueOf(page));
Log.e("myTag","Current page: "+page);
return params;
}
};
myReq.setRetryPolicy(new DefaultRetryPolicy(
20000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT
));
myReq.setShouldCache(false);
queue.add(myReq);
}
public void refresh(int milliseconds){
final Handler handler = new Handler();
final Runnable runnable = new Runnable() {
@Override
public void run() {
}
};
handler.postDelayed(runnable,milliseconds);
}
@Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
if (isVisibleToUser) {
// Refresh your fragment here
getFragmentManager().beginTransaction().detach(this).attach(this).commit();
Log.i("IsRefresh", "Yes");
}
}
}
Iхотите, чтобы вкладка fragment
обновлялась новым значением из mysql
через каждый интервал.