Different Android ViewPager based on user mode - android-fragments

I'm currently stumped on how to show a different set of tabs via a ViewPager based on the user mode selected. If I don't change user mode, tabs/fragments/ViewPager behave as expected. If I change usermode (use a different adapter with the ViewPager) the correct number of tabs show up but the fragments in each tab do not update correctly. Below is code. Thanks in advance for any suggestions.
Using on Resume for all the magic. onCreate is normal Layout setup.
// -------------------------------------------------
#Override
public void onResume() {
super.onResume();
if(isActivityForResult){
return;
}
if (PreferenceManager.getDefaultSharedPreferences(getActivity()).getString("userMode", "").equalsIgnoreCase("buyer")) {
TextView title = (TextView) rootView.findViewById(R.id.mfm_main_header_title);
title.setText(R.string.buyer_main_fragment_title);
adapter = new BuyerSectionsPagerAdapter(getChildFragmentManager());
} else if (PreferenceManager.getDefaultSharedPreferences(getActivity()).getString("userMode", "").equalsIgnoreCase("seller")) {
TextView title = (TextView) rootView.findViewById(R.id.mfm_main_header_title);
title.setText(R.string.seller_main_fragment_title);
adapter = new SellerSectionsPagerAdapter(getChildFragmentManager());
}
setUpViewTabs(adapter);
setNavigationDrawer();
}
// Set up tabs for either buyer or seller perspectives
// -------------------------------------------------
public void setUpViewTabs(PagerAdapter adapter) {
// Initialize the ViewPager and set an adapter
ViewPager pager = (ViewPager) rootView.findViewById(R.id.pager);
pager.setAdapter(adapter);
// Bind the tabs to the ViewPager
PagerSlidingTabStrip tabs = (PagerSlidingTabStrip) rootView.findViewById(R.id.tabs);
tabs.setTextColor(getResources().getColor(R.color.themeCommonBGColor));
tabs.setIndicatorColor(getResources().getColor(R.color.themeYellow));
tabs.setIndicatorHeight(4);
tabs.setTabBackground(R.drawable.tab_background_statelist);
tabs.setTabPaddingLeftRight(0);
tabs.setAllCaps(true);
tabs.setShouldExpand(true);
tabs.setViewPager(pager);
}
// -------------------------------------------------
// -------------------------------------------------
public class BuyerSectionsPagerAdapter extends FragmentPagerAdapter {
public BuyerSectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
// -------------------------------------------------
#Override
public Fragment getItem(int position) {
switch (position) {
case 0: {
return BuyerMyFarmersRootFragment.newInstance();
}
case 1: {
return BuyerMyOrdersFragment.newInstance();
}
default: {
return null;
}
}
}
// -------------------------------------------------
#Override
public int getCount() {
return 2;
}
// -------------------------------------------------
#Override
public CharSequence getPageTitle(int position) {
Locale l = Locale.getDefault();
switch (position) {
case 0: {
return getString(R.string.buyer_fragment_my_farmers)
.toUpperCase(l);
}
case 1: {
return getString(R.string.buyer_fragment_my_orders)
.toUpperCase(l);
}
default: {
return null;
}
}
}
}
// -------------------------------------------------
// -------------------------------------------------
public class SellerSectionsPagerAdapter extends FragmentPagerAdapter {
// -------------------------------------------------
public SellerSectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
// -------------------------------------------------
#Override
public Fragment getItem(int position) {
switch (position) {
case 0: {
return SellerOrdersRootFragment.newInstance();
}
case 1: {
return SellerProductsRootFragment.newInstance();
}
case 2: {
return SellerCustomersRootFragment.newInstance();
}
default:
return null;
}
}
// -------------------------------------------------
#Override
public int getCount() {
return 3;
}
// -------------------------------------------------
#Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return getString(R.string.seller_fragment_title_orders);
case 1:
return getString(R.string.seller_fragment_title_products);
case 2:
return getString(R.string.seller_fragment_title_customers);
}
return null;
}
}

Related

Why my diffutils dont update my position in background

I'm using DiffUtils to update my Recyclerview.
Visually works but clicking an item returns it to me a position that does not match the item I clicked
I used NotifyDataChange that was able to solve the position problem. But visually, the last item is misconfigured.
I try to use NotifyDataChange that was able to solve the position problem. But visually, the last item is misconfigured.
My adapter:
class AdapterUser : RecyclerView.Adapter
{
//Global Var
public event EventHandler<int> ItemClick;
public List<Class.Result> ClassUser;
public Android.Content.Context context;
public class UserViewHolder : RecyclerView.ViewHolder
{
public static TextView txtName { get; set; }
public static TextView txtEspecialidade { get; set; }
public static CircleImageView Imagem { get; set; }
public static Bitmap bitmap { get; set; }
public static CircleImageView status { get; set; }
public static Button button { get; set; }
public UserViewHolder(View itemview, Action<int> listener) : base(itemview)
{
UserViewHolder.txtName = itemview.FindViewById<TextView>(Resource.Id.nameUser);
UserViewHolder.txtEspecialidade = itemview.FindViewById<TextView>(Resource.Id.speciality);
UserViewHolder.Imagem = itemview.FindViewById<CircleImageView>(Resource.Id.avatarUser);
UserViewHolder.status = itemview.FindViewById<CircleImageView>(Resource.Id.status);
UserViewHolder.button = itemview.FindViewById<Button>(Resource.Id.BtCriar);
}
}
public AdapterUser(List<Class.Result> user)
{
ClassUser = user;
}
public override int ItemCount
{
get { return ClassUser.Count(); }
}
public override void OnBindViewHolder(RecyclerView.ViewHolder holder, int position)
{
//Method to transform the uri to bitmap
async Task MyMethodAsync()
{
// Do asynchronous work.
UserViewHolder.Imagem.SetImageBitmap(await Droid.Class.Functions.GetImageBitmapFromUrlAsync(ClassUser[position].PhotoUri));
};
UserViewHolder userHolder = holder as UserViewHolder;
if (ClassUser[position].PhotoUri != null)
{
MyMethodAsync();
}
else
{
UserViewHolder.Imagem.SetImageResource(Resource.Drawable.avatar);
}
if (ClassUser[position].IsOnline != true)
{
UserViewHolder.status.Visibility = ViewStates.Invisible;
}
else
{
UserViewHolder.status.Visibility = ViewStates.Visible;
}
UserViewHolder.txtName.Text = ClassUser[position].Name;
UserViewHolder.txtEspecialidade.Text = ClassUser[position].Specialty;
UserViewHolder.button.Click += (sender, args) =>
{
Toast.MakeText(context, ClassUser[position].Name, ToastLength.Short).Show();
Console.WriteLine(ClassUser[position].Name);
};
}
public override RecyclerView.ViewHolder OnCreateViewHolder(ViewGroup parent, int viewType)
{
View itemView = LayoutInflater.From(parent.Context).Inflate(Resource.Layout.ResultUser, parent, false);
UserViewHolder vh = new UserViewHolder(itemView, OnClick);
context = parent.Context;
return vh;
}
private void OnClick(int obj)
{
}
public void Update(List<Class.Result> oldList, List<Class.Result> newList)
{
// Set detectMoves to true for smoother animations
MyDiffCallback callback = new MyDiffCallback(oldList, newList);
DiffUtil.DiffResult result = DiffUtil.CalculateDiff(callback);
this.ClassUser.Clear();
this.ClassUser.AddRange(newList);
// Despatch the updates to your RecyclerAdapter
result.DispatchUpdatesTo(this);
}
My DiffUtills:
class MyDiffCallback : DiffUtil.Callback
{
List<Class.Result> newList;
List<Class.Result> oldList;
public MyDiffCallback(List<Class.Result> oldList, List<Class.Result> newList)
{
this.oldList = oldList;
this.newList = newList;
}
public override int NewListSize => newList.Count;
public override int OldListSize => oldList.Count;
public override bool AreContentsTheSame(int oldItemPosition, int newItemPosition)
{
return oldList[oldItemPosition].IsOnline == newList[newItemPosition].IsOnline;
}
public override bool AreItemsTheSame(int oldItemPosition, int newItemPosition)
{
return oldList[oldItemPosition].RowKey == newList[newItemPosition].RowKey;
}
public override Java.Lang.Object GetChangePayload(int oldItemPosition, int newItemPosition)
{
return base.GetChangePayload(oldItemPosition, newItemPosition);
}
}
My activity:
ClassUtilizador = Data.Result.ToString();
Class.ClassUtilizador classUser = JsonConvert.DeserializeObject<Class.ClassUtilizador>(Data.Result.ToString());
//Call the function to update item
adapter.Update(classUserOld.Result, classUser.Result);
//Clean class and put the new data
classUserOld = new Class.ClassUtilizador();
classUserOld = classUser;
Update items, remove, add ou move items. Depending of my request.
You should call:
holder.bindingAdapterPosition
clicking an item returns it to me a position that does not match the
item I clicked
UserViewHolder.button.Click += (sender, args) =>
{
Toast.MakeText(context, ClassUser[position].Name, ToastLength.Short).Show();
Console.WriteLine(ClassUser[position].Name);
};
change to :
UserViewHolder.button.Tag = position;
UserViewHolder.button.SetOnClickListener(this);
then let your adapter extends View.IOnClickListener
class AdapterUser : RecyclerView.Adapter,View.IOnClickListener
public void OnClick(View v)
{
//here you could get the correct position
Toast.MakeText(context, v.Tag.ToString(), ToastLength.Short).Show();
}
if it doesn't update your Recyclerview, you could add the method in your adapter:
public void setData(List<Class.Result> newList)
{
this.ClassUser= new List<Class.Result>(newList);
}
in your update method :
public void Update(List<Class.Result> oldList, List<Class.Result> newList)
{
// Set detectMoves to true for smoother animations
MyDiffCallback callback = new MyDiffCallback(oldList, newList);
DiffUtil.DiffResult result = DiffUtil.CalculateDiff(callback);
this.ClassUser.Clear();
this.ClassUser.AddRange(newList);
setData(this.ClassUser);
// Despatch the updates to your RecyclerAdapter
result.DispatchUpdatesTo(this);
}

Filter Data from RecyclerView Firebase

I am trying to implement a searchview in my action bar and for that to filter the RecyclerView Data that I retrieved from Firebase. Right now I am looking for the code that I need to add to the recycleradapter to be able to filter the retrieved data.
This is how I added the recyclerView to my MainActivity.
Query query = mRef.orderByChild("city");
// everything else
FirebaseRecyclerAdapter<City, CityViewHolder> firebaseRecyclerAdapter =
new FirebaseRecyclerAdapter<City, CityViewHolder>(
City.class,
R.layout.city_starter,
CityViewHolder.class,
query
) {
#Override
protected void populateViewHolder(CityViewHolder viewHolder, City city, int position) {
viewHolder.setDetails(getApplicationContext(),
city.getCity());
}
// for click of parent item
#Override
public CityViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
CityViewHolder viewHolder = super.onCreateViewHolder(parent, viewType);
viewHolder.setOnClickListener(new CityViewHolder.ClickListener() {
#Override
public void onItemClick(View view, int position) {
//get Data from Firebase
String cCity = getItem(position).getCity();
// pass this data to new activity
Intent secondMainActivity = new Intent(view.getContext(), SecondMainActivity.class);
secondMainActivity.putExtra("city", cCity);
startActivity(secondMainActivity);
}
#Override
public void onItemLongClick(View view, int position) {
// possible to implement another way of interacting for a long click
}
});
return viewHolder;
}
};
// set adapter to recyclerview
mRecyclerView.setAdapter(firebaseRecyclerAdapter);
}
Is there anybody who is able to help?
Thank you :)
This is what I found searching for solutions but I don't get it how to adapt it to my code:
public void filter(String text) {
items.clear();
if(text.isEmpty()){
items.addAll(itemsCopy);
} else{
text = text.toLowerCase();
for(PhoneBookItem item: itemsCopy){
if(item.name.toLowerCase().contains(text) || item.phone.toLowerCase().contains(text)){
items.add(item);
}
}
}
notifyDataSetChanged();
}
You can use android's Filterable interface..
Follow this link for example
Firstly implements Filterable to your adapter class.. You can use another array list of same type you are using for storing and showing filtered items.
Implements Filterable interface's method getFilter()
Example Code...
#Override
public Filter getFilter() {
return new Filter() {
#Override
protected FilterResults performFiltering(CharSequence charSequence) {
String charString = charSequence.toString();
if (charString.isEmpty()) {
contactListFiltered = contactList;
} else {
List<Contact> filteredList = new ArrayList<>();
for (Contact row : contactList) {
// name match condition. this might differ depending on your requirement
// here we are looking for name or phone number match
if (row.getName().toLowerCase().contains(charString.toLowerCase()) || row.getPhone().contains(charSequence)) {
filteredList.add(row);
}
}
contactListFiltered = filteredList;
}
FilterResults filterResults = new FilterResults();
filterResults.values = contactListFiltered;
return filterResults;
}
#Override
protected void publishResults(CharSequence charSequence, FilterResults filterResults) {
contactListFiltered = (ArrayList<Contact>) filterResults.values;
// refresh the list with filtered data
notifyDataSetChanged();
}
};
}
Add search view into your toolbar....
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
// Associate searchable configuration with the SearchView
SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
searchView = (SearchView) menu.findItem(R.id.action_search)
.getActionView();
searchView.setSearchableInfo(searchManager
.getSearchableInfo(getComponentName()));
searchView.setMaxWidth(Integer.MAX_VALUE);
// listening to search query text change
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
// filter recycler view when query submitted
mAdapter.getFilter().filter(query);
return false;
}
#Override
public boolean onQueryTextChange(String query) {
// filter recycler view when text is changed
mAdapter.getFilter().filter(query);
return false;
}
});
return true;
}
#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();
//noinspection SimplifiableIfStatement
if (id == R.id.action_search) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onBackPressed() {
// close search view on back button pressed
if (!searchView.isIconified()) {
searchView.setIconified(true);
return;
}
super.onBackPressed();
}

Realm Array of Strings in Android

I have been trying to store an array of strings in Realm database programmatically as given below:
Model Class:
public class Station extends RealmObject {
private String name;
// ... Generated getters and setters ...
}
Saving Data:
realm.executeTransactionAsync(new Realm.Transaction() {
#Override
public void execute(Realm realm) {
Station station1 = realm.createObject(Station.class)
station1.setName(name1);
Station station2 = realm.createObject(Station.class)
station2.setName(name2);
//goes on till station8000
}
}, new Realm.Transaction.OnSuccess() {
#Override
public void onSuccess() {
// ...
});
Is there an alternate best way for this?
Why yes of course there is
public class Station extends RealmObject {
private String name;
// ... Generated getters and setters ...
}
and
// field variable
RealmResults<Station> stations;
// field variable
RealmChangeListener<RealmResults<Station>> changeListener = new RealmChangeListener<RealmResults<Station>>() {
#Override
public void onChange(RealmResults<Station> results) {
// handle onSuccess()
}
}
and
stations = realm.where(Station.class).findAll();
stations.addChangeListener(changeListener);
realm.executeTransactionAsync(new Realm.Transaction() {
#Override
public void execute(Realm realm) {
Station station = new Station();
for(String stationName : listOfStationNames) {
station.setName(stationName);
realm.insert(station);
}
}
});
EDIT: Check out this sexy spinner.
public class DropdownSpinnerAdapter
extends BaseAdapter
implements SpinnerAdapter {
private static final String TAG = "DropdownSpinnerAdapter";
private boolean isItemSelected;
RealmResults<Station> content;
public ResultDropdownSpinnerAdapter(RealmResults<Station> objects) {
this.content = objects;
}
#Override
public int getCount() {
if(content == null || !content.isValid()) {
return 1;
}
return content.size() + 1;
}
#Override
public String getItem(int position) {
if(position <= 0) {
return "";
}
return content.get(position - 1);
}
#Override
public long getItemId(int position) {
return position;
}
public int findPosition(Station selectedItem) {
for(int i = 0, s = content.size(); i < s; i++) {
Station item = content.get(i);
if(item.equals(selectedItem)) {
return i + 1;
}
}
return 0;
}
static class ViewHolder {
TextView textView;
ImageView imageView;
public ViewHolder(View convertView) {
textView = ButterKnife.findById(convertView, R.id.dropdown_textview);
imageView = ButterKnife.findById(convertView, R.id.dropdown_arrow);
}
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if(convertView != null) {
if(!(convertView instanceof DropdownHeaderView)) {
convertView = null;
}
}
if(convertView == null) {
convertView = LayoutInflater.from(parent.getContext())
.inflate((isItemSelected) ? R.layout.dropdown_selected : R.layout.dropdown,
parent,
false);
ViewHolder viewHolder = new ViewHolder(convertView);
convertView.setTag(viewHolder);
}
ViewHolder viewHolder = (ViewHolder) convertView.getTag();
viewHolder.textView.setText(getItem(position).getName());
return convertView;
}
public void setItemSelected(boolean selected) {
this.isItemSelected = selected;
}
#Override
public View getDropDownView(int position, View convertView, ViewGroup parent) {
if(convertView != null) {
if(!(convertView instanceof DropdownView)) {
convertView = null;
}
}
if(convertView == null) {
convertView = LayoutInflater.from(parent.getContext()).inflate(R.layout.dropdown_noarrow, parent, false);
ViewHolder viewHolder = new ViewHolder(convertView);
convertView.setTag(viewHolder);
}
ViewHolder viewHolder = (ViewHolder) convertView.getTag();
viewHolder.textView.setText(getItem(position).getName());
return convertView;
}
public void updateContent(RealmResults<Station> content) {
this.content = content;
notifyDataSetChanged();
}
}

Refresh list and adapter when DB changed in custom Adapter

my project is todo
i have 4 tab , 4 fragment with 4 list(Actionbar navigation contain 4 tab and ViewPager).
4 list(tab) use same db table but each of them retrieve different data with categoryID.
i use a Asynctask for all of them ,to read data and set adapter to list.
public class AsyncTaskDB extends AsyncTask<Void, Void, listAdapter> {
Context act;
int Categoryid;
ArrayList<memo> arraymemo;
listAdapter myadapter;
ListView list;
listAdapter listAdp;
public AsyncTaskDB(Context acti, int categoryID) {
this.act = acti;
this.Categoryid = categoryID;
}
#Override
protected listAdapter doInBackground(Void... params) {
MemoDBHelper helper = new MemoDBHelper(act);
// getAllDataByCategoryID
if (Categoryid != CategoryID.Done_ID)
arraymemo = helper.getAllTaskByCategory(Categoryid);
else
arraymemo = (ArrayList<memo>) helper.gatDoneMemo();
myadapter = new listAdapter(act, arraymemo);
if (myadapter == null) {
Toast.makeText(act, "no data", Toast.LENGTH_SHORT).show();
cancel(true);
}
return myadapter;
}
#Override
protected void onPostExecute(listAdapter result) {
switch (Categoryid) {
case CategoryID.Urgent_Imprtant_ID:
list = (ListView) ((Activity) act)
.findViewById(R.id.Urgent_Important_list);
break;
case CategoryID.Urgent_Less_Imprtant_ID:
list = (ListView) ((Activity) act)
.findViewById(R.id.Urgent_Less_Important_list);
break;
case CategoryID.Less_Urgent_Imprtant_ID:
list = (ListView) ((Activity) act)
.findViewById(R.id.Less_Urgent_Imprtant_list);
break;
case CategoryID.Neither_Urgent_Or_Imprtant_ID:
list = (ListView) ((Activity) act)
.findViewById(R.id.Neither_Urgent_Imprtant_list);
break;
case CategoryID.Done_ID:
list = (ListView) ((Activity) act).findViewById(R.id.ArchiveList);
break;
}
list.setAdapter(result);
this.listAdp = result;
}
public listAdapter getlistAdapter() {
return this.listAdp;
}
}
each memo in list have Done CheckBox.when user check and uncheck it,automatically memo update in db.(in custom adapter)
----------------------------
| -- |
| | | memotitle |
| -- |
----------------------------
public class listAdapter extends BaseAdapter implements OnCheckedChangeListener { Context act;
ArrayList<memo> MemoArray;
SparseBooleanArray mcheck;
int pos;
MemoDBHelper helper;
public listAdapter(Context activity, ArrayList<memo> memoarray) {
this.act = activity;
this.MemoArray = memoarray;
mcheck = new SparseBooleanArray(memoarray.size());
helper = new MemoDBHelper(act);
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return MemoArray.size();
}
#Override
public memo getItem(int position) {
// TODO Auto-generated method stub
return MemoArray.get(position);
}
#Override
public long getItemId(int arg0) {
// TODO Auto-generated method stub
return 0;
}
public class viewHolder {
TextView title;
// TextView description;
CheckBox chkstatus;
}
viewHolder it;
#Override
public View getView(int position, View convertView, ViewGroup parent) {
pos = position;
LayoutInflater in = ((Activity) act).getLayoutInflater();
if (convertView == null) {
convertView = in.inflate(R.layout.list_item, null);
it = new viewHolder();
it.title = (TextView) convertView.findViewById(R.id.txt_list_title);
it.chkstatus = (CheckBox) convertView
.findViewById(R.id.chkStatusid);
convertView.setTag(it);
} else {
it = (viewHolder) convertView.getTag();
}
it.title.setText(MemoArray.get(position).GetTitle());
it.chkstatus.setChecked(MemoArray.get(position).GetSattus());
it.chkstatus.setOnCheckedChangeListener(this);
it.chkstatus.setTag(String.valueOf(MemoArray.get(position).GetID()));
return convertView;
}
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
mcheck.put(Integer.valueOf((String) buttonView.getTag()), isChecked);
helper.updateStatusByID(Integer.valueOf((String) buttonView.getTag()),
(isChecked));
helper.close();
//after db updatedt ,call method in fragment to notifydatsetchanged!
UrgentImportant_frg.notifyAdapter();
}
}
adapter must notify data changed ,and list don't show done memo.i don't how to do it !
my first fragment :
public class UrgentImportant_frg extends Fragment {
static listAdapter myadp;
ListView list;
// memo selectedmemo;
long[] checkid;
AsyncTaskDB asyn;
ArrayList<memo> selectedMemoArray;
final static int RQS_MoveTo = 10;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootview = inflater.inflate(R.layout.urgentimportant_layout,
container, false);
return rootview;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
list.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE_MODAL);
selectedMemoArray = new ArrayList<memo>();
list.setMultiChoiceModeListener(new MultiChoiceModeListener() {
#Override
public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
return true;
}
#Override
public void onDestroyActionMode(ActionMode mode) {
// list.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE_MODAL);
}
#Override
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
mode.getMenuInflater().inflate(R.menu.list_select_menu, menu);
/*
* MenuInflater inflater = getActivity().getMenuInflater();
* inflater.inflate(R.menu.list_select_menu, menu);
*/
mode.setTitle("Select Items");
return true;
}
#Override
public boolean onActionItemClicked(final ActionMode mode,
MenuItem item) {
switch (item.getItemId()) {
case R.id.deletemenu:
final int[] myitemsid = getSelectedID();
final MemoDBHelper helper = new MemoDBHelper(getActivity());
AlertDialog.Builder myAlert = new AlertDialog.Builder(
getActivity());
myAlert.setMessage(
"Are you sure to delete " + myitemsid.length
+ " memo ?")
.setPositiveButton("yes", new OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int which) {
for (int j = 0; j < myitemsid.length; j++) {
helper.deleteRow(myitemsid[j]);
/*
* if (j == myitemsid.length - 1) {
* strid[j] = String
* .valueOf(myitemsid[j]); } else {
* strid[j] = String
* .valueOf(myitemsid[j]) + ","; }
*/
}
mode.finish();
onResume();
}
}).setNegativeButton("no", new OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int which) {
mode.finish();
}
});
AlertDialog alert = myAlert.create();
alert.show();
// mode.finish();
break;
case R.id.MoveTomenu:
// myadp.getItem(position);
Intent i = new Intent(getActivity(),
MoveToCategory_act.class);
i.putExtra("categoryid", CategoryID.Urgent_Imprtant_ID);
startActivityForResult(i, RQS_MoveTo);
mode.finish();
break;
}
return true;
}
// get selected id to delete and move category
#Override
public void onItemCheckedStateChanged(ActionMode mode,
int position, long id, boolean checked) {
if (myadp == null) {
myadp = asyn.getlistAdapter();
}
int p = ifMemoSelectedBefore(myadp.getItem(position));
if (p != -1) {
selectedMemoArray.remove(p);
} else if (checked) {
selectedMemoArray.add(myadp.getItem(position));
}
final int checkedCount = list.getCheckedItemCount();
switch (checkedCount) {
case 0:
mode.setSubtitle(null);
break;
case 1:
mode.setSubtitle("One Item Selected");
break;
default:
mode.setSubtitle(checkedCount + " Item Selected");
break;
}
}
});
getActivity().getActionBar().setSubtitle("subtitle");
}
public int ifMemoSelectedBefore(memo m) {
return selectedMemoArray.indexOf(m);
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onViewCreated(view, savedInstanceState);
list = (ListView) view.findViewById(R.id.Urgent_Important_list);
// -------------click item
list.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1,
int position, long arg3) {
if (myadp == null) {
myadp = asyn.getlistAdapter();
}
// Log.d("tag", myadp.getItem(position).GetTitle() + "");
Intent nextintent = new Intent(getActivity(),
EditMemo_act.class);
memo g = myadp.getItem(position);
/*
* MemoDBHelper helper = new MemoDBHelper(getActivity());
* helper.updateStatusByID(g.GetID(), true);
*/
nextintent.putExtra("editmemo", g);
startActivity(nextintent);
}
});
}
#Override
public void onResume() {
asyn = new AsyncTaskDB(getActivity(), CategoryID.Urgent_Imprtant_ID);
asyn.execute();
super.onResume();
}
public int[] getSelectedID() {
int[] SelectedArray_ID = new int[selectedMemoArray.size()];
for (int j = 0; j < selectedMemoArray.size(); j++) {
SelectedArray_ID[j] = selectedMemoArray.get(j).GetID();
// Log.d("id", selectedMemoArray.get(j).GetID() + "");
}
return SelectedArray_ID;
}
//-------------a method to notifymyadpter
public static void notifyAdapter() {
if (myadp != null) {
myadp.notifyDataSetChanged();
Log.d("notify", "here");
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RQS_MoveTo) {
if (resultCode == Result.RESULT_OK) {
int id = data.getExtras().getInt("NEWCategoryID");
MemoDBHelper helper = new MemoDBHelper(getActivity());
final int[] myitemsid = getSelectedID();
for (int j = 0; j < myitemsid.length; j++) {
helper.updateCategory(myitemsid[j], id);
}
onResume();
}
}
}
}
is there any method in fragment to run after adapter changed?or in myadapter ,after db updated i call a method in fragment to notify data changed ? i think the second solution isn't right >_<
p.s:notifyAdapter() doesn't work,is it because my adapter fill in asyntask ?
When the adapter changed, try to call below method.
Once you use FragmentPagerAdapter or ListView, when you change the data, you should call this.
notifyDataSetChanged();
read about it : notifyDataSetChanged

how I get the current visible fragment from view pager Adapter..?

I have implemented these lines of code but it is not working .
pagerAdapter= new AbstractPagerAdapter(getSupportFragmentManager());
mViewPager = (ViewPager)findViewById(R.id.pager);
MyFragment frg = (MyFragment)pagerAdapter.getItem(mViewPager.getCurrentItem());
public class AbstractPagerAdapter extends FragmentPagerAdapter {
public AbstractPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
return AbstractDetailFragment.newInstance(objlist.get(position),position == notePosition ? true : false);
}
#Override
public int getCount() {
return objlist.size();
}
#Override
public CharSequence getPageTitle(int position) {
return objlist.get(position).getTitle();
}
}
To get the currently visible fragment instance try the following
viewPager.setOnPageChangeListener(this);
and in the following method
#Override
public void onPageSelected(int position) {
if (position == 0)
setFragmentFor(0);
if (position == 1)
setFragmentFor(1);
.
.
.
// Upto how many fragments you've in your ViewPager
}
so in the setFragmentFor() method you should write your own logic to get the new Instance of Fragment depending upon the argument value passed over the setFragmentFor().

Resources