Unable to reset FragmentAdapter to ViewPager in onActivityResult(...) - android

I am using a FragmentActivity in that ViewPager, in onCreate(...) method i am setting FragmentPagerAdapter adapter to ViewPager it is working fine here but when i try to reset new FragmentPagerAdapter to ViewPager in onActivityResult(...) method only the constructor of the adapter is getting calling and public Fragment getItem(int position); is not getting called because of which i am getting fragment null. so when i try to get the current visible fragment after reseting the adapter in onActivityResult(...) i am getting null.
This is what I am doing in onCreate:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Remove title bar
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.blocked_list);
lable = getIntent().getStringExtra("ItemName");
blocked_list_lable = (TextView) findViewById(R.id.blocked_list_lable);
add_Contact = (Button) findViewById(R.id.add);
mAdapter = new CallManagerFragmentAdapter(getSupportFragmentManager(), lable);
mPager = (ViewPager)findViewById(R.id.pager);
mPager.setAdapter(mAdapter);
mIndicator = (TitlePageIndicator)findViewById(R.id.indicator);
mIndicator.setViewPager(mPager);
addNewContact = new AddNewContactPopup(this);
addNewContact.setPopDimentions((int) TypedValue.applyDimension(
TypedValue.COMPLEX_UNIT_DIP, 320, getResources()
.getDisplayMetrics()), (int) TypedValue.applyDimension(
TypedValue.COMPLEX_UNIT_DIP, 280, BlackList.this.getResources()
.getDisplayMetrics()));
blocked_list_lable.setText(lable);
setListener(add_Contact);
}
This is what I am doing in onActivityResult:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CALLS_SMS_LOGS || requestCode == CONTACTS_LIST) {
if (resultCode == RESULT_OK) {
String result = data.getStringExtra("dbUpdateSucess");
if (result.equals("Success")) {
Logger.log("Info", TAG,
"Update from call logs is Sucess...");
//Cursor cursor = getCursor(lable);
mAdapter = new CallManagerFragmentAdapter(getSupportFragmentManager(), lable);
mPager.setAdapter(mAdapter);
//adapter = new BlackListAdapter(this, cursor);
//blocked_List.setAdapter(adapter);
return;
} else {
Logger.log("Error", TAG, "Update from call logs failed...");
}
}
}
}
Here is my FragmentAdapter code;
class CallManagerFragmentAdapter extends FragmentPagerAdapter implements IconPagerAdapter {
protected static final String[] CONTENT = new String[] { "Call Logs", "Blacklist No"};
protected static final String[] BLACK_LIST_SMS_CONTENT = new String[] { "SMS Logs", "Blacklist No"};
protected static final String[] WHITELIST_CALLS_CONTENT = new String[] { "Call Logs", "Whitelist No"};
protected static final String[] WHITELIST_SMS_CONTENT = new String[] { "SMS Logs", "Whitelist No"};
protected static final String[] PRIVATE = new String[] { "SMS Logs", "Call Logs", "Private No"};
protected static final int[] ICONS = new int[] {
R.drawable.perm_group_calendar,
R.drawable.perm_group_camera/*,
R.drawable.perm_group_device_alarms,
R.drawable.perm_group_location*/
};
private int mCount = CONTENT.length;
private String lable;
public HashMap<Integer, CallManagerFragment> fragmentMap;
public CallManagerFragmentAdapter(FragmentManager fm, String lable) {
super(fm);
this.lable = lable;
fragmentMap = new HashMap<Integer, CallManagerFragment>();
}
#Override
public Fragment getItem(int position) {
String content;
CallManagerFragment fragment = CallManagerFragment.newInstance(content, lable);
fragmentMap.put(position, fragment);
return fragment;
}
public CallManagerFragment getFragment(int key) {
return fragmentMap.get(key);
}
public void destroyItem(ViewGroup container, int position, Object object) {
super.destroyItem(container, position, object);
fragmentMap.remove(position);
}
#Override
public int getCount() {
return mCount;
}
#Override
public CharSequence getPageTitle(int position) {
if(lable.equals("Whitelist Calls")) {
return CallManagerFragmentAdapter.WHITELIST_CALLS_CONTENT[position % WHITELIST_CALLS_CONTENT.length];
} else if (lable.equals("Whitelist SMS")) {
return WHITELIST_SMS_CONTENT[position % WHITELIST_SMS_CONTENT.length];
} else if(lable.equals("Private")) {
return PRIVATE[position % PRIVATE.length];
} else if(lable.equals("Blacklist SMS")) {
return BLACK_LIST_SMS_CONTENT[position % BLACK_LIST_SMS_CONTENT.length];
}
return CallManagerFragmentAdapter.CONTENT[position % CONTENT.length];
}
public int getIconResId(int index) {
return ICONS[index % ICONS.length];
}
public void setCount(int count) {
if (count > 0 && count <= 10) {
mCount = count;
notifyDataSetChanged();
}
}
}

Related

How to destroy a Fragment programmatically in FragmentStatePagerAdapter

I'm using the MainActivity's SearchView here to filter the listview which is showing under tabs but there is an issue of the state of Fragment.
It filters perfectly but when I select first Tab(ADVISORY), then it filters the child of this Tab. And after selecting next Tab(TOP ADVISORY), it filters all listview of the child of this tab but it stops filtering in previous Tab (ADVISORY). And at last I move to the EXPERTVIEW it works only for it not for others.
After lots of debugging I found that it doesn't get destroy when we select another Parent Tab so now I wanna know how I can remove a fragment from its adapter on unselected and reselect on selected again.
MainTabFragment.java
public class MainTabFragment extends Fragment {
public static int position_child_tab = 0, three_childs_tab_position = 0;
static int count = -1, index = 0;
int position_tab = 0;
Bundle args;
int Current_tab = 0;
public static MyTabLayout myTabLayout;
private static MainTabFragment sMainTabFragment;
public static NonSiwpablePager pager;
private Fragment mFragment;
SharedPreferences pref;
private static final int NUM_ITEMS = 2;
List<Integer> TABLE;
public MainTabFragment() {
// Required empty public constructor
}
public static MainTabFragment getInstance() {
return sMainTabFragment;
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* #param param1 Parameter 1.
* #param param2 Parameter 2.
* #return A new instance of fragment MainTabFragment.
*/
// TODO: Rename and change types and number of parameters
public static MainTabFragment newInstance(String param1, String param2) {
return new MainTabFragment();
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
args = getArguments();
if (args != null && args.containsKey("pos_next"))
position_tab = args.getInt("pos_next");
if (args != null && args.containsKey("pos_end"))
position_child_tab = args.getInt("pos_end");
if (position_child_tab != 3) {
three_childs_tab_position = position_child_tab;
} else {
three_childs_tab_position = 0;
}
args = new Bundle();
args.putInt("pos_end", position_child_tab);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.main_tab_fragment, container, false);
myTabLayout = (MyTabLayout) view.findViewById(R.id.mainTabLayout);
pager = (NonSiwpablePager) view.findViewById(R.id.pager);
final ViewPagerAdapter mAdapter = getViewPagerAdapter();
pager.setAdapter(mAdapter);
myTabLayout.setupWithViewPager(pager);
for (int i = 0; i < mAdapter.getCount(); i++) {
View customView = mAdapter.getCustomeView(getActivity(), i);
myTabLayout.getTabAt(i).setCustomView(customView);
}
pager.setCurrentItem(position_tab);
pager.setOffscreenPageLimit(NUM_ITEMS-1);
changeTab();
final Fragment fragment = getFragmentManager().findFragmentByTag("TOP");
if (fragment != null) {
pager.setCurrentItem(position_tab);
}
index = pager.getCurrentItem();
pref = getActivity().getPreferences(0);
SharedPreferences.Editor edt = pref.edit();
edt.putInt("facebook_id", pager.getCurrentItem());
edt.commit();
// ViewPagerAdapter adapter = ((ViewPagerAdapter)pager.getAdapter());
final Fragment fragment22 = mAdapter.getRegisteredFragment(pager.getCurrentItem());
pager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageSelected(int arg0) {
// TODO Auto-generated method stub
pref = getActivity().getPreferences(0);
SharedPreferences.Editor edt = pref.edit();
edt.putInt("facebook_id", pager.getCurrentItem());
edt.commit();
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
// TODO Auto-generated method stub
//Log.e("Fragment", fragment + "" +pager.getCurrentItem() + fragment22);
}
#Override
public void onPageScrollStateChanged(int arg0) {
// TODO Auto-generated method stub
// Log.e("Fragment", fragment + "" +pager.getCurrentItem() + fragment22);
}
});
myTabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
pager.setCurrentItem(tab.getPosition());
//Log.e("Fragment", fragment + "" +pager.getCurrentItem() + fragment22);
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
// mAdapter.destroyAllItem();
// Log.e("Fragment", fragment + "" +pager.getCurrentItem() + fragment22);
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
// Log.e("Fragment", fragment + "" +pager.getCurrentItem() + fragment22);
}
});
return view;
}
public void changeTab() {
Current_tab = pager.getCurrentItem();
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
myTabLayout.getTabAt(position_tab).getCustomView().setSelected(true);
}
public void setCurrentItem(int item) {
pager.setCurrentItem(item);
}
private ViewPagerAdapter getViewPagerAdapter() {
ViewPagerAdapter mAdapter = new ViewPagerAdapter(getChildFragmentManager());
String title_arr[] = {"ADVISORY", "TOP ADVISORS", "EXPERT VIEW"};
for (int i = 0; i < title_arr.length; i++) {
Map<String, Object> map = new Hashtable<>();
map.put(ViewPagerAdapter.KEY_TITLE, title_arr[i]);
if (i == 0) {
map.put(ViewPagerAdapter.KEY_FRAGMENT, AdvisoryPagerFragment.newInstance());
AdvisoryPagerFragment.newInstance().setTargetFragment(this, getTargetRequestCode());
} else if (i == 1) {
map.put(ViewPagerAdapter.KEY_FRAGMENT, TopAdvisoryPagerFragment.newInstance());
TopAdvisoryPagerFragment.newInstance().setTargetFragment(this, getTargetRequestCode());
} else if (i == 2) {
map.put(ViewPagerAdapter.KEY_FRAGMENT, ExperViewPagerFragment.newInstance());
ExperViewPagerFragment.newInstance().setTargetFragment(this, getTargetRequestCode());
}
mAdapter.addFragmentAndTitle(map);
}
return mAdapter;
}
public static class ViewPagerAdapter extends FragmentStatePagerAdapter {
private static final String KEY_TITLE = "fragment_title";
private static final String KEY_FRAGMENT = "fragment";
boolean abc = false;
private int[] drawables = new int[]{R.drawable.advisory_selector, R.drawable.top_advisors_selector, R.drawable.expertview_selector};
private List<Map<String, Object>> maps = new ArrayList<>();
private Fragment mCurrentFragment;
SparseArray<Fragment> registeredFragments = new SparseArray<Fragment>();
public ViewPagerAdapter(FragmentManager fm) {
super(fm);
}
public View getCustomeView(Context context, int pos) {
View mView = LayoutInflater.from(context).inflate(R.layout.custom_tab_view, null);
TextView mTextView = (TextView) mView.findViewById(R.id.textView);
mTextView.setTypeface(Typeface.createFromAsset(context.getAssets(), "fonts/ufonts.com_cambria.ttf"));
ImageView mImageView = (ImageView) mView.findViewById(R.id.imageView2);
mImageView.setTag(pos);
/*if(count >0)
{
Toast.makeText(context,"Count Is "+count,Toast.LENGTH_SHORT).show();
mImageView = (ImageView) mImageView.getTag(0);
mImageView.setSelected(false);
}
*/
mImageView.setImageResource(drawables[pos]);
mTextView.setText(getPageTitle(pos));
return mView;
}
public void addFragmentAndTitle(Map<String, Object> map) {
maps.add(map);
}
#Override
public CharSequence getPageTitle(int position) {
return (CharSequence) maps.get(position).get(KEY_TITLE);
}
#Override
public Fragment getItem(int position) {
Log.e("Fragmentss", (Fragment) maps.get(position).get(KEY_FRAGMENT) + "");
return (Fragment) maps.get(position).get(KEY_FRAGMENT);
}
public Fragment getCurrentFragment() {
return mCurrentFragment;
}
#Override
public void setPrimaryItem(ViewGroup container, int position, Object object) {
if (mCurrentFragment != object) {
mCurrentFragment = (Fragment) object;
}
super.setPrimaryItem(container, position, object);
}
#Override
public int getCount() {
return maps.size();
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
Fragment fragment = (Fragment) super.instantiateItem(container, position);
registeredFragments.put(position, fragment);
return fragment;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
registeredFragments.remove(position);
super.destroyItem(container, position, object);
}
public Fragment getRegisteredFragment(int position) {
return registeredFragments.get(position);
}
}
}

Refresh SlidingTabLayout

Examples in pictures:
Empty PagerView
PagerView with new content(SlidingTabLayout doesn't update)
New instance of view(SlidingTabLayout updated);
This is my code:
public class CharSortFragment extends Fragment {
private final String TAG = "CharSortFragment";
private ViewPager viewPager;
private TabsPagerAdapter tabsAdapter;
private SlidingTabLayout slidingTabLayout;
private FragmentActivity activity;
public CharSortFragment() {}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
Log.d(TAG, "OnCreate view...");
final View view = inflater.inflate(R.layout.char_sort_fragment, container, false);
activity = getActivity();
Log.d(TAG, "Init add button...");
FloatingActionButton addButton = (FloatingActionButton) view.findViewById(R.id.add_button);
addButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d(TAG, "Add button was clicked...");
startActivityForResult(new Intent(getActivity(), EditActivity.class), 1);
}
});
viewPager = (ViewPager) view.findViewById(R.id.pager);
tabsAdapter = new TabsPagerAdapter(activity.getSupportFragmentManager());
viewPager.setAdapter(tabsAdapter);
Log.d(TAG, "Connecting PagerSlidingTabStrip...");
slidingTabLayout = (SlidingTabLayout) view.findViewById(R.id.tabs);
slidingTabLayout.setViewPager(viewPager);
Log.d(TAG, "OnCreate finished!");
return view;
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
Log.d(TAG, "On activity result: " + resultCode);
if(resultCode == 1) {
Log.d(TAG, "Notify data changes...");
tabsAdapter.updateCharSet();
tabsAdapter.notifyDataSetChanged();
slidingTabLayout.invalidate();
CardListFragment cardListFragment = tabsAdapter.currentFragment;
/* Обновляем TabsAdapter всегда, ибо я ленивая жопа
if(tabsAdapter.currentFragment == null) {
tabsAdapter.updateCharSet();
tabsAdapter.notifyDataSetChanged();
cardListFragment = tabsAdapter.currentFragment;
}
*/
RecyclerViewAdapter recyclerViewAdapter = cardListFragment.getAdapter();
recyclerViewAdapter.updateDataSet();
recyclerViewAdapter.notifyDataSetChanged();
Log.d(TAG, "Views was notified!");
}
}
public class TabsPagerAdapter extends FragmentPagerAdapter {
private final String TAG = "TabsPagerAdapter";
private final HashSet<TongueTwister> data = TongueTwistersStorageManager.getInstance().getData();
private final ArrayList<Character> characters = new ArrayList<>();
private CardListFragment currentFragment;
public TabsPagerAdapter(FragmentManager fm) {
super(fm);
Log.i(TAG, "Creating TabsPagerAdapter...");
updateCharSet();
}
#Override
public Fragment getItem(int position) {
char charAtCurrentPos = characters.get(position);
return CardListFragment.newInstance(charAtCurrentPos);
}
protected void updateCharSet() {
this.characters.clear();
this.characters.addAll(generateCharList());
}
private ArrayList<Character> generateCharList() {
Log.i(TAG, "Generating char list...");
Log.i(TAG, "Total tongue twisters: " + data.size());
HashSet<Character> hashCharacters = new HashSet<>();
for (TongueTwister tongueTwister : data) {
for(char character : tongueTwister.getCharacters()) {
if(!hashCharacters.contains(character)) {
Log.i(TAG, "Char: " + character);
hashCharacters.add(character);
}
}
}
Log.i(TAG, "Sorting...");
ArrayList<Character> characters = new ArrayList<>(hashCharacters);
Collections.sort(characters);
Log.i(TAG, "Char list was generated!");
return characters;
}
#Override
public int getCount() {
return characters.size();
}
#Override
public CharSequence getPageTitle(int position) {
return String.valueOf(characters.get(position));
}
#Override
public void setPrimaryItem(ViewGroup container, int position, Object object) {
currentFragment = (CardListFragment) object;
}
}
}
How can i refresh SlidingTabLayout? (slidingTabLayout.invalidate() doesn't works for me)
Found the solution!
Just set ViewPager after you update its adapter:
tabsAdapter.updateCharSet(); // Updating FragmentPagerAdapter
tabsAdapter.notifyDataSetChanged();
slidingTabLayout.setViewPager(viewPager); // Updating SlidingTabStrip

Viewpager adapter in android

Why does my pager adapter doesn't want to start from my first item. When I start ContainerIspiti activity, and show first fragment, the view pager dones't show the right element. Insted of first, view pager shows the second element, and I can't to swipe to first element of my array list. Does anybody have solution.
Here is my code for ConainterIspiti
public class ContainerIspiti extends FragmentActivity{
private Button next, previous, odgovori, informacije;
private TextView textPitanja, brojPitanja;
private ViewPager pager;
private PagerAdapter mPagerAdapter;
public static ArrayList<Pitanja> getAllPitanja;
public static ArrayList<Pitanje_has_Slika> getAllImages;
private Intent intent;
private DBTools db = new DBTools(this);
private ProgressDialog pDialog;
private int broj;
#Override
protected void onCreate(Bundle arg0) {
super.onCreate(arg0);
setContentView(R.layout.activity_container_pitanja);
Bundle bundle = new Bundle();
intent = getIntent();
Dohvati d = new Dohvati();
d.execute();
textPitanja = (TextView) findViewById(R.id.kategorijaTextViewPitanjeActivity);
brojPitanja = (TextView) findViewById(R.id.brojPitanjaTextViewPitanjeActivity);
pager = (ViewPager) findViewById(R.id.pagerPitanja);
pager.setCurrentItem(0, true);
bundle.putString("NAZIV_KATEGORIJE", intent.getStringExtra("NAZIV_KATEGORIJE"));
}
private class ScreenSlidePagerAdapter extends FragmentStatePagerAdapter {
public ScreenSlidePagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
Log.i("Position je sljedeci ", String.valueOf(position));
return PitanjaFragment.create(position);
}
#Override
public int getCount() {
Log.i("Velicina polja je ", String.valueOf(getAllPitanja.size()));
Log.i("Prvi eleemnt liste je", getAllPitanja.get(0).getTextPitanja());
return getAllPitanja.size();
}
}
private class Dohvati extends AsyncTask<String, String, String>{
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(ContainerIspiti.this);
pDialog.setCancelable(false);
pDialog.setIndeterminate(false);
pDialog.show();
}
#Override
protected String doInBackground(String... params) {
getAllPitanja = db
.getAllPitanja(intent.getStringExtra("id_kategorije"));
Log.i("Ovoliki je get all pitanja", String.valueOf(getAllPitanja.size()));
getAllImages = db.getAllPitanjaImages();
Log.i("ovoliko je slika", String.valueOf(getAllImages.size()));
return null;
}
#Override
protected void onPostExecute(String result) {
pDialog.dismiss();
mPagerAdapter = new ScreenSlidePagerAdapter(getSupportFragmentManager());
pager.setAdapter(mPagerAdapter);
pager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener(){
#Override
public void onPageSelected(int position) {
invalidateOptionsMenu();
brojPitanja.setText(String.valueOf(position) + "/" + String.valueOf(getAllPitanja.size()));
broj = position;
}
});
textPitanja.setText(intent.getStringExtra("NAZIV_KATEGORIJE"));
brojPitanja.setText(String.valueOf(broj) + "/" + getAllPitanja.size());
}
}
}
and here is my fragment activity
public class PitanjaFragment extends Fragment implements API{
public static final String ARG_PAGE = "page";
private int broj;
private ImageView image;
private TextView textPitanja;
private String uri;
private View view;
private ListView listView;
private Typeface custom_font;
private boolean odgovoreno, tocno;
private ArrayList<Odgovor> odgovorList;
private PitanjaAdapter adapter;
private DBTools db;
private List<Integer> kliknuti;
private HashMap<Integer, List<Integer>> odgBrojPitanja;
public static PitanjaFragment create(int pageNumber) {
PitanjaFragment fragment = new PitanjaFragment();
Bundle args = new Bundle();
args.putInt(ARG_PAGE, pageNumber);
fragment.setArguments(args);
return fragment;
}
public PitanjaFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
broj = getArguments().getInt(ARG_PAGE);
}
#Override
public View onCreateView(LayoutInflater inflater,
#Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
// TODO Auto-generated method stub
View view = inflater.inflate(R.layout.fragment_pitanja, container, false);
image = (ImageView) view.findViewById(R.id.imageSlikaImageView);
image.setOnClickListener(this);
textPitanja = (TextView) view.findViewById(R.id.textPitanjaTextViewPitanjaActivity);
db = new DBTools(getActivity());
listView = (ListView) view.findViewById(R.id.listView);
updateDisplay((broj+1));
return view;
}
public void updateDisplay(int z) {
odgovoreno = false;
tocno = true;
textPitanja.setText(stripHtml(String.valueOf(ContainerIspiti.getAllPitanja.get(z).getTextPitanja())));
image.setImageBitmap(null);
//info = ContainerIspiti.getAllPitanja.get(z).getInfo();
Log.d("Postoji", ContainerIspiti.getAllImages.get(z).getNazivSlike() + ", ");
for (int j = 0; j < ContainerIspiti.getAllImages.size(); j++) {
if (ContainerIspiti.getAllImages.get(j).getIdPitanja() == ContainerIspiti.getAllPitanja.get(z)
.getIdPitanja()
&& ContainerIspiti.getAllImages.get(j).getNazivSlike() != null) {
Log.i("Id pitanja slike + idpitanja pitanja + idSlike",
ContainerIspiti.getAllImages.get(j).getIdPitanja()
+ ", "
+ String.valueOf(ContainerIspiti.getAllPitanja.get(z)
.getIdPitanja()
+ ", "
+ ContainerIspiti.getAllImages.get(j).getIdSlika()));
image.setVisibility(View.VISIBLE);
//povecalo.setImageResource(R.drawable.gumb_pretrazi);
//povecalo.setEnabled(true);
uri = PregledZnakova.PHOTOS_BASE_URL
+ ContainerIspiti.getAllImages.get(j).getNazivSlike();
int rounded_value = 40;
DisplayImageOptions options = new DisplayImageOptions.Builder().showImageForEmptyUri(R.drawable.placeholder).showStubImage(R.drawable.placeholder).cacheInMemory().cacheOnDisc().displayer(new RoundedBitmapDisplayer(rounded_value)).build();
ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(getActivity().getApplicationContext()).defaultDisplayImageOptions(options).build();
ImageLoader.getInstance().init(config);
ImageLoader.getInstance().displayImage(uri, image,options);
break;
// }
} else {
image.setVisibility(View.GONE);
//povecalo.setImageResource(R.drawable.gumb_pretrazi_neaktivno);
//povecalo.setEnabled(false);
}
}
odgovorList = db.getAllOdgovore(Integer.toString(ContainerIspiti.getAllPitanja.get(z)
.getIdPitanja()));
adapter = new PitanjaAdapter(getActivity(),
R.layout.pitanja_entry, odgovorList);
listView.setAdapter(adapter);
for (int i=0;i<ContainerIspiti.getAllPitanja.size();i++){
if (ContainerIspiti.getAllPitanja.get(i).isTocno()){
Log.i("Ovo pitanje je tocno", ContainerIspiti.getAllPitanja.get(i).getTextPitanja());
}
}
}
#Override
public int getItemBroj() {
return broj;
}
#Override
public int getPosition() {
return broj;
}
#Override
public void setPosition(int position) {
this.broj = position;
}
#Override
public Fragment getFragment() {
return this;
}
}
Thanks for your time and your help.
In the onCreateView() method of your PitanjaFragment class, replace:
updateDisplay((broj+1));
with
updateDisplay(broj);
Try this. It should work.

viewpager with images works but on back button images don't show

I have a viewpager with image fragments in it that works but on back was getting an error saying that there is no empty constructor. I made one but now my images don't show up because imageResourceId is null. I've tried a million things and can't figure it out.
public final class TestFragment extends Fragment {
String imageResourceId;
public TestFragment() {
}
public TestFragment(String cONTENT) {
imageResourceId = cONTENT;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
ImageView image = new ImageView(getActivity());
new DownloadImageTask((ImageView) image).execute(imageResourceId);
LinearLayout layout = new LinearLayout(getActivity());
layout.setGravity(Gravity.CENTER);
layout.addView(image);
return layout;
}
}
class TestFragmentAdapter extends FragmentPagerAdapter implements
IconPagerAdapter {
public String[] CONTENT;
private int mCount;
protected static final int[] ICONS = new int[] {
R.drawable.perm_group_calendar, R.drawable.perm_group_camera,
R.drawable.perm_group_device_alarms, R.drawable.perm_group_location };
public TestFragmentAdapter(FragmentManager fm, JSONArray photoData) {
super(fm);
// photoData = (JSONArray) userProfile.get("photos");
CONTENT = new String[photoData.length()];
mCount = photoData.length();
for (int i = 0; i < photoData.length(); i++) {
JSONObject mainPhoto;
try {
mainPhoto = photoData.getJSONObject(i);
CONTENT[i] = mainPhoto.getString("src_big");
} catch (JSONException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
notifyDataSetChanged();
}
#Override
public Fragment getItem(int position) {
return new TestFragment(CONTENT[position]);
}
#Override
public int getCount() {
return mCount;
}
#Override
public int getIconResId(int index) {
return ICONS[index % ICONS.length];
}
public void setCount(int count) {
if (count > 0 && count <= 10) {
mCount = count;
notifyDataSetChanged();
}
}
in the activity
mAdapter = new TestFragmentAdapter(
getSupportFragmentManager(), photoData);
mPager = (ViewPager) findViewById(R.id.pager);
mPager.setAdapter(mAdapter);
mIndicator = (LinePageIndicator) findViewById(R.id.indicator);
mIndicator.setViewPager(mPager);
Android uses the empty constructor of a fragment to restore the fragment when there is a configuration change, that's why you can't modify it, and you can't override it because you get an error in eclipse. The best practice to pass arguments to a fragment, when instantiating it, is to use an static factory method:
public class TestFragment extends Fragment {
String imageResourceId;
public static TestFragment newInstance(String resource) {
TestFragment f = new TestFragment();
Bundle args = new Bundle();
args.putString("Resource", resource);
f.setArguments(args);
return f;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
imageResourceId = getArguments().getString("Resource");
}
}
To instanciate it you use the static method:
TestFragment fragment = TestFragment.newInstance("some string");

Show new page in ViewPager

I'm having a ViewPager with a FragmentStatePagerAdapter that shows items from a ContentProvider via a CursorAdapter. So there is a callback when data is changed in the content provider that automatically creates/removes pages.
When I create a new item via ContentResolver.insert() from another fragment I want to show the created page in the ViewPager.
To show a page I call ViewPager.setCurrentItem(). But it seems that directly after the insert call the ViewPager is not yet updated. When and where do I call that?
Edit:
Here is my MainActivity:
I'm having one fragment for creation of items (on position 0) and several items from the content provider. From the creation fragment I call insert on the content resolver.
public class MainActivity extends FragmentActivity implements
LoaderManager.LoaderCallbacks<Cursor> {
SectionsPagerAdapter mSectionsPagerAdapter;
SimpleCursorAdapter mCommitmentAdapter;
private static final byte LOADER_ID = 0;
private static final String TAG = MainActivity.class.getName();
ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Adapter for commitment names and ids
mCommitmentAdapter = new SimpleCursorAdapter(this,
android.R.layout.simple_dropdown_item_1line, null,
new String[] { Commitment.Columns.NAME },
new int[] { android.R.id.text1 }, 0);
// Adapter for the saved commitments
mSectionsPagerAdapter = new SectionsPagerAdapter(
getSupportFragmentManager(), mCommitmentAdapter);
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mSectionsPagerAdapter);
getSupportLoaderManager().initLoader(LOADER_ID, null, this);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public final Loader<Cursor> onCreateLoader(int id, final Bundle args) {
....
}
#Override
public final void onLoadFinished(Loader<Cursor> loader, Cursor cursor) {
mCommitmentAdapter.swapCursor(cursor);
}
#Override
public final void onLoaderReset(Loader<Cursor> loader) {
mCommitmentAdapter.swapCursor(null);
}
public final void showPageWithCommitmentId(long id) {
// this is called after contentresolver.insert
// but it does not work
mViewPager.setCurrentItem(mSectionsPagerAdapter.getItemPosition(id));
}
#Override
protected void onDestroy() {
if (mSectionsPagerAdapter != null) {
mSectionsPagerAdapter.destroy();
}
getLoaderManager().destroyLoader(LOADER_ID);
super.onDestroy();
}
public class SectionsPagerAdapter extends FragmentStatePagerAdapter {
final CursorAdapter wrappedAdapter;
final DataSetObserver subObserver;
public SectionsPagerAdapter(FragmentManager fm,
SimpleCursorAdapter adapter) {
super(fm);
this.wrappedAdapter = adapter;
subObserver = new DataSetObserver() {
#Override
public void onChanged() {
notifyDataSetChanged();
}
#Override
public void onInvalidated() {
// Probably destroying the loader
}
};
if (wrappedAdapter != null)
wrappedAdapter.registerDataSetObserver(subObserver);
}
public void destroy() {
if (wrappedAdapter != null) {
wrappedAdapter.unregisterDataSetObserver(subObserver);
}
}
#Override
public Fragment getItem(int position) {
if (position == 0) {
Fragment fragment = CreateCommitmentSectionFragment
.getInstance(position);
return fragment;
} else {
// create new ShowCommitSectionFragment
Fragment fragment = ShowCommitmentSectionFragment.getInstance(
getItemId(position), getPageTitle(position).toString());
return fragment;
}
}
public long getItemId(int position) {
long id = 0;
if (wrappedAdapter != null && position > 0) {
Cursor c = (Cursor) wrappedAdapter.getItem(position - 1);
if (c != null && !c.isAfterLast() && !c.isBeforeFirst()) {
id = c.getLong(0);
}
}
return id;
}
#Override
public int getCount() {
if (wrappedAdapter != null)
return 1 + wrappedAdapter.getCount();
else
return 1;
}
#Override
public CharSequence getPageTitle(int position) {
if (position >= getCount())
return null;
if (position == 0) {
return MainActivity.this.getString(R.string.main_create_create);
}
Cursor c = (Cursor) wrappedAdapter.getItem(position - 1);
if (c != null && !c.isAfterLast() && !c.isBeforeFirst()) {
return c.getString(1);
}
return null;
}
#Override
public int getItemPosition(Object object) {
Fragment f = (Fragment) object;
long listId = 0;
if (f instanceof ShowCommitmentSectionFragment) {
listId = f.getArguments().getLong(
ShowCommitmentSectionFragment.ARG_COMMITMENT_ID);
}
return getItemPosition(listId);
}
/**
* Get the position of the given commitment id.
*
* #param commitmentId
* #return
*/
public int getItemPosition(final long commitmentId) {
int length = getCount();
int result = POSITION_NONE;
int position;
for (position = 0; position < length; position++) {
if (commitmentId == getItemId(position)) {
result = position;
break;
}
}
return result;
}
}
}

Categories

Resources