Tabs with Fragment life cycle - java

in my app i have a Tabs with fragment classes. i trying to refresh listView in "fragment a" with the new data i insert.
In "fragment b" i have EditText and Button ,that inserting text to the database.
in "fragment a" i have the ListView with the dataBase rows. when "fragment a" is "OnCreateView" i just put the dataBase on a "ArrayList" and past it to my baseAdapter.
but "onCreateView" not refreshing my new data every time i get into the "fragment a" else i goes to "fragment c" and "onDestroy" call on "fragment a".
so my result it was to call : "setUserVisibleHint" override method, and check if it is visible and refreshing the list.
but i dont think it is the good practice .
what should i do?
Class a
public class ListFragment extends Fragment{
basAdapterCustom adapter;
ListView lv;
ArrayList<Clock> list;
private DbHandler hand;
Context context;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.list_fragment, container, false);
context = getActivity();
Log.d(TAG, "onCreateView");
hand = new DbHandler(context);
list = new ArrayList<Clock>();
lv = (ListView) v.findViewById(R.id.listOfShifts);
adapter = new basAdapterCustom(list, getActivity());
lv.setAdapter(adapter);
refreshList();
return v;
}
//like on "resume":
#Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
// Make sure that we are currently visible
if (this.isVisible()) {
refreshList();
if (!isVisibleToUser) {
// TODO stop
}
}
}
private void refreshList() {
list = hand.getByWorkName();
adapter = new basAdapterCustom(list,getActivity());
lv.setAdapter(adapter);
}
class b:
public class ClockFragment extends Fragment{
DbHandler hand;
Context context;
#Override
public View onCreateView(LayoutInflater inflater,
#Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.clock, container,false);
context = getActivity();
hand = new DbHandler(context);
return v;
}
// ADD to .Db
public void addToDb(View v){
hand.add(new Clock(0, dateDay));
}
}
class mainActivity:
public class MainActivity extends FragmentActivity implements ActionBar.TabListener, OnPageChangeListener{
public static final String TAG = "myClock";
String[] tabMenu = {"FRAG A","FRAG B","FRAG C"};
private ViewPager viewPager;
private TabPagerAdapter mAdapter;
private ActionBar actionBar;
#SuppressLint("NewApi")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d(MainActivity.TAG, "OnCreate = MainActivity (Pager");
viewPager = (ViewPager) findViewById(R.id.pager );
actionBar = getActionBar();
mAdapter = new TabPagerAdapter(getSupportFragmentManager());
viewPager.setAdapter(mAdapter);
actionBar.setHomeButtonEnabled(false);
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
for (String tabsNames : tabMenu) {
actionBar.addTab(actionBar.newTab().setText(tabsNames).setTabListener(this));
}
viewPager.setOnPageChangeListener(this);
}
// public void transDialog(){
// Dialog mDialog = new Dialog(this, android.R.style.Theme_Translucent_NoTitleBar_Fullscreen);
// }
#Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
// TODO Auto-generated method stub
}
#Override
public void onTabReselected(Tab tab, FragmentTransaction ft) {
}
#Override
public void onPageScrollStateChanged(int arg0) {
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
}
#Override
public void onPageSelected(int position) {
actionBar.setSelectedNavigationItem(position);
}
}
PagetAdapter.class
public class TabPagerAdapter extends FragmentPagerAdapter {
private static final String TAG = "myClock";
public TabPagerAdapter(FragmentManager fm) {
super(fm);
// TODO Auto-generated constructor stub
}
#Override
public Fragment getItem(int index) {
Log.d(TAG, " CLASS : TabPagerAdapter");
switch (index) {
case 0:
return new ListFragment();
case 1:
return new ClockFragment();
case 2:
return new SettingFragment();
default:
break;
}
Log.d(TAG, " CLASS : TabPagerAdapter = "+index);
return null;
}
#Override
public int getCount() {
return 3;
}
}
Please help me i hope you are understand my problem...

You want to update listView in fragment A, after insert data in fragment b? Then  you have a few solutions to choose:
1. Implement communications between fragments via activity. Then B insert date, it send message to activity, that data need to be updated. Then fragment A started, it's ask activity to need update data. For details on implementing this communication check link.
2. Use some bus library, EventBus for example. Then fragment B insert data, it post 'data changed' event to bus. Fragment A checks on start if this event occurs.
3. Use Loaders which "monitor the source of their data and deliver new results when the content changes."

Related

How do I use back stack or get getChildFragmentManager() with this specific pager adapter in order to use the back button?

I'm using Fragments to change scenes in my application, and I've come across the problem where when the phone back button is pressed, the application closes. How would I make it so when the back button is pressed, the previous fragment opens.
I searched for solutions and there are quite a few like using getChildFragmentManager or back stack. I just don't know how to implement it for my specific state pager adapter, of which I followed a youtube video tutorial for.
SectionsStatePagerAdapter.java:
public class SectionsStatePagerAdapter extends FragmentStatePagerAdapter {
private final ArrayList<Fragment> mFragmentList = new ArrayList<>();
private final ArrayList<String> mFragmentTitleList = new ArrayList<>();
public SectionsStatePagerAdapter(#NonNull FragmentManager fm, int behavior) {
super(fm, behavior);
}
public SectionsStatePagerAdapter(FragmentManager supportFragmentManager) {
super(supportFragmentManager);
}
public void addFragment(Fragment fragment, String title){
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
#NonNull
#Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
#Override
public int getCount() {
return mFragmentList.size();
}
}
MainActivity.java:
public class MainActivity extends AppCompatActivity implements MyRecyclerViewAdapter.ItemClickListener {
public SectionsStatePagerAdapter mSectionsStatePagerAdapter;
private ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
//Fragment Stuff:
mSectionsStatePagerAdapter = new SectionsStatePagerAdapter(getSupportFragmentManager());
mViewPager = findViewById(R.id.container);
//SetUpPager:
setupViewPager(mViewPager);
}
private void setupViewPager(ViewPager viewPager){
SectionsStatePagerAdapter adapter = new SectionsStatePagerAdapter(getSupportFragmentManager());
adapter.addFragment(new MainPageFragment(),"MainPage"); //0
adapter.addFragment(new CoffeePageFragment(),"CoffeePage"); //1
adapter.addFragment(new RegularCoffeeFragment(),"RegularCoffeePage"); //2
viewPager.setAdapter(adapter);
}
public void setViewPager(int fragmentNumber){
mViewPager.setCurrentItem(fragmentNumber);
}
}
CoffeePageFragment.java:
public class CoffeePageFragment extends Fragment {
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.content_coffee_page,container,false);
btnRegularCoffee = view.findViewById(R.id.regular_coffee_button);
btnRegularCoffee.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
((MainActivity)getActivity()).setViewPager(2);
}
});
return (view);
}
}
In conclusion, how do I make it so when the device back button is pressed, it will go back to the previous fragment?
In previous versions of the AppCompatActivity implementation it was enough to override onBackPressed() in your activity, newer versions dictate to implement the OnBackPressedCallback, like shown here: https://developer.android.com/reference/androidx/activity/OnBackPressedDispatcher.html
public class FormEntryFragment extends Fragment {
#Override
public void onAttach(#NonNull Context context) {
super.onAttach(context);
OnBackPressedCallback callback = new OnBackPressedCallback(
true // default to enabled
) {
#Override
public void handleOnBackPressed() {
showAreYouSureDialog();
}
};
requireActivity().getOnBackPressedDispatcher().addCallback(
this, // LifecycleOwner
callback);
}
}
It might still be ok to use onBackPressed on the Activity level, though.

Modify Fragment's views from MainActivity

I am trying to implement swipe views with android. I am using a ViewPager with two tabs containing fragments. In my onCreate() method, I am trying to read from a sharedPrefferences and according to what i am getting, i want to change text and visibility to some child views of the parent view of the first fragment. Unfortunately i am always getting NullPointerException when i am trying to access fragments views.
My sample code from the one of the two fragments is given below. Could you please help me ? Is there a better way to do so?
MainActivity:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
actionBar = getActionBar();
context = getApplicationContext();
myTabPagerAdapter = new TabPagerAdapter(getSupportFragmentManager());
myViewPager = (ViewPager) findViewById(R.id.pager);
myViewPager.setAdapter(myTabPagerAdapter);
myViewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
Toast.makeText(MainActivity.this, "Selected page position: " + position, Toast.LENGTH_SHORT).show();
getActionBar().setSelectedNavigationItem(position);
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
ActionBar.TabListener tabListener = new ActionBar.TabListener() {
#Override
public void onTabReselected(android.app.ActionBar.Tab tab, FragmentTransaction ft) {
// TODO Auto-generated method stub
}
#Override
public void onTabSelected(ActionBar.Tab tab, FragmentTransaction ft) {
myViewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(android.app.ActionBar.Tab tab, FragmentTransaction ft) {
// TODO Auto-generated method stub
}
};
actionBar.addTab(actionBar.newTab().setText("Spot Position").setTabListener(tabListener));
actionBar.addTab(actionBar.newTab().setText("Track Vehicle").setTabListener(tabListener));
//Get saved latitude and longitude from sharedPreferences
sharedPref = context.getSharedPreferences("net.ddns.drimou.bachelorthesis", Context.MODE_PRIVATE);
editor = sharedPref.edit();
}
#Override
protected void onStart() {
super.onStart();
getSharedPreferencesOnStart();
}
public void getSharedPreferencesOnStart() {
String s = myTabPagerAdapter.makeFragmentName(myViewPager.getId(),myViewPager.getCurrentItem());
SpotPosition sp = (SpotPosition) myTabPagerAdapter.getItem(0);
sp.setSettings();//In this call i am getting null pointer
...}
Fragment A
public class SpotPosition extends Fragment {
TextView locationTextView;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View spotPosition = inflater.inflate(R.layout.spot_position, container, false);
return spotPosition;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
public void setSettings(){
locationTextView = (TextView) myView.findViewById(R.id.mainTextView);//NullPointerException here
locationTextView.setVisibility(View.VISIBLE);
locationTextView.setText("Hello");
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public void onDestroyView() {
super.onDestroyView();
}
TabPagerAdapter
public class TabPagerAdapter extends FragmentPagerAdapter {
SparseArray<Fragment> registeredFragments = new SparseArray<Fragment>();
private View mCurrentView;
private SpotPosition sp = null;
private static int NUM_ITEMS = 2;
public TabPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int i) {
switch (i) {
case 0:
//Fragment for SpotPosition myViewPager
return new SpotPosition();
case 1:
//Fragment for TrackVehicle myViewPager
return new TrackVehicle();
}
return null;
}
#Override
public int getCount() {
return NUM_ITEMS; //Number of Tabs
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
Fragment fragment = (Fragment) super.instantiateItem(container, position);
registeredFragments.put(position, fragment);
return fragment;
}
#Override
public void setPrimaryItem(ViewGroup container, int position, Object object) {
sp = (SpotPosition)object;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
registeredFragments.remove(position);
super.destroyItem(container, position, object);
}
#Override
public CharSequence getPageTitle(int position) {
switch(position) {
case 0:
return "Spot Position";
case 1:
return "Track Vehicle";
default:
return null;
}
}
public String makeFragmentName(int viewId, int index) {
return "android:switcher:" + viewId + ":" + index;
}
public Fragment getRegisteredFragment(int position) {
return registeredFragments.get(position);
}
#Override
public int getItemPosition(Object object) {
return POSITION_NONE;
}
public View getCurrentView(){
return this.mCurrentView;
}
public SpotPosition getCurrentSpotPosition(){
return this.sp;
}
Feel free to ask if something is not understood. Thank you
As far as I understand you call setSettings from you activity, to change views in you fragment. You did not provide stacktrace and i assume you problem - attempt to change view after onPause was called in offcreen fragment. There are several ways to deal with it.
First of all dont call to views dirrectly.
On activity
public void getSharedPreferencesOnStart() {
String s = myTabPagerAdapter.makeFragmentName(myViewPager.getId(),myViewPager.getCurrentItem());
SpotPosition sp = (SpotPosition) myTabPagerAdapter.getItem(0);
// sp.setSettings();//In this call i am getting null pointer
SharedPreferences prefs = getSharedPreferences("message",MODE_PRIVATE);
Editor editor = prefs.edit();
editor.putBoolean("say_hello",true")
editor.commit();
...}
in fragments
#Override
public void onResume(){
super.onResume();
SharedPreferences prefs =
getActivity().getSharedPreferences("message", Context.MODE_PRIVATE);
{
//this block is used for offsreen fragment, it will get update, when it go to forescreen
boolean sayHello = prefs.getBoolean("say_hello", false);
if(sayHello){
locationTextView =
(TextView) myView.findViewById(R.id.mainTextView);//NullPointerException here
locationTextView.setVisibility(View.VISIBLE);
locationTextView.setText("Hello");
}else{
// say something elese
}
}
{
//this listener is for forescreen fragment, as soon as shared preferences will be updated,
// listerner willbe called and you can update your view depending on changed parameters
prefs.registerOnSharedPreferenceChangeListener(
new OnSharedPreferenceChangeListener(){
#Override
public void onSharedPreferenceChanged(
SharedPreferences sharedPreferences, String key
){
if(key.equals("say_hello")){
boolean sayHello = sharedPreferences.getBoolean("say_hello", false);
if(sayHello){
locationTextView =
(TextView) myView.findViewById(R.id.mainTextView);//NullPointerException here
locationTextView.setVisibility(View.VISIBLE);
locationTextView.setText("Hello");
}else{
// say something elese
}
}
}
}
);
}
}
You also can use Otto bus it is still unsutable for activity to fragment communication, as fragment can be in !isResumed state, but it is usefull fro fragment -activity comunication.
If you need some complex state tracking for each fragment and activity separatly, I'd recomment to use sqlDatabase and CursorLoaders. It will give you good controll over states and instan comunication.
Edit:
Its not that you cannot pass view from fragment to activity with getters.
Problem - you cannot garanty, that you completly aware of state of the fragment and a view. You try to update views on onStart of activity, which is call earlier, then fragmentsonStart, because fragment have to be generated by adapter and go through attachement process. (to find yout if fragment is attached to activity, you have to set listener in activity and call it ononActivityAttached` of fragment. See android studio activity with fragment template). Thus, when you call to change views, fragment and views probably did not exist.
Futhermore you should read about fragment and activity lifecycle and read about context ( espesialy why strong referencing views in unrelated context holder lead to sever memmory leaks and lificle errors

How to reload fragment or refresh fragment on TabReselected Using ActionBar Tabs

DESCRIPTION::
There is a ActionBarTab(3-tab) setup, We are linking three fragments
for each Action-Tab, Each fragment contains a listview
Whenever we are clicking Tab, we are sorting data.
In onTabReselect i am calling sort function using interface method,
without error it executes but its not refreshing the listview
MainActivity.java
public class MainActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Toast.makeText(this, DosUtils.ExecuteDOSCommand(), Toast.LENGTH_SHORT);
// Initialize
FindMyBuffetApplicationCls.initFindMyBuffetApplicationCls(MainActivity.this);
setContentView(R.layout.main_activity);
appContext = getApplicationContext();
//ActionBar
ActionBar actionbar = getActionBar();
actionbar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
ActionBar.Tab RatingTab = actionbar.newTab().setText(FindMyBuffetConstants.TAB_NAME_RATING);
ActionBar.Tab PriceTab = actionbar.newTab().setText(FindMyBuffetConstants.SORT_BY_PRICE);
ActionBar.Tab DistanceTab = actionbar.newTab().setText(FindMyBuffetConstants.SORT_BY_DISTANCE);
Fragment SortRestFragmentByRating = new SortRestaurantRating();
Fragment SortRestFragmentByPrice = new SortRestaurantByPrice();
Fragment SortRestFragmentByDistance = new SortRestaurantByDistance();
RatingTab.setTabListener(new MyTabsListener(SortRestFragmentByRating));
PriceTab.setTabListener(new MyTabsListener(SortRestFragmentByPrice));
DistanceTab.setTabListener(new MyTabsListener(SortRestFragmentByDistance));
actionbar.addTab(RatingTab);
actionbar.addTab(PriceTab);
actionbar.addTab(DistanceTab);
FindMyBuffetApplicationCls.comm = (Communicator) new SortRestaurantByPrice();
}
class MyTabsListener implements ActionBar.TabListener {
public Fragment fragment;
public MyTabsListener(Fragment fragment) {
this.fragment = fragment;
}
#Override
public void onTabReselected(Tab tab, FragmentTransaction ft) {
if(tab.getText().toString()==FindMyBuffetConstants.TAB_NAME_RATING){
if(FindMyBuffetApplicationCls.isRatingOrderByDesc==false){
FindMyBuffetApplicationCls.isRatingOrderByDesc=true;
}
else {
FindMyBuffetApplicationCls.isRatingOrderByDesc=false;
}
}
if(tab.getText().toString()==FindMyBuffetConstants.SORT_BY_PRICE){
if(FindMyBuffetApplicationCls.isPriceOrderByDesc==false){
FindMyBuffetApplicationCls.isPriceOrderByDesc=true;
}
else {
FindMyBuffetApplicationCls.isPriceOrderByDesc=false;
}
FindMyBuffetApplicationCls.comm.RefreshFragment();
}
if(tab.getText().toString()==FindMyBuffetConstants.SORT_BY_DISTANCE){
if(FindMyBuffetApplicationCls.isDistanceOrderByDesc==false){
FindMyBuffetApplicationCls.isDistanceOrderByDesc=true;
}
else {
FindMyBuffetApplicationCls.isDistanceOrderByDesc=false;
}
}
}
#Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
ft.replace(R.id.main_container, fragment);
if(tab.getText().toString()==FindMyBuffetConstants.TAB_NAME_RATING){
if(FindMyBuffetApplicationCls.isRatingOrderByDesc==false)
FindMyBuffetApplicationCls.isRatingOrderByDesc=true;
else
FindMyBuffetApplicationCls.isRatingOrderByDesc=false;
}
if(tab.getText().toString()==FindMyBuffetConstants.SORT_BY_PRICE){
if(FindMyBuffetApplicationCls.isPriceOrderByDesc==false)
FindMyBuffetApplicationCls.isPriceOrderByDesc=true;
else
FindMyBuffetApplicationCls.isPriceOrderByDesc=false;
}
if(tab.getText().toString()==FindMyBuffetConstants.SORT_BY_DISTANCE){
if(FindMyBuffetApplicationCls.isDistanceOrderByDesc==false)
FindMyBuffetApplicationCls.isDistanceOrderByDesc=true;
else
FindMyBuffetApplicationCls.isDistanceOrderByDesc=false;
}
}
#Override
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
ft.remove(fragment);
Log.i("TEST TAB",tab.getText().toString());
}
}
SortRestaurantByPrice.java
public class SortRestaurantByPrice extends Fragment implements Communicator{
// Declaration
ListView xmlFragmentListView;
SortRestaurantListViewAdapter listViewAdapter;
View layout;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
layout = inflater.inflate(R.layout.sort_restaurant_by_price, container,false);
xmlFragmentListView = ((ListView) layout.findViewById(R.id.sortrestaurantbypricelistview));
return layout;
}
#Override
public void onDestroyView() {
super.onDestroyView();
//layout = null; // now cleaning up!
}
private void SortRestaurantList(String strSortBy)
throws Exception, TransformerConfigurationException,
TransformerException, FindMyBuffetException {
// Process the Main Screen Data
List<RestaurantDetails> lstRest = null;
lstRest = SAXXMLParser.parse(xmlInputStream);
SortRestaurantListViewAdapter listViewAdapter = new SortRestaurantListViewAdapter(lstRest);
xmlFragmentListView.setAdapter(listViewAdapter);
}
#Override
public void RefreshFragment() {
// TODO Auto-generated method stub
Log.i("hELLO", "refresh requested. Try to reload data for this fragment...");
SortRestaurantList("Price");
}
}
Communicator.java
public interface Communicator {
public void RefreshFragment();
}
Please call notifyDataChanged method on your list in the sortRestaurantList method.
private void SortRestaurantList(String strSortBy)
throws Exception, TransformerConfigurationException,
TransformerException, FindMyBuffetException {
// Process the Main Screen Data
List<RestaurantDetails> lstRest = null;
lstRest = SAXXMLParser.parse(xmlInputStream);
SortRestaurantListViewAdapter listViewAdapter = new SortRestaurantListViewAdapter(lstRest);
xmlFragmentListView.setAdapter(listViewAdapter);
listViewAdapter.notifyDataSetChanged(); // call this on Adapter
}
Infact move the adapter code in the onCreateView method. Only modify (sort) your List lstRest in the SortRestaurant method and after that call the notifyDataSetChanged method.

Why is my android.R.id.home not called in my fragment?

I'm currently using FragmentStatePagerAdapter and I would like it to have a "navigate up" feature (DisplayHomeAsUpEnabled). When I set the following code it shows up as a correct navigate back button. But nothing happens when I click on it, can you guys see anything that I', doing wrong in my code, I get no error while pressing the "navigate up" button and I get no compiler errors.
Here is the code, its in the "public boolean onOptionsItemSelected(MenuItem item) {" it gets interesting at the bottom.
public class ShareholdingDetailFragment extends FragmentActivity {
final int NUM_ITEMS = Portfolio.getPortfolio().count();
MyAdapter mAdapter;
ViewPager mPager;
Bundle extras;
#Override
protected void onCreate(Bundle savedInstanceState) {
System.out.println(NUM_ITEMS + "e");
super.onCreate(savedInstanceState);
setContentView(R.layout.shareholdingdetailview_fragment_wrapper);
mAdapter = new MyAdapter(getSupportFragmentManager());
mPager = (ViewPager)findViewById(R.id.pager);
mPager.setAdapter(mAdapter);
}
public class MyAdapter extends FragmentStatePagerAdapter {
public MyAdapter(FragmentManager fm) {
super(fm);
}
public int getCount() {
return NUM_ITEMS;
}
public Fragment getItem(int position) {
return ShareholdingFragment.newInstance(position);
}
}
public static class ShareholdingFragment extends Fragment {
int mNum;
static ShareholdingFragment newInstance(int num) {
ShareholdingFragment f = new ShareholdingFragment();
// Supply num input as an argument.
Bundle args = new Bundle();
args.putInt("num", num);
f.setArguments(args);
return f;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mNum = getArguments() != null ? getArguments().getInt("num") : 1;
}
#SuppressLint({ "NewApi", "NewApi" })
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.shareholdingdetailview_fragment, container, false);
/****************Setting the Display as home and it shows*******************/
ActionBar bar = getActivity().getActionBar();
bar.setDisplayHomeAsUpEnabled(true);
/**********************************/
return view;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home://Not working
System.out.println("test");//This isn't printed out
Intent upIntent = new Intent(getActivity(), DetailShareHoldingActivity.class);
if (NavUtils.shouldUpRecreateTask(getActivity(), upIntent)) {
getActivity().finish();
} else {
NavUtils.navigateUpTo(getActivity(), upIntent);
}
return true;
}
return super.onOptionsItemSelected(item);
}
}
}
Try adding: setHasOptionsMenu(true); in your onCreate() in ShareholdingFragment.
Add setHomeButtonEnabled(true) on API Level 14 and higher when you configure your action bar. On API Level 11-13, the home button is enabled automatically.
If you're using the new Toolbar and ActionbarDrawerToggle. You can assign clickHandler directly. For my activities that have this drawer toolbar I implemented an interface to enable drawer if at root,
#Override
public void enableDrawer(boolean enable) {
mDrawerToggle.setDrawerIndicatorEnabled(enable);
mDrawerToggle.setToolbarNavigationClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Pop fragment back stack or pass in a custom click handler from the fragment.
}
});
}

How do I update a ListView in a Fragment?

I´m trying to udate a ListView in a Fragment the only way it actually will work is if I instanciate the fragment new. adpter.notifyDataSetChanged() is not working? Whay not? Here the Code an Activity and the Fragment:
public class TimerList extends Activity{
private DataSource datasource;
TimerListFragment timerfragment;
IntervalListFragment intervalfragment;
public List<TimerObject> values;
public String name;
public String intervals;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.interval_fragment_container);
datasource = new DataSource(this);
datasource.open();
values = datasource.getAllComments();
if (savedInstanceState == null) {
Toast.makeText(getApplicationContext(), "MADE NEW FRAGMENTS", Toast.LENGTH_SHORT).show();
timerfragment = new TimerListFragment();
intervalfragment = new IntervalListFragment();
}
}
public void delete(Long position){
TimerObject timerobject = datasource.getTimerObject(position);
datasource.deleteComment(timerobject);
values = datasource.getAllComments();
}
#Override
protected void onStart() {
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.add(R.id.fragment_container, timerfragment);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
super.onStart();
}
And my Fragment :
public class TimerListFragment extends ListFragment {
List<TimerObject> values ;
Activity a;
ArrayAdapter<TimerObject> adapter;
ListView lv;
#Override
public void onCreate(Bundle savedInstanceState) {
setHasOptionsMenu(true);
values = ((TimerList)getActivity()).getValues();
setBar();
adapter = new ArrayAdapter<TimerObject>(getActivity(), android.R.layout.simple_list_item_1, values);
setListAdapter(adapter);
super.onCreate(savedInstanceState);
}
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
((TimerList)getActivity()).play(Long.valueOf(position));
super.onListItemClick(l, v, position, id);
}
public void setBar(){
ActionBar actionbar = getActivity().getActionBar();
actionbar.setTitle("Timer List");
}
public void update(){
setBar();
Toast.makeText(getActivity(), "UPDATE", Toast.LENGTH_LONG).show();
values = ((TimerList)getActivity()).getValues();
adapter.notifyDataSetChanged();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.interval_timer_list,
container, false);
return view;
}
#Override
public void onStart() {
update();
lv = getListView();
lv.setOnItemLongClickListener(new OnItemLongClickListener() {
public boolean onItemLongClick(AdapterView parent, View view, int position, long id) {
final TimerObject selected = adapter.getItem(position);
final Dialog d = new Dialog(getActivity());
d.setContentView(R.layout.interval_deletetimer_dialog);
d.setTitle("Delete " + selected.getComment() + "?" );
ImageButton delete = (ImageButton) d.findViewById(R.id.delete);
delete.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
((TimerList)getActivity()).delete(Long.valueOf(selected.getId()));
update();
}
});
d.show();
return true;
}
});
super.onStart();
}
I tried to do something similar, and I solved this problem by simply redoing the fragment transaction.
In your case, you could accomplish this within your onListItemClick() method.
you could copy this:
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.add(R.id.fragment_container, timerfragment);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
into your onListItemClick() method in your fragment
This resets the fragment. Unfortunately, this would also set your list to null. A way around this would be to make the values list a private static variable of the TimerListFragment class. That way, any changes made to the list will remain 'saved', and when you reload your fragment, it will be populated with the newly updated list.
hope this helps

Categories

Resources