Content not updating on changing tabs in viewpager - Tablayout - android

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

you can try this
#Override
public void onTabSelected(TabLayout.Tab tab) {
CharSequence numTab = tab.getTag().toString();
SharedPreferences preferences2 = getSharedPreferences("AUTHENTICATION_FILE_NAME2", Context.MODE_WORLD_WRITEABLE);
SharedPreferences.Editor editor2 = preferences2.edit();
editor2.putString("tabselected",numTab.toString());
editor2.putString("Authentication_Status", "true");
editor2.apply();
// super called last
super.onTabSelected(tab);
}
or store ViewPagerAdapter adapter "globally" on top of ScrollableTabsActivity (not only inside setupViewPager method)
ViewPagerAdapter adapter;
private void setupViewPager(ViewPager viewPager) {
adapter = new ViewPagerAdapter(getSupportFragmentManager());
//rest of your code
}
and then
#Override
public void onTabSelected(TabLayout.Tab tab) {
// your current code
adapter.notifyDataSetChanged(); //ViewPagerAdapter's adapter
}

There might be several Solution to this issue i.e.
1.) Load all your data at once if you have less data and less tabs and also you can increase
viewPager.setOffscreenPageLimit(noOfTabs);
2.) Update your fragment once it is visible to the user.
#Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
if (isVisibleToUser){
// load data
}
}
Hope that will be helpful.

Related

Dynamic update of a view (viewpager) for news application

I can not implement a data update of a Viewpager based fragment.
In fact I have a service that verifies and retrieves the latest information updates published online and comes to feed my database.
Once the job is finished I should update the screen but that's where I'm stuck.
I tried many techniques but until then I have not yet received to update the screen.
I am so overwhelmed by the subject that I do not have the right words.
Thanks for your help
My main activity
public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener{
private static final String TAG = "MainActivity";
ViewPager viewPager;
TabLayout tabLayout;
DrawerLayout drawer;
NavigationView navigationView;
ActionBarDrawerToggle toggle;
Context mContext;
PagerAdapter vAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
mContext = this;
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
viewPager = (ViewPager) findViewById(R.id.viewpager);
setupViewPager(viewPager);
tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
reloadData();
}
private void setupViewPager(ViewPager viewPager) {
vAdapter = new PagerAdapter(getSupportFragmentManager());
vAdapter.addFragment(new StartFragment(), "START");
vAdapter.addFragment(new MapFragment(), "MAP");
vAdapter.addFragment(new ListArticle(), "ARTICLES");
viewPager.setAdapter(vAdapter);
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
int id = item.getItemId();
switch (id) {
case R.id.nav_profile:
startActivity(new Intent(mContext, ProfileActivity.class));
break;
case R.id.nav_map:
startActivity(new Intent(mContext, MapActivity.class));
break;
case R.id.nav_history:
startActivity(new Intent(mContext, HistoryActivity.class));
break;
case R.id.nav_help:
break;
default:
return false;
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
private void scheduleJobMatchDataUpdate(){
JobScheduler jobScheduler = (JobScheduler)getApplicationContext()
.getSystemService(JOB_SCHEDULER_SERVICE);
ComponentName componentName = new ComponentName(this,
MatchUpdatedJob.class);
JobInfo jobInfo = null;
//if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
jobInfo = new JobInfo.Builder(1, componentName)
.setPeriodic(60000).setRequiredNetworkType(
JobInfo.NETWORK_TYPE_NOT_ROAMING)
.setPersisted(true).build();
// }
jobScheduler.schedule(jobInfo);
}
public void reloadData() {
scheduleJobMatchDataUpdate();
StartFragment fragment = new StartFragment();
if (fragment.isInLayout()) {
fragment.data();
}
}
}
//My PagerAdapter
public class PagerAdapter extends FragmentStatePagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
public PagerAdapter(FragmentManager manager) {
super(manager);
}
#Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
#Override
public int getItemPosition(Object object) {
return POSITION_NONE;
}
#Override
public int getCount() {
return mFragmentList.size();
}
public void addFragment(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
}
public class StartFragment extends Fragment implements ArticleAdapter.ClickCB,
BaseSliderView.OnSliderClickListener, ViewPagerEx.OnPageChangeListener{
static final String TAG = "StartFragment";
public StartFragment() {
// Let empty
}
LinearLayoutManager mLayoutManager;
private SwipeRefreshLayout srl;
ArticleAdapter mAdapter;
Context mContext;
List<Article> mList;
List<Article> mListSelected = new ArrayList<>();
Call<List<Article>> call;
ApiService service;
RecyclerView rcv;
Bundle bundle;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.mContext = getActivity();
this.mList = Article.findAll(this.mContext);
this.bundle = savedInstanceState;
service = RetrofitBuilder.createService(ApiService.class);
setHasOptionsMenu(true);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_start, container, false);
SliderLayout mSlider = (SliderLayout) view.findViewById(R.id.slider);
String[] imgUrl = new String[3];
imgUrl[0] = "http://...1.jpg";
imgUrl[1] = "http://...2.jpg";
imgUrl[2] = "http://...3.jpg";
for (String s: imgUrl){
MatchSliderView sliderView = new MatchSliderView(getContext());
sliderView
.image(s)
.description("...")
.setScaleType(BaseSliderView.ScaleType.Fit)
.setOnSliderClickListener(this);
sliderView.bundle(new Bundle());
sliderView.getBundle()
.putString("extra",s);
mSlider.addSlider(sliderView);
}
mSlider.setPresetTransformer(SliderLayout.Transformer.Accordion);
// mSlider.setPresetIndicator(SliderLayout.PresetIndicators.Center_Bottom);
mSlider.setCustomAnimation(new DescriptionAnimation());
mSlider.setDuration(5000);
mSlider.addOnPageChangeListener(this);
rcv = (RecyclerView) view.findViewById(R.id.rcv);
mLayoutManager = new LinearLayoutManager(MainApplication.getContext());
mLayoutManager.setOrientation(1);
rcv.setLayoutManager(mLayoutManager);
rcv.setHasFixedSize(true);
//mList = Article.findAll(this.mContext);
this.mAdapter = new ArticleAdapter(this.mContext,
StartFragment.this, mList, mListSelected);
rcv.setItemViewCacheSize(mList.size());
rcv.setAdapter(this.mAdapter);
Flubber.with()
.animation(Flubber.AnimationPreset.FADE_IN_UP)
.repeatCount(1)
.duration(2000)
.createFor(rcv)
.start();
srl = (SwipeRefreshLayout)view.findViewById(R.id.swipeRefreshLayout);
srl.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
onItemsLoadComplete();
}
});
return view;
}
void onItemsLoadComplete() {
loadData();
srl.setRefreshing(false);
}
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
}
#Override
public void onPageScrollStateChanged(int state) {
}
#Override
public void onSliderClick(BaseSliderView slider) {
Toast.makeText(mContext, slider.getmTitle(),
Toast.LENGTH_SHORT).show();
}
#Override
public void removeNotify(Selection selection) {
badgeView.decrement();
}
public void loadData(){
try{
call = service.matchs();
call.enqueue(new Callback<List<Article>>() {
#Override
public void onResponse(Call<List<Article>> call, Response<List<Article>> response) {
if(response.isSuccessful()){
Article.deleteAll(mContext);
Article.saveAll(mContext,response.body());
}else{
Toast.makeText(mContext, "Update failed!", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onFailure(Call<List<Article>> call, Throwable t) {
call.isCanceled();
t.printStackTrace();
}
});
}catch (Exception e){
e.printStackTrace();
Toast.makeText(mContext, e.getMessage(), Toast.LENGTH_SHORT).show();
}
}
public void refreshData(){
mList.clear();
mList.addAll(Article.findAll(this.mContext));
mAdapter.swap((ArrayList<Article>)mList);
}
#Override
public void onPause() {
super.onPause();
if (srl!=null) {
srl.setRefreshing(false);
srl.destroyDrawingCache();
srl.clearAnimation();
}
}
}
public class ArticleAdapter extends RecyclerView.Adapter<ArticleAdapter.ViewHolder> implements Filterable {
private Context mContext;
private static final String LOG_TAG = ArticleAdapter.class.getSimpleName();
List<Article> mListArticles = new ArrayList<>();
private List<Article> articleList;
private List<Article> articleListFiltered;
private ArticlesAdapterListener listener;
public ArticleAdapter(Context context, List<Article> mListItems){
this.mContext = context;
//this.mListArticles = mListItems;
if (mListArticles != null) {
mListArticles.clear();
mListArticles.addAll(mListItems);
}
else {
this.mListArticles = mListItems;
}
notifyDataSetChanged();
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_article, parent, false);
return new ViewHolder(mContext, mListArticles, view);
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
Article item = mListArticles.get(position);
holder.title.setText(Html.fromHtml( " " + item.getTitre()));
//Glide.with(this).load(item.getMedia()).into((ImageView) findViewById(R.id.media));
if(item.getMedia() != null && item.getMedia().length() >10) {
Picasso.with(mContext).load(item.getMedia()).into(holder.img);
}
}
#Override
public int getItemCount() {
return mListArticles.size();
}
#Override
public Filter getFilter() {
return new Filter() {
#Override
protected FilterResults performFiltering(CharSequence charSequence) {
String charString = charSequence.toString();
if (charString.isEmpty()) {
articleListFiltered = articleList;
} else {
List<Article> filteredList = new ArrayList<>();
for (Article row : articleList) {
// name match condition. this might differ depending on your requirement
// here we are looking for name or phone number match
if (row.getTitre().toLowerCase().contains(charString.toLowerCase())) {
filteredList.add(row);
}
}
articleListFiltered = filteredList;
}
FilterResults filterResults = new FilterResults();
filterResults.values = articleListFiltered;
return filterResults;
}
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
articleListFiltered = (ArrayList<Article>) results.values;
notifyDataSetChanged();
}
};
}
public static class ViewHolder extends RecyclerView.ViewHolder{
private Context mContext;
private List<Article> mItems;
public TextView title;
public ImageView img;
public ViewHolder(Context context, List<Article> newsList, View view){
super(view);
this.mContext = context;
this.mItems = newsList;
this.title= (TextView)view.findViewById(R.id.title);
this.img= (ImageView) view.findViewById(R.id.media);
view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(mContext, ArticleDetailActivity.class);
intent.putExtra("id", mItems.get(getAdapterPosition()).getId());
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
mContext.startActivity(intent);
}
});
}
}
public interface ArticlesAdapterListener {
void onArticleSelected(Article article);
}
}
public class PagerAdapter extends FragmentStatePagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
public PagerAdapter(FragmentManager manager) {
super(manager);
}
#Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
#Override
public int getItemPosition(Object object) {
return POSITION_NONE;
}
#Override
public int getCount() {
return mFragmentList.size();
}
public void addFragment(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
}
mAdapter.swap((ArrayList<Article>)mList);
mAdapter.notifyDataSetChanged();

Data is not fetching when swap the tab

I have implemented one app where I have 7 tabs and I used addOnScrollListener to fetch the data when user will scroll the list. My issue is when I move one fragment or tab to another fragment and then come back on the privious tab, the data is not coming on second time on that tab.
Below is my fragment class
public class EI_Pending_Fragment extends Fragment{
SessionManager session;
private List<SuperHero> listSuperHeroes;
private RecyclerView recyclerView;
private RecyclerView.LayoutManager layoutManager;
private RecyclerView.Adapter adapter;
public ProgressBar progressBar;
private RequestQueue requestQueue;
private int requestCount1 = 1;
private Boolean isStarted = false;
private Boolean isVisible = false;
public String email;
public EI_Pending_Fragment() {}
#Override
public void onStart() {
super.onStart();
isStarted = true;
if (isVisible && isStarted){
getData();
}
}
#Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
isVisible = isVisibleToUser;
if (isStarted && isVisible) {
getData();
}
}
#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.activity_main_test, container, false);
session = new SessionManager(getActivity());
// get user data from session
HashMap<String, String> user = session.getUserDetails();
email = user.get(SessionManager.KEY_EMAIL);
return view;
}
public void onViewCreated(View v, Bundle savedInstanceState) {
super.onViewCreated(v, savedInstanceState);
recyclerView = (RecyclerView) v.findViewById(R.id.recyclerView);
recyclerView.setHasFixedSize(true);
layoutManager = new LinearLayoutManager(getContext());
recyclerView.setLayoutManager(layoutManager);
listSuperHeroes = new ArrayList<>();
requestQueue = Volley.newRequestQueue(getContext());
// getData();
adapter = new CardAdapter(listSuperHeroes, getActivity());
recyclerView.setAdapter(adapter);
progressBar = (ProgressBar) v.findViewById(R.id.progressBar1);
recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
#Override
public void onScrollStateChanged(RecyclerView recyclerView, int
newState) {
super.onScrollStateChanged(recyclerView, newState);
if (isLastItemDisplaying(recyclerView)) {
if(requestCount1==1){
exit();
}
else {
getData();
}
}
}
});
}
private JsonArrayRequest getDataFromServer(int requestCount) {
Log.e("email",email);
final String DATA_URL = "http://192.168.2.110/xp/ei_pending_received.php?matri_id="+email+"&page=";
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(DATA_URL + String.valueOf(requestCount),
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.e("response",response.toString());
if(response.length()==0){
requestCount1 = 1;
}
else {
parseData(response);
progressBar.setVisibility(View.GONE);
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
progressBar.setVisibility(View.GONE);
Toast.makeText(getActivity(), "No More Items Available", Toast.LENGTH_SHORT).show();
}
});
return jsonArrayRequest;
}
private void getData() {
requestQueue.add(getDataFromServer(requestCount1));
requestCount1++;
}
private void parseData(JSONArray array) {
for (int i = 0; i < array.length(); i++) {
//Log.e("array",array.toString().trim());
SuperHero superHero = new SuperHero();
JSONObject json = null;
try {
json = array.getJSONObject(i);
superHero.setImageUrl(json.getString(Config_Test.TAG_IMAGE_URL));
superHero.setMglId(json.getString(Config_Test.TAG_MGLID));
superHero.setAge(json.getString(Config_Test.TAG_AGE));
superHero.setAgeHeight(json.getString(Config_Test.TAG_HEIGHT));
superHero.setCommunity(json.getString(Config_Test.TAG_COMMUNITY));
superHero.setCaste(json.getString(Config_Test.TAG_CASTE));
superHero.setOccupation(json.getString(Config_Test.TAG_OCCUPATION));
superHero.setIncome(json.getString(Config_Test.TAG_INCOME));
superHero.setStatus(json.getString(Config_Test.TAG_STATUS));
superHero.setRequested_On(json.getString(Config_Test.TAG_REQUESTED_ON));
} catch (JSONException e) {
e.printStackTrace();
}
listSuperHeroes.add(superHero);
}
adapter.notifyDataSetChanged();
}
private boolean isLastItemDisplaying(RecyclerView recyclerView) {
if (recyclerView.getAdapter().getItemCount() != 0) {
int lastVisibleItemPosition = ((LinearLayoutManager) recyclerView.getLayoutManager()).findLastCompletelyVisibleItemPosition();
if (lastVisibleItemPosition != RecyclerView.NO_POSITION && lastVisibleItemPosition == recyclerView.getAdapter().getItemCount() - 1)
return true;
}
return false;
}
void exit(){
Toast.makeText(getContext(),"no more data avilable",Toast.LENGTH_SHORT).show();
}
}
Below is my Activity class where I add all the tab
private void setupViewPager(ViewPager viewPager) {
int numberOfPages=7;
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
adapter.addFragment(new NewMatches_Tab(), "New matches");
adapter.addFragment(new Broader_Match_Tab(), "Broader Matches");
adapter.addFragment(new Similar_Matchs_Tab(), "Similar Matches");
adapter.addFragment(new ShortlistTab(), "ShortListed");
adapter.addFragment(new Viewed_My_Profile(), "View My Profile");
adapter.addFragment(new ShortListedMeTab(), "ShortListed Me");
adapter.addFragment(new Photo_Request_Received(), "Photo Request Received");
//viewPager.setOffscreenPageLimit(numberOfPages);
viewPager.setAdapter(adapter);
}
You can add an OnPageChangeListener in the activity and register it to your view pager and do all necessary "setting" within the OnPageChangeListener instance.
ViewPager.OnPageChangeListener viewPagerPageChangeListener = new ViewPager.OnPageChangeListener() {
#Override
public void onPageSelected(int position) {
//Do your fragment refreshing here
mCurrentPage = position;
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
}
#Override
public void onPageScrollStateChanged(int arg0) {
}
};
#Override
public void setFragmentsForContents(List<Content> contents) { //bundle data for your different fragments
if(contents!=null){
NUM_PAGES = contents.size();
mContentPager.addOnPageChangeListener(viewPagerPageChangeListener);
mContentPager.setAdapter(mScreenSlidePagerAdapter);
mContentPager.setCurrentItem(mCurrentPage);
}
}
private class ScreenSlidePagerAdapter extends FragmentStatePagerAdapter {
ScreenSlidePagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
return ContentFragment.newInstance(mContents.get(position).getContent());
}
#Override
public int getCount() {
return NUM_PAGES;
}
#NonNull
#Override
public Object instantiateItem(ViewGroup container, int position) {
return super.instantiateItem(container, position);
}
#Override
public float getPageWidth(int position) {
return 1.0f;
}
}

Tablayout on swipe not refreshing in android

I am implementing tablayout using view pager and in my scenario I have two tab. In my first tab I have add data which store in share preference. and when I move to second tab then data should be retrieve from share preference and show in listview. When I add the data from my first tab then data is added successfully but not show in my second tab means I have to close my application and again restart the app so that I can see saved the detail which saved from my first tab.
Below is my Activity code.
public class FragmentExample extends AppCompatActivity {
private ViewPagerAdapter viewPagerAdapter;
#BindView(R.id.tabCountryState)
TabLayout tabCountryState;
#BindView(R.id.viewPager)
ViewPager viewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fragment_example);
ButterKnife.bind(this);
setViewPager();
setTabIcon();
viewPager.setOffscreenPageLimit(2);
tabCountryState.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
Log.e("Current tab is ", "===> " + tab.getPosition());
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
}
private void setViewPager() {
// set Adaapter.
viewPagerAdapter = new ViewPagerAdapter(getSupportFragmentManager(), FragmentExample.this);
viewPager.setAdapter(viewPagerAdapter);
tabCountryState.setupWithViewPager(viewPager);
}
// set custom icon to tab in Tablayout.
private void setTabIcon() {
// First Tab
View firstTab = (View) LayoutInflater.from(this).inflate(R.layout.tab_icon_first, null);
TextView tvFirsIcon = ButterKnife.findById(firstTab, R.id.tvFirsIcon);
tvFirsIcon.setText("First Tab");
tabCountryState.getTabAt(0).setCustomView(firstTab);
// First Tab
View secondTab = (View) LayoutInflater.from(this).inflate(R.layout.tab_icon_second, null);
TextView tvSecondIcon = ButterKnife.findById(secondTab, R.id.tvSecondIcon);
tvSecondIcon.setText("Second Tab");
tabCountryState.getTabAt(1).setCustomView(secondTab);
}
public class ViewPagerAdapter extends FragmentStatePagerAdapter {
private Context context;
private FirstFragment firstFragment;
private SecondFragment secondFragment;
public ViewPagerAdapter(FragmentManager fm, Context mainActivity) {
super(fm);
context = mainActivity;
new FirstFragment();
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
firstFragment = new FirstFragment();
return firstFragment;
case 1:
secondFragment = new SecondFragment();
return secondFragment;
default:
return null;
}
}
#Override
public int getCount() {
return 2;
}
#Override
public CharSequence getPageTitle(int position) {
return " " + position;
}
}
}
Here is my FirstFragment in which I have added the data into share preference.
public class FirstFragment extends Fragment {
private View v;
#BindView(R.id.btnSubmit)
Button btnSubmit;
#BindView(R.id.edtCityName)
EditText edtCityName;
#BindView(R.id.spStateName)
Spinner spStateName;
private Unbinder unbinder;
private ArrayList<String> alStateName;
private ArrayList<AllStateCityModel> alAllStateCity;
private SpinnerStateAdapter spinnerAdapter;
private int spinnerPosition;
private String strCityName, strSpinnerValue;
#OnClick(R.id.btnSubmit)
public void submit(View view) {
if (spinnerPosition !=0) {
strCityName = edtCityName.getText().toString().trim();
alAllStateCity = SessinoManager.getCityList(getActivity());
if (strCityName.length() > 0) {
alAllStateCity.get(spinnerPosition).getAlCityName().add(new CityStateModel(strCityName));
} else {
}
// Save new data to Session.
SessinoManager.saveCityList(getActivity(), alAllStateCity);
SecondFragment.cityAdapter.notifyDataSetChanged();
Toast.makeText(getActivity(), "Detail saved successfully ", Toast.LENGTH_SHORT).show();
edtCityName.setText("");
} else {
Toast.makeText(getActivity(), "Please select state", Toast.LENGTH_SHORT).show();
}
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
Bundle args = getArguments();
v = inflater.inflate(R.layout.fragment_first, container, false);
unbinder = ButterKnife.bind(this, v);
// arraylist checking if data is available into session.
if(SessinoManager.getCityList(getActivity()).size()>0){
Log.e("First fragment "," if condition ");
alAllStateCity = SessinoManager.getCityList(getActivity());
alStateName = new ArrayList<>();
for(int i=0;i<alAllStateCity.size();i++){
alStateName.add(alAllStateCity.get(i).getStrStateName());
}
setStateSpinner();
}else{
loadArraylist();
setStateSpinner();
}
return v;
}
private void setStateSpinner() {
spStateName.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
spinnerPosition = i;
spinnerAdapter.notifyDataSetChanged();
strSpinnerValue = alStateName.get(i).toString().trim();
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
spinnerAdapter = new SpinnerStateAdapter(getActivity(), alStateName);
spStateName.setAdapter(spinnerAdapter);
}
private void loadArraylist() {
alAllStateCity = new ArrayList<>();
alStateName = new ArrayList<>();
alStateName.add(0, "Select State");
alStateName.add("Gujarat");
alStateName.add("Maharashtra");
alStateName.add("Madhya Pradesh");
for (int i = 0; i < alStateName.size(); i++) {
alAllStateCity.add(new AllStateCityModel(alStateName.get(i), alAllStateCity.size(), new ArrayList<CityStateModel>()));
}
SessinoManager.saveCityList(getActivity(), alAllStateCity);
}
#Override public void onDestroyView() {
super.onDestroyView();
unbinder.unbind();
Log.e("First fragment "," on destroy");
}
}
Here is my SecondFragment in which I have to get saved detail from Share preference.
public class SecondFragment extends Fragment {
private View v;
private Unbinder unbinder;
#BindView(R.id.lvCityList)
ListView lvCityList;
#BindView(R.id.spinnerStateName)
Spinner spinnerStateName;
private ArrayList<AllStateCityModel> alAllStateCity;
private ArrayList<CityStateModel> alCityName;
private ArrayList<String> alStateName;
private int spinnerPosition;
private SpinnerStateAdapter spinnerAdapter;
private ArrayList<String> alCity;
public static CityAdapter cityAdapter;
private Context context;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
Bundle args = getArguments();
v = inflater.inflate(R.layout.fragment_two, container, false);
unbinder = ButterKnife.bind(this, v);
context = getActivity();
loadArrayList(context);
Log.e("onCreateView", "onCreateView");
return v;
}
private void loadArrayList(Context context) {
alCityName = new ArrayList<>();
alStateName = new ArrayList<>();
alAllStateCity = SessinoManager.getCityList(context);
for (int j = 0; j < alAllStateCity.size(); j++) {
// Log.e("State name "," =========================> "+allPlayList.get(j).getStrStateName());
// get state name from session
alStateName.add(alAllStateCity.get(j).getStrStateName());
setSpinner(context);
}
}
private void setSpinner(Context context) {
spinnerAdapter = new SpinnerStateAdapter(context, alStateName);
spinnerStateName.setAdapter(spinnerAdapter);
spinnerStateName.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
spinnerPosition = i;
spinnerAdapter.notifyDataSetChanged();
setList(spinnerPosition);
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
}
private void setList(int position) {
alCityName = alAllStateCity.get(position).getAlCityName();
alCity = new ArrayList<>();
for (int i = 0; i < alCityName.size(); i++) {
// Log.e("City name "," !!!!!!!!!!!!!!!!"+alCityName.get(i).getStrCity());
alCity.add(alCityName.get(i).getStrCity());
}
cityAdapter = new CityAdapter(context, alCity);
lvCityList.setAdapter(cityAdapter);
cityAdapter.notifyDataSetChanged();
}
}
And I am saving data into Share preference which is given below.
public class SessinoManager {
private static final String CITY_PREFERENCE = "city_preference";
// Save data to share preference.
public static void saveCityList(Context context, ArrayList<AllStateCityModel> alAllPlayList) {
try {
SharedPreferences settings;
SharedPreferences.Editor editor;
settings = context.getSharedPreferences(CITY_PREFERENCE,Context.MODE_PRIVATE);
editor = settings.edit();
Gson gson = new Gson();
String jsonUsers = gson.toJson(alAllPlayList);
editor.putString("all_play_list", jsonUsers);
editor.commit();
// Check to save data into share preferent
for(int j=0;j<alAllPlayList.size();j++){
Log.e("State name ","----------------------"+alAllPlayList.get(j).getStrStateName());
ArrayList<CityStateModel> cityName = alAllPlayList.get(j).getAlCityName();
for(int i=0;i<cityName.size();i++){
Log.e("cityName "," in session ==> "+cityName.get(i).getStrCity());
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
public static ArrayList<AllStateCityModel> getCityList(Context context)
{
SharedPreferences settings;
List<AllStateCityModel> users = new ArrayList<>();
settings = context.getSharedPreferences(CITY_PREFERENCE,Context.MODE_PRIVATE);
if (settings.contains("all_play_list"))
{
String jsonUsers = settings.getString("all_play_list", null);
Gson gson = new Gson();
AllStateCityModel[] userItems = gson.fromJson(jsonUsers,AllStateCityModel[].class);
users = Arrays.asList(userItems);
users= new ArrayList<AllStateCityModel>(users);
}
return (ArrayList<AllStateCityModel>) users;
}
}
When I add new city detail into first tab then data is data successfully but when I swipe or move to next then data is not displaying and I have to restart whole application to get updated data from Share preference. Kindly help me to resolve this issue. Thanks in advance.
I have resolved the problem by implementing below method setUserVisibleHint.
public class SecondFragment extends Fragment {
private View v;
private Unbinder unbinder;
#BindView(R.id.lvCityList)
ListView lvCityList;
#BindView(R.id.spinnerStateName)
Spinner spinnerStateName;
private ArrayList<AllStateCityModel> alAllStateCity;
private ArrayList<CityStateModel> alCityName;
private ArrayList<String> alStateName;
private int spinnerPosition;
private SpinnerStateAdapter spinnerAdapter;
private ArrayList<String> alCity;
public static CityAdapter cityAdapter;
private Context context;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
Bundle args = getArguments();
v = inflater.inflate(R.layout.fragment_two, container, false);
unbinder = ButterKnife.bind(this, v);
context = getActivity();
loadArrayList(context);
// Log.e("onCreateView", "onCreateView");
return v;
}
private void loadArrayList(Context context) {
alCityName = new ArrayList<>();
alStateName = new ArrayList<>();
alAllStateCity = SessinoManager.getCityList(context);
for (int j = 0; j < alAllStateCity.size(); j++) {
// Log.e("State name "," =========================> "+allPlayList.get(j).getStrStateName());
// get state name from session
alStateName.add(alAllStateCity.get(j).getStrStateName());
setSpinner(context);
}
}
#Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
Log.e("setUserVisibleHint","setUserVisibleHint "+isVisibleToUser);
if(isVisibleToUser==true){
loadArrayList(context);
}
}
#Override
public boolean getUserVisibleHint() {
Log.e("getUserVisibleHint","getUserVisibleHint "+super.getUserVisibleHint());
return super.getUserVisibleHint();
}
private void setSpinner(Context context) {
spinnerAdapter = new SpinnerStateAdapter(context, alStateName);
spinnerStateName.setAdapter(spinnerAdapter);
spinnerStateName.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
spinnerPosition = i;
spinnerAdapter.notifyDataSetChanged();
setList(spinnerPosition);
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
}
private void setList(int position) {
alCityName = alAllStateCity.get(position).getAlCityName();
alCity = new ArrayList<>();
for (int i = 0; i < alCityName.size(); i++) {
// Log.e("City name "," !!!!!!!!!!!!!!!!"+alCityName.get(i).getStrCity());
alCity.add(alCityName.get(i).getStrCity());
}
cityAdapter = new CityAdapter(context, alCity);
lvCityList.setAdapter(cityAdapter);
cityAdapter.notifyDataSetChanged();
}
}

Different NavigationDrawer items for Different activities in android

Here i am using NavigationDrawer for my activities.It is working fine.i am using Recyclerview for displaying NavigationDrawer items. Now i want to display different NavigationDrawer Item for different Activity..Here i am using nav_drawer_labels in FragmentDrawer to display items.How to display nav_drawer_labels1 in another activity.I mean i have to display different NavigationDrawer in each activity..here is my code.
CompProfileDisplay.java
public class CompProfileDisplay extends AppCompatActivity implements OnItemClickListener, FragmentDrawer.FragmentDrawerListener {
private static String TAG = CompProfileDisplay.class.getSimpleName();
private MenuItem menuitems;
private Toolbar mToolbar;
private FragmentDrawer drawerFragment1;
private ImageView img;
private int count;
private TextView textView;
private String doc;
public static final String UPLOAD_URL = "http://website.com/aboutme_update.php";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//getActionBar().setDisplayShowTitleEnabled(false);
setContentView(R.layout.compprofile_display);
mToolbar = (Toolbar) findViewById(R.id.toolbar);
img = (ImageView) findViewById(R.id.imageView10);
setSupportActionBar(mToolbar);
getSupportActionBar().setDisplayShowHomeEnabled(true);
final Context context = this;
drawerFragment1 = (FragmentDrawer)
getSupportFragmentManager().findFragmentById(R.id.fragment_navigation_drawer);
drawerFragment1.setUp(R.id.fragment_navigation_drawer, (DrawerLayout) findViewById(R.id.drawer_layout), mToolbar);
drawerFragment1.setDrawerListener(this);
// display the second navigation drawer view on app launch
displayView(0);
SharedPreferences sharedPreferences = getSharedPreferences(ProfileLogin.SHARED_PREF_NAME, MODE_PRIVATE);
SharedPreferences sharedPreferences1 = getSharedPreferences(ClickToComp.SHARED_PREF_NAME, MODE_PRIVATE);
img.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
final Dialog dialog = new Dialog(context);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);//no title in dialog.
dialog.getWindow().setBackgroundDrawable( new ColorDrawable(android.graphics.Color.TRANSPARENT));
dialog.setContentView(R.layout.im);
Typeface font = Typeface.createFromAsset( getAssets(), "fontawesome-webfont.ttf" );
TextView txt = (TextView) dialog.findViewById(R.id.custom_fullimage_placename);
txt.setTypeface(font);
String url1 = "http://www.website.com/" + doc;
new DownloadImageTask((ImageView) dialog.findViewById(R.id.fullimage))
.execute(url1);
//on click of cancel icon/btn popup screen will close.
txt.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
dialog.dismiss();
}
});
dialog.show();
}
});
}
private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
ImageView bmImage;
public DownloadImageTask(ImageView bmImage) {
this.bmImage = bmImage;
}
protected Bitmap doInBackground(String... urls) {
String urldisplay = urls[0];
Bitmap mIcon11 = null;
try {
InputStream in = new java.net.URL(urldisplay).openStream();
mIcon11 = BitmapFactory.decodeStream(in);
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return mIcon11;
}
protected void onPostExecute(Bitmap result) {
bmImage.setImageBitmap(result);
}
}
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
Intent intent;
switch (position) {
default:
intent = new Intent(CompProfileDisplay.this, Banking.class);
startActivity(intent);
break;
}
}
#Override
public boolean onCreateOptionsMenu(final Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
MenuItem menuItem = menu.findItem(R.id.testAction);
menuItem.setIcon(buildCounterDrawable(count, R.drawable.add));
return true;
}
private Drawable buildCounterDrawable(int count, int backgroundImageId) {
LayoutInflater inflater = LayoutInflater.from(this);
View view = inflater.inflate(R.layout.action_bar_notifitcation_icon, null);
view.setBackgroundResource(backgroundImageId);
if (count == 0) {
View counterTextPanel = view.findViewById(R.id.counterValuePanel);
counterTextPanel.setVisibility(View.GONE);
} else {
textView = (TextView) view.findViewById(R.id.count);
textView.setText("" + count);
textView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(CompProfileDisplay.this, "You have new friend request", Toast.LENGTH_SHORT).show();
}
});
}
view.measure(
View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED),
View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
view.layout(0, 0, view.getMeasuredWidth(), view.getMeasuredHeight());
view.setDrawingCacheEnabled(true);
view.setDrawingCacheQuality(View.DRAWING_CACHE_QUALITY_HIGH);
Bitmap bitmap = Bitmap.createBitmap(view.getDrawingCache());
view.setDrawingCacheEnabled(false);
return new BitmapDrawable(getResources(), bitmap);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.testAction) {
if(count>0) {
Toast.makeText(getApplicationContext(), "You have new friend request", Toast.LENGTH_SHORT).show();
}
else {
Toast.makeText(getApplicationContext(), "You dont have any new notification", Toast.LENGTH_SHORT).show();
}
return true;
}
if(id == R.id.action_search){
/*Toast.makeText(getApplicationContext(), vault_no, Toast.LENGTH_SHORT).show();
return true;*/
//logout();
}
if(id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onDrawerItemSelected(View view, int position) {
displayView(position);
}
private void displayView(int position) {
Fragment fragment = null;
String title = getString(R.string.app_name);
switch (position) {
case 0:
/*fragment = new HomeFragment();*/
title = "Profile";
break;
case 1:
/*fragment = new ProfileFragment();
title = getString(R.string.title_profile);
break;*/
startActivity(new Intent(this, CompProfileDisplay.class));
return;
case 2:
startActivity(new Intent (this,DisplayContact.class));
return;
case 3:
startActivity(new Intent(this, DocUpload.class));
return;
default:
break;
}
if (fragment != null) {
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.container_body, fragment);
fragmentTransaction.commit();
// set the toolbar title
getSupportActionBar().setTitle(title);
}
}
}
FragmentDrawer.class
public class FragmentDrawer extends Fragment {
private static String TAG = FragmentDrawer.class.getSimpleName();
public static final String SHARED_PREF_NAME = "myloginapp";
private RecyclerView recyclerView;
private String doc;
private String fullname;
private String vault;
private ActionBarDrawerToggle mDrawerToggle;
private DrawerLayout mDrawerLayout;
private NavigationDrawerAdapter adapter;
private View containerView;
private static String[] titles = null;
private FragmentDrawerListener drawerListener;
public FragmentDrawer() {
}
public void setDrawerListener(FragmentDrawerListener listener) {
this.drawerListener = listener;
}
public static List<NavDrawerItem> getData() {
List<NavDrawerItem> data = new ArrayList<>();
// preparing navigation drawer items
for (int i = 0; i < titles.length; i++) {
NavDrawerItem navItem = new NavDrawerItem();
navItem.setTitle(titles[i]);
data.add(navItem);
}
return data;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// here i am displaying nav_drawer_labels items in one activity.
titles = getActivity().getResources().getStringArray(R.array.nav_drawer_labels);
//i want to display nav_drawer_labels1 in another activity.
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflating view layout
View layout = inflater.inflate(R.layout.fragment_navigation_drawer, container, false);
ImageView img = (ImageView)layout.findViewById(R.id.img);
TextView name = (TextView)layout.findViewById(R.id.name);
TextView vault_no = (TextView)layout.findViewById(R.id.vault);
SharedPreferences sharedPreferences1 = this.getActivity().getSharedPreferences(FragmentDrawer.SHARED_PREF_NAME, Context.MODE_PRIVATE);
vault = sharedPreferences1.getString(ProfileLogin.EMAIL_SHARED_PREF,"Not Available");
SharedPreferences sharedPreferences = this.getActivity().getSharedPreferences(FragmentDrawer.SHARED_PREF_NAME, Context.MODE_PRIVATE);
doc = sharedPreferences.getString(ClickToLogin.DOC_SHARED_PREF,"Not Available");
fullname = sharedPreferences.getString(ClickToLogin.FULLNAME_SHARED_PREF,"Not Available");
name.setText(fullname);
vault_no.setText(vault);
recyclerView = (RecyclerView) layout.findViewById(R.id.drawerList);
String url1 = "http://www.miisky.com/"+doc;
new DownloadImageTask((ImageView) layout.findViewById(R.id.img))
.execute(url1);
adapter = new NavigationDrawerAdapter(getActivity(), getData());
recyclerView.setAdapter(adapter);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
recyclerView.addOnItemTouchListener(new RecyclerTouchListener(getActivity(), recyclerView, new ClickListener() {
#Override
public void onClick(View view, int position) {
drawerListener.onDrawerItemSelected(view, position);
mDrawerLayout.closeDrawer(containerView);
}
#Override
public void onLongClick(View view, int position) {
}
}));
return layout;
}
private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
ImageView bmImage;
public DownloadImageTask(ImageView bmImage) {
this.bmImage = bmImage;
}
protected Bitmap doInBackground(String... urls) {
String urldisplay = urls[0];
Bitmap mIcon11 = null;
try {
InputStream in = new java.net.URL(urldisplay).openStream();
mIcon11 = BitmapFactory.decodeStream(in);
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return mIcon11;
}
protected void onPostExecute(Bitmap result) {
bmImage.setImageBitmap(result);
}
}
public void setUp(int fragmentId, DrawerLayout drawerLayout, final Toolbar toolbar) {
containerView = getActivity().findViewById(fragmentId);
mDrawerLayout = drawerLayout;
mDrawerToggle = new ActionBarDrawerToggle(getActivity(), drawerLayout, toolbar, R.string.drawer_open, R.string.drawer_close) {
#Override
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
getActivity().invalidateOptionsMenu();
}
#Override
public void onDrawerClosed(View drawerView) {
super.onDrawerClosed(drawerView);
getActivity().invalidateOptionsMenu();
}
#Override
public void onDrawerSlide(View drawerView, float slideOffset) {
super.onDrawerSlide(drawerView, slideOffset);
toolbar.setAlpha(1 - slideOffset / 2);
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
mDrawerLayout.post(new Runnable() {
#Override
public void run() {
mDrawerToggle.syncState();
}
});
}
public static interface ClickListener {
public void onClick(View view, int position);
public void onLongClick(View view, int position);
}
static class RecyclerTouchListener implements RecyclerView.OnItemTouchListener {
private GestureDetector gestureDetector;
private ClickListener clickListener;
public RecyclerTouchListener(Context context, final RecyclerView recyclerView, final ClickListener clickListener) {
this.clickListener = clickListener;
gestureDetector = new GestureDetector(context, new GestureDetector.SimpleOnGestureListener() {
#Override
public boolean onSingleTapUp(MotionEvent e) {
return true;
}
#Override
public void onLongPress(MotionEvent e) {
View child = recyclerView.findChildViewUnder(e.getX(), e.getY());
if (child != null && clickListener != null) {
clickListener.onLongClick(child, recyclerView.getChildPosition(child));
}
}
});
}
#Override
public boolean onInterceptTouchEvent(RecyclerView rv, MotionEvent e) {
View child = rv.findChildViewUnder(e.getX(), e.getY());
if (child != null && clickListener != null && gestureDetector.onTouchEvent(e)) {
clickListener.onClick(child, rv.getChildPosition(child));
}
return false;
}
#Override
public void onTouchEvent(RecyclerView rv, MotionEvent e) {
}
#Override
public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {
}
}
public interface FragmentDrawerListener {
public void onDrawerItemSelected(View view, int position);
}
}
string.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="nav_item_home1">Home</string>
<string name="nav_item_profile1">Profile</string>
<string name="nav_item_customersupport">Customer Support</string>
<string name="nav_item_dealer">Dealer Network</string>
<string-array name="nav_drawer_labels1">
<item>#string/nav_item_home1</item>
<item>#string/nav_item_profile1</item>
<item>#string/nav_item_customersupport</item>
</string-array>
<string name="nav_item_home">Home</string>
<string name="nav_item_profile">Profile</string>
<string name="nav_item_contacts">Contacts</string>
<string name="nav_item_docupload">Upload Documents</string>
<!-- navigation drawer item labels -->
<string-array name="nav_drawer_labels">
<item>#string/nav_item_home</item>
<item>#string/nav_item_profile</item>
<item>#string/nav_item_contacts</item>
</string-array>
</resources>
Navigation drawer is meant to be used with fragments.
The main activity host the the nav drawer.
Fragments make it easy to swap the drawer content a keep its state.
If you wanted to use acitvity instead then you should create a base activity conaining the drawer so that all your activities inherit from that activity.
This way the nav drawer can persist from activity to activity.

ViewPagerAdapter update fragment when starting again

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

Categories

Resources