In myfragment class witch extends Fragment I'm finding object reference in onCreateView method
private static final String TAG = "CloadLab";
private Cloud dCloud;
private EditText dNameText;
public String dNameHolder = "";
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
UUID dreamId = (UUID)getArguments().getSerializable(EXTRA_DREAM_ID);
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
getActivity().setTitle("Add new");
}
#Override
public View onCreateView(LayoutInflater inflater,
ViewGroup parent, Bundle savedInstanceState){
View v = inflater.inflate(R.layout.fragment_add,parent,false);
dNameText = (EditText) v.findViewById(R.id.dream_name);
return v;
}
public void SaveDream (){
dNameHolder = dNameText.getText().toString();
if (dNameText != null) {
Log.e(TAG,"not null");
}else if (dNameText == null){
Log.e(TAG,"null");
}
}
}
which works fine if I use it within onCreateView method, but for example I want to use dNameText in this method which is in same class
public void SaveDream (){
dNameHolder = dNameText.getText().toString();
}
and now it has null object reference how can I fix that and how can I set references through whole class?
I'm calling this SaveDream() method from Activity which holds this Fragment
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_favorite:
AddFragment mActivity= new AddFragment();
mActivity.SaveDream();
finish();
return true;
}
return super.onOptionsItemSelected(item);
}
Every Activity extends SingleFragmentActivity and has these methods in it
private AddFragment mFragment;
#Override
protected Fragment createFragment() {
UUID dreamId = (UUID)getIntent()
.getSerializableExtra(AddFragment.EXTRA_DREAM_ID);
return AddFragment.newInstance(dreamId);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
//setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.action_bar_menu,menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_favorite:
// AddFragment mActivity= new AddFragment();
// mActivity.SaveDream();
//finish();
mFragment = new AddFragment();
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(android.R.id.content, mFragment);
fragmentTransaction.commit();
mFragment.SaveDream();
finish();
return true;
}
return super.onOptionsItemSelected(item);
}
SingleFragmentActivity
protected abstract Fragment createFragment();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fragment);
FragmentManager fm = getSupportFragmentManager();
Fragment fragment = fm.findFragmentById(R.id.fragmentContainer);
// getSupportActionBar().setDisplayHomeAsUpEnabled(false);
if (fragment == null){
fragment = createFragment();
fm.beginTransaction()
.add(R.id.fragmentContainer, fragment)
.commit();
}
}
You are calling SaveDream method on a new instance of the fragment, not the one which is loaded right now at
AddFragment mActivity= new AddFragment();
mActivity.SaveDream();
Because the view is not created on the new instance (view is created while loading) and you are getting null for EditText. You should keep the loaded instance globally and call the method on that instance.
Follow these steps.
Step 1: Create a class level variable
private AddFragment mFragment;
Step 2: Load Fragment like this
mFragment = new AddFragment();
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(android.R.id.content, mFragment);
fragmentTransaction.commit();
Step 3: Call method like this
mFragment.SaveDream();
Update
Update method like this
#Override
protected Fragment createFragment() {
UUID dreamId = (UUID)getIntent()
.getSerializableExtra(AddFragment.EXTRA_DREAM_ID);
mFragment = AddFragment.newInstance(dreamId);
return mFragment;
}
and
case R.id.action_favorite:
mFragment.SaveDream();
return true;
Related
Working on an app that included 3 fragments. I want to retain data in the FragmentA when the user decides to switch back to FragmentA from FragmentB or FragmentC via BottomNavigationView.
My code works great with changing screen orientation, but for some reason it wont retain data on fragment change.
For testing, I've used only one EditText that should retain data from string.
MainActivity
public class MainActivity extends AppCompatActivity implements
BottomNavigationView.OnNavigationItemSelectedListener {
Fragment Frag = new Fragment();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
BottomNavigationView navigation = findViewById(R.id.navigation);
navigation.setOnNavigationItemSelectedListener(this); // mOnNavigationItemSelectedListener
if (savedInstanceState != null)
{
Frag = getSupportFragmentManager().getFragment(savedInstanceState, "Frag");
}
else
loadFragment(new FragmentA());
}
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem menuItem) {
Fragment fragment = null;
int i = menuItem.getItemId();
if (i == R.id.fragmentA) {
fragment = new FragmentA();
} else if (i == R.id.fragmentB) {
fragment = new FragmentB();
} else if (i == R.id.fragmentC) {
fragment = new FragmentC();
}
return loadFragment(fragment);
}
private boolean loadFragment(Fragment fragment)
{
if (fragment != null)
{
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, fragment).commit();
Frag = fragment;
return true;
}
return false;
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
getSupportFragmentManager().putFragment(outState, "Frag", Frag);
}
}
FragmentA
public class FragmentA extends Fragment {
EditText editText;
String string;
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (savedInstanceState != null)
{
string = savedInstanceState.getString("Text", "");
}
}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
// return super.onCreateView(inflater, container, savedInstanceState);
LayoutInflater layoutInflater = getActivity().getLayoutInflater();
View view = layoutInflater.inflate(R.layout.fragmentA, container, false);
editText = view.findViewById(R.id.centerText);
editText.setText(string);
return view;
}
#Override
public void onSaveInstanceState(#NonNull Bundle outState) {
super.onSaveInstanceState(outState);
string = editText.getText().toString();
outState.putString("Text", string);
}
}
I want that editText retains data when user switches back to FragmentA from FragmentB or FragmentC.
I've been struggling with this problem for some time now, trying different methods with no luck.
Either you can keep the references to your fragments, instead of creating new ones every time like you do here:
if (i == R.id.fragmentA) {
fragment = new FragmentA();
} else if (i == R.id.fragmentB) {
fragment = new FragmentB();
} else if (i == R.id.fragmentC) {
fragment = new FragmentC();
}
You could also use a ViewPager which allows you not only to swipe in-between the screens, but to set viewPager.setOffscreenPageLimit(i); which means that fragments will not be recreated unless they're too far off screen.
Here is your mistake
if (i == R.id.fragmentA) {
fragment = new FragmentA();
} else if (i == R.id.fragmentB) {
fragment = new FragmentB();
} else if (i == R.id.fragmentC) {
fragment = new FragmentC();
}
On click you create new fragment instance
Thank you for your replies.
This is what I changed. It is now working although I'm not sure if that's the elegant way to solve this problem. Data now retains in EditText while navigating back to FragmentA.
MainActivity
public class MainActivity extends AppCompatActivity implements
BottomNavigationView.OnNavigationItemSelectedListener {
Fragment Frag = new Fragment();
Fragment FragmentA;
Fragment FragmentB;
Fragment FragmentC;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
BottomNavigationView navigation = findViewById(R.id.navigation);
navigation.setOnNavigationItemSelectedListener(this); // mOnNavigationItemSelectedListener
FragmentA = new FragmentA();
FragmentB = new FragmentB();
FragmentC = new FragmentC();
if (savedInstanceState != null)
{
Frag = getSupportFragmentManager().getFragment(savedInstanceState, "Frag");
}
else
loadFragment(FragmentA);
}
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem menuItem) {
Fragment fragment = null;
int i = menuItem.getItemId();
if (i == R.id.fragmentA) {
fragment = FragmentA;
} else if (i == R.id.fragmentB) {
fragment = FragmentB;
} else if (i == R.id.fragmentC) {
fragment = FragmentC;
}
return loadFragment(fragment);
}
private boolean loadFragment(Fragment fragment)
{
if (fragment != null)
{
getSupportFragmentManager().beginTransaction().hide(FragmentA).commit();
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, fragment).commit();
getSupportFragmentManager().beginTransaction().show(fragment).commit();
Frag = fragment;
return true;
}
return false;
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
getSupportFragmentManager().putFragment(outState, "Frag", Frag);
}
}
In my MainActivity class, I have a BottomNavigationView with 3 tabs that switch between activities (home, search, and personal). Whenever I click on any of the tabs, it pulls up the respective fragment, but I believe that I am calling a new fragment each and every time.
I need these fragments to maintain whatever changes are made in them (similarly to how Instagram does). Each fragment is currently very basic (newly created and unchanged), but I want to set them up in a way in which their states are saved when I switch to another fragment and restored when I go back to them.
Below is code for my main activity and the home fragment.
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
BottomNavigationView navigationView = (BottomNavigationView) findViewById(R.id.bottomNavigationView);
navigationView.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener);
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction transaction = fragmentManager.beginTransaction();
transaction.replace(R.id.content, new HomeFragment()).commit();
}
private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener =
new BottomNavigationView.OnNavigationItemSelectedListener(){
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item){
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction transaction = fragmentManager.beginTransaction();
switch (item.getItemId()){
case R.id.HomeItem:
transaction.replace(R.id.content, new HomeFragment()).commit();
return true;
case R.id.SearchItem:
transaction.replace(R.id.content, new SearchFragment()).commit();
return true;
case R.id.PersonalItem:
transaction.replace(R.id.content, new PersonalFragment()).commit();
return true;
}
return false;
}
};
}
public class HomeFragment extends Fragment {
// TODO: Rename parameter arguments, choose names that match
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
private OnFragmentInteractionListener mListener;
public HomeFragment() {
// Required empty public constructor
}
// TODO: Rename and change types and number of parameters
public static HomeFragment newInstance(String param1, String param2) {
HomeFragment fragment = new HomeFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_home, container, false);
}
// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentInteractionListener) {
mListener = (OnFragmentInteractionListener) context;
} else {
Toast.makeText(context, "Home Fragment Attached", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
void onFragmentInteraction(Uri uri);
}
}
You must use transaction.hide(fragment) and transaction.show(fragment) instead of transaction.replace, since replacing will delete the fragment and add it again, removing its saved state.
Doing it my way will call fragments' onPause and onReaume method, not resetting their state.
Hope it helps!
I have a problem and the solutions I've found did not work for me (check for null etc.).
I have a simple activity which hosts 2 fragments in landscape mode and 1 framelayout in portrait mode. When I change the orientation of the device and then change it back, the click handler is not working (getActivity() in DetailFragment is null).
Here is my code so far:
//UserListActivity.java
public class UserListActivity extends AppCompatActivity implements UserListFragment.OnUserListSelectedListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user_list);
// Check whether the activity is using the layout version with
// the fragment_container FrameLayout. If so, we must add the first fragment
if (findViewById(R.id.fragment_container) != null) {
// However, if we're being restored from a previous state,
// then we don't need to do anything and should return or else
// we could end up with overlapping fragments.
if (savedInstanceState != null) {
return;
}
UserListFragment fragment = new UserListFragment();
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.add(R.id.fragment_container, fragment, "");
fragmentTransaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
fragmentTransaction.commit();
}
}
#Override
public void onUserListSelected(User selectedUser) {
UserDetailFragment userDetailFragment = (UserDetailFragment) getSupportFragmentManager().findFragmentById(R.id.user_detail_fragment);
if (userDetailFragment != null) {
// If detail frag is available, we're in two-pane layout...
userDetailFragment.updateSelectedView(selectedUser);
} else {
// Otherwise, we're in the one-pane layout and must swap frags...
//create detailFragment
UserDetailFragment newFragment = new UserDetailFragment();
Bundle args = new Bundle();
args.putString(UserDetailFragment.ARG_SELECTED_USER, new Gson().toJson(selectedUser));
newFragment.setArguments(args);
//replace fragment
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.fragment_container, newFragment, "");
fragmentTransaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
}
}
}
//UserListFragment.java
public class UserListFragment extends ListFragment implements AdapterView.OnItemClickListener {
private OnUserListSelectedListener mCallback;
private User[] users;
public interface OnUserListSelectedListener {
void onUserListSelected(User selectedUser);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.user_list_fragment, container, false);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
if (users == null) {
getAllUsers();
} else {
setAdapter();
}
getListView().setOnItemClickListener(this);
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
// This makes sure that the container activity has implemented
// the callback interface. If not, it throws an exception
try {
mCallback = (OnUserListSelectedListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString() + " must implement OnUserListSelectedListener");
}
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
mCallback.onUserListSelected(users[position]);
}
private void setAdapter() {
setListAdapter(new UserListAdapter(getActivity(), R.layout.user_list_row, users));
}
private void getAllUsers() {
try {
//...
//Async webCall using volley
//...
users = tmp.getUsers().toArray(new User[tmp.getUsers().size()]);
setAdapter();
//...
}
}
//UserDetailFragment.java
public class UserDetailFragment extends Fragment {
final public static String ARG_SELECTED_USER = "selectedUser";
private User mSelectedUser;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
if (savedInstanceState != null) {
mSelectedUser = new Gson().fromJson(savedInstanceState.getString(ARG_SELECTED_USER), User.class);
}
return inflater.inflate(R.layout.user_detail_fragment, container, false);
}
#Override
public void onStart() {
super.onStart();
Bundle args = getArguments();
if (args != null) {
updateSelectedView(new Gson().fromJson(args.getString(ARG_SELECTED_USER), User.class));
} else {
updateSelectedView(null);
}
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putString(ARG_SELECTED_USER, new Gson().toJson(mSelectedUser));
}
public void updateSelectedView(User selectedUser) {
//??? WHY IS GETACTIVITY() AFTER CHANGE OF ORIENTATION NULL ???
if (getActivity() != null) {
TextView textUserName = (TextView) getActivity().findViewById(R.id.textUserName);
TextView textUserEmail = (TextView) getActivity().findViewById(R.id.textUserEmail);
if (selectedUser != null) {
textUserName.setText(selectedUser.getName());
textUserEmail.setText(selectedUser.getEmail());
mSelectedUser = selectedUser;
} else {
textUserName.setText(null);
}
}
}
}
UserDetailFragment userDetailFragment = (UserDetailFragment) getSupportFragmentManager().findFragmentById(R.id.user_detail_fragment);
Creates a new instance of fragment.
if (findViewById(R.id.fragment_container) != null) {
// However, if we're being restored from a previous state,
// then we don't need to do anything and should return or else
// we could end up with overlapping fragments.
if (savedInstanceState != null) {
return;
}
UserListFragment fragment = new UserListFragment();
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.add(R.id.fragment_container, fragment, "");
fragmentTransaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
fragmentTransaction.commit();
}
is reusing the old instance of fragment .
Therefore, use getFragmentByTag() and dont keep the tag empty string (""), while calling .add
I have a FragmentActivity in my android application.
I use a viewPager to insert tabs in the activity. So I have this code. It works.
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.view_clienti);
Bundle extras = getIntent().getExtras();
if (extras != null) {
String datas= extras.getString("Cliente");
if (datas!= null) {
System.out.println("pippo");
}
}
TabAdapter = new DemoCollectionPagerAdapter(getSupportFragmentManager());
Tab = (ViewPager)findViewById(R.id.pager);
Tab.setOnPageChangeListener(
new ViewPager.SimpleOnPageChangeListener() {
#Override
public void onPageSelected(int position) {
actionBar = getActionBar();
actionBar.setSelectedNavigationItem(position); }
});
Tab.setAdapter(TabAdapter);
actionBar = getActionBar();
//Enable Tabs on Action Bar
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) {
Tab.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(android.app.ActionBar.Tab tab,
FragmentTransaction ft) {
// TODO Auto-generated method stub
}};
//Add New Tab
actionBar.addTab(actionBar.newTab().setText("Scheda Cliente").setTabListener(tabListener));
actionBar.addTab(actionBar.newTab().setText("Conto Cliente").setTabListener(tabListener));
apriConnessioneDB();
}
This is the class FragmentStatePagerAdapter
public class DemoCollectionPagerAdapter extends FragmentStatePagerAdapter {
public DemoCollectionPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int i) {
switch (i) {
case 0:
//Fragement for Android Tab
return new infoCliente();
case 1:
//Fragment for Ios Tab
return new infoCliente();
case 2:
//Fragment for Windows Tab
return new infoCliente();
}
return null;
}
#Override
public int getCount() {
return 2;
}
#Override
public CharSequence getPageTitle(int position) {
return "OBJECT " + (position + 1);
}
}
This is the class Fragment:
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.view_infocliente, container, false);
if(savedInstanceState!=null){
//String tmp = savedInstanceState.getString("myKey");
//TextView mTabHost = (TextView) findViewById(android.R.id.labelRagioneSociale);
System.out.println("PIPPPPPPPPPPPPPPPPPPPPPP");
}
TextView btn=(TextView) view.findViewById(R.id.labelRagioneSociale5);
btn.setText("pippo");
return view;
}
Now I want to know How I can pass a parameter to infoCliente class.
In the onCreate method of first class I have this:
String datas= extras.getString("Cliente");
I want pass this parameter to fragment class.
Bundle bundle = new Bundle();
bundle.putInt("battery", bat);
MyFragment fragment=new MyFragment();
fragment.setArguments(bundle);
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.add(R.id.fragment_container,fragment);
ft.commit();
Then in onCreate() method of the fragment:
Bundle bundle=getArguments(); int mLabel = bundle.getInt("battery",0);
Define an interface in your Fragment, for example
public interface FragmentCallback {
onSomethingHappend(String param);
}
Implement the interface in your Activity.
Then, when you want to call the callback, do something like this:
FragmentCallback callback = (FragmentCallback) getActivity();
callback.onSomethingHappened(string);
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