NullPointerException when notifyDataSetChanged() on ArrayAdapter (ListView in ViewPager) - android-listview

I have an Activity with ViewPager which manage 2 Fragments using FragmentStatePagerAdapter,
The fragments have ListViews, each of the ListView shows data and I am able to go from Fragment_A to Fragment_B by swipe or item tapping on the ListView of Fragment_A.
I am also able to update the underlying data source for Fragment_B based on the item selected in Fragment_A. But when I try to notifyDataSetChanged() on the DataAdapter of Fragment_B, I am getting NullPointerException .
I want to update the data in Fragment_B according to the item selected in Fragment_A.
Here is my code
public class MyActivity extends FragmentActivity implements AdapterView.OnItemClickListener{
ViewPager viewPager = null;
int mSelectedItemPosition;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_fail_activity);
viewPager = (ViewPager) findViewById(R.id.fail_pager_VP);
viewPager.setAdapter(new pagerAdapter(getSupportFragmentManager()));
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
mSelectedItemPosition = position;
viewPager.setCurrentItem(1);
FragmentStatePagerAdapter fspa = (FragmentStatePagerAdapter) viewPager.getAdapter();
Fragment_B item = (Fragment_B) fspa.getItem(1);
item.setData(position);
item.refresh();
}
}
class pagerAdapter extends FragmentStatePagerAdapter {
public pagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
Fragment fragment = null;
if (position == 0) {
fragment = new Fragment_A();
} else if (position == 1) {
fragment = new Fragment_B();
}
return fragment;
}
#Override
public int getCount() {
return 2;
}
#Override
public CharSequence getPageTitle(int position) {
String title = "";
if (position == 0) {
return "a_title";
}else if (position == 1) {
return "b_title";
}
}
}
public class Fragment_A extends android.support.v4.app.Fragment {
private ListView frag_a_listView;
DataAdapter dataAdapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
ListView frag_a_listView = (ListView) getActivity().findViewById(R.id.frag_a_LV);
frag_a_listView.setOnItemClickListener((AdapterView.OnItemClickListener) getActivity());
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View layout = inflater.inflate(R.layout.fragment_fail_main, container, false);
frag_a_listView = (ListView) layout.findViewById(R.id.frag_a_LV);
dataAdapter = new DataAdapter(getActivity(),
R.layout.data_row,
R.id.data_label_TV,
getFrag_aData());
frag_a_listView.setAdapter(dataAdapter);
return layout;
}
private List<String> getFrag_aData() {
...
return someData;
}
}
public class Fragment_B extends android.support.v4.app.Fragment {
ListView frag_b_listView;
List<String> mData;
DataAdapter dataAdapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
ListView frag_b_listView = (ListView) getActivity().findViewById(R.id.frag_b_LV);
frag_b_listView.setOnItemClickListener((AdapterView.OnItemClickListener) getActivity());
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View layout = inflater.inflate(R.layout.fragment_frag_b, container, false);
frag_b_listView = (ListView) layout.findViewById(R.id.frag_b_LV);
setData(0);
dataAdapter = new DataAdapter(getActivity(),
R.layout.data_row,
R.id.data_label_TV,
mData);
frag_b_listView.setAdapter(dataAdapter);
return layout;
}
public void setData(int position) {
...
mData = some List<String>;
}
public void refresh() {
dataAdapter.notifyDataSetChanged(); <------- this crashes the app
}
}
public class DataAdapter extends ArrayAdapter {
public DataAdapter(Context context, int resource, int textViewResourceId, List objects) {
super(context, resource, textViewResourceId, objects);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
convertView = super.getView(position, convertView, parent);
return convertView;
}
}
here is the crash log
06-25 16:51:46.813 21537-21537/au.myCity.eight E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: au.myCity.eight, PID: 21537
java.lang.NullPointerException: Attempt to invoke virtual method 'void au.myCity.eight.dataAdapter.notifyDataSetChanged()' on a null object reference
at au.myCity.eight.fragments.Fragment_B.refresh(Fragment_B.java:56)
at au.myCity.eight.MyActivity.onItemClick(MyActivity.java:37)
at android.widget.AdapterView.performItemClick(AdapterView.java:305)
at android.widget.AbsListView.performItemClick(AbsListView.java:1146)
at android.widget.AbsListView$PerformClick.run(AbsListView.java:3053)
at android.widget.AbsListView$3.run(AbsListView.java:3860)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5254)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)

After few tries with Log.d and checking some variable references.
The problem was the reference to Fragment_B changed by the time I called dataAdapter.notifyDataSetChanged(), to fix this I used the solution suggested in SO here, thanks to the "Streets Of Boston".
Summery, In the PagerAdapter:
Save a reference to initialized fragments in a SparseArray, use getRegisteredFragment in
onItemClick instead of getItem in MyActivity.
Override instantiateItem and destroyItem as suggested in the link.

Related

How to convert Firebase child name into date and time

I have a basic app that has RecyclerView for getting data from a Firebase database, which looks like this:
I would like to have the 20170108_100 converted into data and time format (08/01/2017 10:00), which can then be compared to the actual date.
I'm planning to have some IF conditions in order to sort the database by date&time and I need to have something like this:
if (20170108_100 < CurrentDate&Time) then doSomething else doSomethingElse
Is there any way one can do that?
So far, I have this code that reads that database:
public class Hotarari extends Fragment {
View v;
ProgressDialog progress;
private FirebaseRecyclerAdapter < Variabile_primarie, ContactViewHolder > cc;
private RecyclerView mContactRV;
private DatabaseReference mPostRef;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, Bundle savedInstanceState) {
v = inflater.inflate(R.layout.fragment_hotarari, container, false);
return v;
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
this.v = view;
initialiseScreen();
}
private void initialiseScreen() {
mContactRV = (RecyclerView) v.findViewById(R.id.contact_recyclerview);
mContactRV.setLayoutManager(new LinearLayoutManager(getContext()));
mPostRef = FirebaseDatabase.getInstance().getReference("-DeciziiPrimari");
setupAdaptater();
mContactRV.setAdapter(cc);
}
private void setupAdaptater() {
cc = new FirebaseRecyclerAdapter < Variabile_primarie, ContactViewHolder > (
Variabile_primarie.class,
R.layout.item_hotarari,
ContactViewHolder.class,
mPostRef
) {
#Override
protected void populateViewHolder(ContactViewHolder viewHolder, final Variabile_primarie model, int position) {
viewHolder.setData(model.getData());
viewHolder.setNumar(model.getNumar());
viewHolder.setHotarare(model.getHotarare());
}
};
}
public static class ContactViewHolder extends RecyclerView.ViewHolder {
private TextView tv_hotarare;
private TextView tv_data;
private TextView tv_numar;
public ContactViewHolder(View itemView) {
super(itemView);
tv_hotarare = (TextView) itemView.findViewById(R.id.continut_hotarare);
tv_data = (TextView) itemView.findViewById(R.id.data_hotarare);
tv_numar = (TextView) itemView.findViewById(R.id.numar_hotarare);
}
void setHotarare(String hotarare) {
tv_hotarare.setText(String.valueOf(hotarare));
}
public void setData(String data) {
tv_data.setText(String.valueOf(data));
}
void setNumar(String numar) {
tv_numar.setText(String.valueOf(numar));
}
}
}

Android ListView - ExpandableHeightListView add a limit of 10 records per page

My listview is found inside a ScrollView. The ListView was extended by ExpandableHeightListView class. When, 20 row items are loaded, the image library freeze the UI until all images are loaded. Then, user can scroll and select an item. To handle this issue, I tried to load every 10 records in the arraylist. Can i do it directly in the ExpandableHeightListView , if so how ?
public class ExpandableHeightListView extends ListView {
boolean expanded = false;
public ExpandableHeightListView(Context context) {
super(context);
}
public ExpandableHeightListView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public ExpandableHeightListView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
public boolean isExpanded() {
return expanded;
}
#Override
public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
if (isExpanded()) {
// int expandSpec = MeasureSpec.makeMeasureSpec(MEASURED_SIZE_MASK, MeasureSpec.AT_MOST);
//super.onMeasure(widthMeasureSpec, heightMeasureSpec);
// Calculate entire height by providing a very large height hint.
// MEASURED_SIZE_MASK represents the largest height possible.
//int expandSpec = MeasureSpec.makeMeasureSpec(MEASURED_SIZE_MASK, MeasureSpec.AT_MOST);
//super.onMeasure(widthMeasureSpec, expandSpec);
// Calculate entire height by providing a very large height hint.
// But do not use the highest 2 bits of this integer; those are
// reserved for the MeasureSpec mode.
int expandSpec = MeasureSpec.makeMeasureSpec(
Integer.MAX_VALUE >> 2, MeasureSpec.AT_MOST);
super.onMeasure(widthMeasureSpec, expandSpec);
ViewGroup.LayoutParams params = getLayoutParams();
params.height = getMeasuredHeight();
} else {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
}
public void setExpanded(boolean expanded) {
this.expanded = expanded;
}
}
The ListView adapter is as follows:
public class ResultatRechercheAdapter extends BaseAdapter {
public static final String IMAGE_CACHE_DIR = "images";
public static final String EXTRA_IMAGE = "extra_image";
public List<MRechercheResult> items;
public final OnClickListener itemButtonClickListener;
public final Context context;
public Activity activity;
public String agenda_date;
public String agenda_from;
public String agenda_to;
public ViewHolder holder;
public int agenda_from_hour=-1;
public int agenda_from_minute=-1;
public int agenda_to_hour;
public int agenda_to_minute;
public String from_am_pm;
public String to_am_pm;
private String monday;
private String tuesday;
private String wednesday;
private String thursday;
private String friday;
private String saturday;
private String sunday;
public ImageFetcher mImageFetcher;
public ResultatRechercheAdapter(Activity activity,Context context, List<MRechercheResult> resultat, OnClickListener itemButtonClickListener) {
this.activity = activity;
this.context = context;
this.items = resultat;
this.itemButtonClickListener = itemButtonClickListener;
//this.mImageFetcher = mImageFetcher;
try {
monday= activity.getResources().getString(R.string.monday);
tuesday= activity.getResources().getString(R.string.tuesday);
wednesday= activity.getResources().getString(R.string.wednesday);
thursday= activity.getResources().getString(R.string.thursday);
friday= activity.getResources().getString(R.string.friday);
saturday= activity.getResources().getString(R.string.saturday);
sunday= activity.getResources().getString(R.string.sunday);
} catch(Exception ex){}
}
#Override
public int getCount() {
return items.size();//items.size()
}
#Override
public MRechercheResult getItem(int position) {
return items.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public int getViewTypeCount() {
return 1;//items.size()
}
#Override
public int getItemViewType(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = LayoutInflater.from(context).inflate(R.layout.list_item_card, null);
holder = new ViewHolder();
holder.txRowTitle = (TextView) convertView.findViewById(R.id.txRowTitle);
holder.imThumbnail= (RecyclingImageView) convertView.findViewById(R.id.imThumbnail);
holder.itemButton1 = (Button) convertView.findViewById(R.id.list_item_card_close);
holder.itemButton2 = (Button) convertView.findViewById(R.id.list_item_card_button_2);
holder.imCircleLundi= (ImageView) convertView.findViewById(R.id.imCircleLundi);
holder.imCircleMardi= (ImageView) convertView.findViewById(R.id.imCircleMardi);
holder.imCircleMercredi= (ImageView) convertView.findViewById(R.id.imCircleMercredi);
holder.imCircleJeudi= (ImageView) convertView.findViewById(R.id.imCircleJeudi);
holder.imCircleVendredi= (ImageView) convertView.findViewById(R.id.imCircleVendredi);
holder.imCircleSamedi= (ImageView) convertView.findViewById(R.id.imCircleSamedi);
holder.imCircleDimanche= (ImageView) convertView.findViewById(R.id.imCircleDimanche);
holder.rlListRecherche= (RelativeLayout) convertView.findViewById(R.id.rlListRecherche);
holder.llImage= (LinearLayout) convertView.findViewById(R.id.llImage);
holder.rlListClose= (RelativeLayout) convertView.findViewById(R.id.rlListClose);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
boolean no_record = items.get(position).no_record;
if (no_record){ // listview is empty
holder.llImage.setVisibility(View.GONE);
holder.rlListClose.setVisibility(View.GONE);
holder.rlListRecherche.setVisibility(View.VISIBLE);
} else {
Utils.shortWeek(activity, convertView);
holder.llImage.setVisibility(View.VISIBLE);
holder.rlListClose.setVisibility(View.VISIBLE);
holder.rlListRecherche.setVisibility(View.GONE);
if (itemButtonClickListener != null) {
//holder.itemButton1.setOnClickListener(itemButtonClickListener);
holder.itemButton1.setVisibility(View.GONE);
holder.itemButton2.setOnClickListener(itemButtonClickListener);
}
final String image_url = items.get(position).profil_photo.toString().replace("\\","").replace("hepigo", "helpigo");
String item_title = items.get(position).profil.toString();
if (item_title.equalsIgnoreCase("Julien Perez")){
if (true){
String display_pos = String.valueOf(position);
System.out.println(display_pos);
}
}
//searchRequest(position,image_url);
//if (!TextUtils.isEmpty(image_url))
// mImageFetcher.loadImage(image_url, holder.imThumbnail);
activity.runOnUiThread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
if (TextUtils.isEmpty(items.get(position).profil_photo)) {
//no url
} else {
Picasso.with(activity)
.load(image_url)
.error(android.R.drawable.stat_notify_error)
.transform(transformation)
.placeholder(R.drawable.loading_image_placeholder)
.config(Config.RGB_565)
.into(holder.imThumbnail);
}
}
});
//if (!TextUtils.isEmpty(image_url))
// new DownloadImageTask(holder.imThumbnail).execute(image_url);
holder.txRowTitle.setText(item_title);
activity.runOnUiThread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
List<Agenda> agenda = items.get(position).agenda;
Utils.displayAgenda(agenda,holder.imCircleLundi,monday);
Utils.displayAgenda(agenda,holder.imCircleMardi,tuesday);
Utils.displayAgenda(agenda,holder.imCircleMercredi,wednesday);
Utils.displayAgenda(agenda,holder.imCircleJeudi,thursday);
Utils.displayAgenda(agenda,holder.imCircleVendredi,friday);
Utils.displayAgenda(agenda,holder.imCircleSamedi,saturday);
Utils.displayAgenda(agenda,holder.imCircleDimanche,sunday);
}
});
}
return convertView;
}
public static class ViewHolder {
public RelativeLayout rlListClose;
public LinearLayout llImage;
public RelativeLayout rlListRecherche;
public ImageView imCircleSamedi;
public ImageView imCircleDimanche;
public ImageView imCircleVendredi;
public ImageView imCircleJeudi;
public ImageView imCircleMercredi;
public ImageView imCircleMardi;
public ImageView imCircleLundi;
public RecyclingImageView imThumbnail;
public TextView txRowTitle;
public Button itemButton1;
public Button itemButton2;
}

Updating ListView data onItemClick

My code does update the ListView when onItemClick is fired but only if I replace the line "inside the onItemClick method"
categoryAdapter.notifyDataSetChanged();
with the line
lv.setAdapter(new CategoryAdapter(categories));
Should I replace the line as indicated above or the notifyDataSetChanged is what I should use? since the docs say that it should update the view as well.
besides, when I do that, the app runs but hitting the back button shuts the app down instead of go back to the last screen which what I like to see.
public class MainActivity extends ActionBarActivity {
ListView lv;
String[] categories = null;
private static String[] failCategories = {"a","b","c};
private static String[] category_a= { "a1","a2"};
CategoryAdapter categoryAdapter = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_categories);
lv = (ListView) findViewById(R.id.lvCategories);
categories = failCategories; //initial set
categoryAdapter = new CategoryAdapter(categories);
lv.setAdapter(categoryAdapter);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if (position == 0){
categories = category_a;
categoryAdapter.notifyDataSetChanged();
}
}
});
}
private class CategoryAdapter extends ArrayAdapter<String>{
CategoryAdapter(String[] objects) {
super(getBaseContext(), R.layout.activity_categories,R.id.tvCategory, objects);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
convertView = super.getView(position, convertView, parent);
return convertView;
}
}
}
please try this part of code inside your code if you want to update respected item only, make sure category_a has equal items
Version 1
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
categoryAdapter.insert(position,category_a[position]);
categoryAdapter.notifyDataSetChanged();
}
Version 2
if you want to update whole listview with all items in category_a then
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
categoryAdapter.clear();
categoryAdapter.addAll(category_a);
categoryAdapter.notifyDataSetChanged();
}

How to create ExpandableListView keeping some child fixed?

I want to create an expandable list view Keeping some child visible,where as I want to show rest on click.
Please suggest what is the best approach in such scenario,if any custom element or any tutorial as such.
Many Thanks,
This will be helpful to you.
Adapter class:-
public class MyExpandableAdapter extends BaseExpandableListAdapter {
private Activity activity;
private ArrayList<Object> childtems;
private LayoutInflater inflater;
private ArrayList<String> parentItems, child;
public MyExpandableAdapter(ArrayList<String> parents,
ArrayList<Object> childern) {
this.parentItems = parents;
this.childtems = childern;
}
public void setInflater(LayoutInflater inflater, Activity activity) {
this.inflater = inflater;
this.activity = activity;
}
#Override
public View getChildView(int groupPosition, final int childPosition,
boolean isLastChild, View convertView, ViewGroup parent) {
child = (ArrayList<String>) childtems.get(groupPosition);
TextView textView = null;
if (convertView == null) {
convertView = inflater.inflate(R.layout.group, null);
}
textView = (TextView) convertView.findViewById(R.id.textView1);
textView.setText(child.get(childPosition));
convertView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(activity, child.get(childPosition),
Toast.LENGTH_SHORT).show();
}
});
return convertView;
}
#Override
public View getGroupView(int groupPosition, boolean isExpanded,
View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = inflater.inflate(R.layout.row, null);
}
((CheckedTextView) convertView).setText(parentItems
.get(groupPosition));
((CheckedTextView) convertView).setChecked(isExpanded);
return convertView;
}
#Override
public Object getChild(int groupPosition, int childPosition) {
return null;
}
#Override
public long getChildId(int groupPosition, int childPosition) {
return 0;
}
#Override
public int getChildrenCount(int groupPosition) {
return ((ArrayList<String>) childtems.get(groupPosition)).size();
}
#Override
public Object getGroup(int groupPosition) {
return null;
}
#Override
public int getGroupCount() {
return parentItems.size();
}
#Override
public void onGroupCollapsed(int groupPosition) {
super.onGroupCollapsed(groupPosition);
}
#Override
public void onGroupExpanded(int groupPosition) {
super.onGroupExpanded(groupPosition);
}
#Override
public long getGroupId(int groupPosition) {
return 0;
}
#Override
public boolean hasStableIds() {
return false;
}
#Override
public boolean isChildSelectable(int groupPosition, int childPosition) {
return false;
}
}
MainActivity is here.
public class MainActivity extends ExpandableListActivity {
private ArrayList<String> parentItems = new ArrayList<String>();
private ArrayList<Object> childItems = new ArrayList<Object>();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// this is not really necessary as ExpandableListActivity contains
// an ExpandableList
// setContentView(R.layout.main);
ExpandableListView expandableList = getExpandableListView(); // you
// can
// use
// (ExpandableListView)
// findViewById(R.id.list)
expandableList.setDividerHeight(2);
expandableList.setGroupIndicator(null);
expandableList.setClickable(true);
setGroupParents();
setChildData();
MyExpandableAdapter adapter = new MyExpandableAdapter(parentItems,
childItems);
adapter.setInflater(
(LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE),
this);
expandableList.setAdapter(adapter);
expandableList.setOnChildClickListener(this);
}
public void setGroupParents() {
parentItems.add("Android");
parentItems.add("Core Java");
parentItems.add("Desktop Java");
parentItems.add("Enterprise Java");
}
public void setChildData() {
// Android
ArrayList<String> child = new ArrayList<String>();
child.add("Core");
child.add("Games");
childItems.add(child);
// Core Java
child = new ArrayList<String>();
child.add("Apache");
child.add("Applet");
child.add("AspectJ");
child.add("Beans");
child.add("Crypto");
childItems.add(child);
// Desktop Java
child = new ArrayList<String>();
child.add("Accessibility");
child.add("AWT");
child.add("ImageIO");
child.add("Print");
childItems.add(child);
// Enterprise Java
child = new ArrayList<String>();
child.add("EJB3");
child.add("GWT");
child.add("Hibernate");
child.add("JSP");
childItems.add(child);
}
}
At start open the groups you want to be fixed then implement this , specify the the groups postion
expandableList.setOnGroupClickListener(new OnGroupClickListener() {
#Override
public boolean onGroupClick(ExpandableListView parent, View v,
int groupPosition, long id) {
if(groupPosition==your group position){
return true; // This way the expander cannot be collapsed
}else{
return false;
}
}
});
Override onGroupCollapsed and onGroupExpanded of the ExpandableListView based on your needs.
EDITED: In addition: implement the mentioned setOnGroupClickListener, store the groupIDs within your view, and suppress the collapsing in onGroupCollapsed.

refresh listView by clicking outside of it

I have a viewpager with an adapter that extends FragmentStatePagerAdapter, this has to show some fragment that always repeats the same layout (in whic there is a listView) for every page ... now the problem is how can I update the listView that is currently visible by clicking on a button that is outside of the Fragment? I can refresh only the ones that are in the not visible pages,but not the ones that are displayed or adjacent...
One possible solution is to reset the adapter, but it doesn't seems to be right one, because it' s slow... could you please help me?
public class MainActivity extends FragmentActivity implements OnClickListener{
#Override
protected void onCreate(Bundle arg0) {
// TODO Auto-generated method stub
super.onCreate(arg0);
setContentView(R.layout.layout1);
pagerAdapter = new AdapterPager(getSupportFragmentManager());
ctx=this;
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(pagerAdapter);
pagerTab=(PagerTabStrip) findViewById(R.id.pager_tab_strip);
mViewPager.setCurrentItem(paginaCentrale);
modifica=(ImageView)findViewById(R.id.modifica);
modifica.setOnClickListener(this);
}
#Override
public void onClick(View arg0) {
// TODO onClick
switch (arg0.getId()){
case R.id.modifica:
//here I would like to call the method caricaLista() of the fragment
break;
}
}
public static class AdapterPager extends FragmentStatePagerAdapter {
public AdapterPager(FragmentManager fm) {
super(fm);
}
#Override
public int getItemPosition(Object object) {
// TODO Auto-generated method stub
return super.getItemPosition(object);
}
#Override
public Fragment getItem(int i) {
Fragment fragment;
Bundle args = new Bundle();
args.putInt("position", i);
fragment=new Fragment1();
fragment.setArguments(args);
return fragment;
}
#Override
public int getCount() {
return 1000;}
#Override
public CharSequence getPageTitle(int i) {
String title=String.valueOf(i);
return title;
}
}
public static class Fragment1 extends Fragment implements OnItemClickListener{
int fragmentPosition;
ListView lv;
List<Lista> lista= new ArrayList<Lista>();
public Fragment1(){
}
public static Fragment1 newInstance(){
return new Fragment1();
}
#Override
public void onResume() {
// TODO Auto-generated method stub
super.onResume();
caricaLista("")}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle
savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment1, container, false);
lv=(ListView) rootView.findViewById(R.id.listViewCompiti);
Bundle args = getArguments();
int position= args.getInt("position");
fragmentPosition=position;
lv.setOnItemClickListener(this);
homeListAdapter= new HomeListAdapterWithCache(ctx,R.layout.list_item_home,lista);
lv.setAdapter(homeListAdapter);
return rootView;
}
You have to store the Current Fragment into your MainActivity , and change every time the page changes.
So you call the method of the current fragments.
Check out how your MainActivity should look like:
public class MainActivity extends FragmentActivity implements OnClickListener{
&Fragment mCurrentFragment;*
protected void onCreate(Bundle arg0) {
super.onCreate(arg0);
setContentView(R.layout.layout1);
pagerAdapter = new AdapterPager(getSupportFragmentManager());
ctx=this;
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(pagerAdapter);
pagerTab=(PagerTabStrip) findViewById(R.id.pager_tab_strip);
mViewPager.setCurrentItem(paginaCentrale);
modifica=(ImageView)findViewById(R.id.modifica);
modifica.setOnClickListener(this);
*mViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
#Override
public void onPageSelected(int position) {
mCurrentFragment = pagerAdapter.getItem(position);
}*
});
#Override
public void onClick(View arg0) {
// TODO onClick
switch (arg0.getId()){
case R.id.modifica:
*mCurrentFragment.caricaLista();*
break;
}
}
}