How to pass parameter to Fragment from FragmentActivity - java

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);

Related

EditText becomes null on other methods

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;

getActivity in Fragment is null after change of orientation (single and one pane layout)

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

Tabs with Fragment life cycle

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."

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.

Android: ViewPager, ActionBar and Android.app.Fragments

i have an actionbar with two tabs and an tablistener which handles the fragments. Now i want with a ViewPager the possibility to Swipe to also switch the tabs.
I tried the solution stated here:
Android, How to mix ActionBar.Tab + View Pager + ListFragment
But it gives an conflicts with Android.app.Fragments and the Support Package Fragments.
The App is for >4.0 so i dont need the support fragments.
public class MainActivity extends Activity{
....
actionBar = getActionBar();
actionBar.setDisplayShowTitleEnabled(false);
actionBar.setDisplayShowHomeEnabled(false);
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
//viewpager
mViewPager = new ViewPager(this);
setContentView(mViewPager);
Doesnt work:
//TabsAdapter tabsAdapter = new TabsAdapter(this,mViewPager);
// Tab tab1 = actionBar.newTab().setText("Tab1");
// Tab tab2 = actionBar.newTab().setText("Tab2");
// tabsAdapter.addTab(tab1, Tab1Fragment.class, null);
// tabsAdapter.addTab(tab2, Tab2Fragment.class, null);
Alternative:
//viewpager
mViewPager = new ViewPager(this);
setContentView(mViewPager);
mViewPager.setOnPageChangeListener(
new ViewPager.SimpleOnPageChangeListener() {
#Override
public void onPageSelected(int position) {
// When swiping between pages, select the
// corresponding tab.
super.onPageSelected(position);
getActionBar().setSelectedNavigationItem(position);
}
});
tab_1 = actionBar.newTab().setText("Tab1");
tab_1
.setTabListener(new TabListener<Tab1Fragment>(
this, "Tab1", Tab1Fragment.class,mViewPager));
actionBar.addTab(tab_1);
tab_2 = actionBar.newTab().setText("Tab2");
tab_2
.setTabListener(new TabListener<Tab2Fragment>(
this, "Tab2", Tab2Fragment.class,mViewPager));
actionBar.addTab(tab_2);
/**
* TabListener
* #param <T>
*/
private static class TabListener<T extends Fragment> implements ActionBar.TabListener
{
private Fragment mFragment;
private Activity mActivity;
private final String mTag;
private final Class<T> mClass;
private ViewPager vp;
public TabListener(Activity activity, String tag, Class<T> clz, ViewPager vp) {
mActivity = activity;
mTag = tag;
mClass = clz;
mFragment = mActivity.getFragmentManager().findFragmentByTag(mTag);
this.vp = vp;
}
public void onTabSelected(Tab tab, FragmentTransaction ft) {
if (mFragment == null) {
mFragment = Fragment.instantiate(mActivity, mClass.getName());
ft.replace(android.R.id.content, mFragment, mTag);
} else {
if (mFragment.isDetached()) {
ft.attach(mFragment);
}
}
vp.setCurrentItem(tab.getPosition());
}
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
if (mFragment != null) {
ft.detach(mFragment);
}
}
public void onTabReselected(Tab tab, FragmentTransaction ft) {
}
}
In the Fragments classes i have statements like:
Bundle args = new Bundle();
args.putString("name", atn.getName());
args.putLong("aid", atn.getId());
AFragment f = new AFragment();
f.setArguments(args);
f.show(getFragmentManager(), "tag");
FragmentManager fragmentManager =mActivity.getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
Fragment f = fragmentManager.findFragmentByTag("Tab1");
if (f != null) {
fragmentTransaction.detach(f);
fragmentTransaction.attach(f);
}
fragmentTransaction.replace(android.R.id.content, f);
fragmentTransaction. commitAllowingStateLoss();
which are not compatible with the other Fragment type (import android.support.v4.app.Fragment;). How can i easily add the swipe gesture? Selection on Tabs works perfectly.
EDIT:
With support package 13 the view pager worked but the content isnt refreshed. I use FragmentStatePagerAdapter so the Fragments should be removed and added again but instead it takes the same fragment without new creation. Also Viewpage named teh Fragments like
android:switcher... can i name them on my own?
import android.support.v13.app.FragmentStatePagerAdapter;
public class TabsAdapter extends FragmentStatePagerAdapter
implements ActionBar.TabListener, ViewPager.OnPageChangeListener {
private final Context mContext;
private final ActionBar mActionBar;
private final ViewPager mViewPager;
private final ArrayList<TabInfo> mTabs = new ArrayList<TabInfo>();
private Fragment mFragment;
private Activity mActivity;
private String mTag;
private final List<Fragment> fragments = new ArrayList<Fragment>();
static final class TabInfo {
private final Class<?> clss;
private final Bundle args;
private final String name;
TabInfo(Class<?> _class, Bundle _args,String name) {
clss = _class;
args = _args;
this.name=name;
}
}
public TabsAdapter(Activity activity, ViewPager pager) {
super(activity.getFragmentManager());
mContext = activity;
mActionBar = activity.getActionBar();
mViewPager = pager;
mViewPager.setAdapter(this);
mViewPager.setOnPageChangeListener(this);
mActivity = activity;
}
public void addTab(ActionBar.Tab tab, Class<?> clss, Bundle args) {
TabInfo info = new TabInfo(clss, args,tab.getText()+"");
tab.setTag(info.name);
tab.setTabListener(this);
mTabs.add(info);
mActionBar.addTab(tab);
notifyDataSetChanged();
}
#Override
public int getCount() {
return mTabs.size();
}
#Override
public int getItemPosition(Object object) {
return POSITION_NONE;
// return super.getItemPosition(object);
}
#Override
public Fragment getItem(int position) {
TabInfo info = mTabs.get(position);
Fragment fr = Fragment.instantiate(mContext, info.clss.getName(), info.args);
//
// //addFragment (fr, position);
return fr;
}
public void addFragment(Fragment f, int location) {
if (fragments.size() == 0)
fragments.add(f);
else
fragments.add(location, f);
}
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
mActionBar.setSelectedNavigationItem(position);
}
#Override
public void onPageScrollStateChanged(int state) {
}
#Override
public void onTabSelected(ActionBar.Tab tab, android.app.FragmentTransaction ft) {
Object tag = tab.getTag();
for (int i=0; i<mTabs.size(); i++) {
if (mTabs.get(i).name == tag) {
updateDataSet(i);
mViewPager.setCurrentItem(i);
}
}
}
#Override
public void onTabReselected(ActionBar.Tab tab, android.app.FragmentTransaction ft) {
// TODO Auto-generated method stub
}
#Override
public void onTabUnselected(ActionBar.Tab tab, android.app.FragmentTransaction ft) {
// TODO Auto-generated method stub
}
public void updateDataSet(int pos)
{
//Let's update the dataset for the selected genre
Fragment fragment =
(mActivity.getFragmentManager().findFragmentByTag(
"android:switcher:"+ mViewPager.getId()+":"+pos));
//TabFragment fragment = (TabFragment) getItem(pos);
if(fragment != null) // could be null if not instantiated yet
{
if(fragment.getView() != null)
{
// no need to call if fragment's onDestroyView()
//has since been called.
if(fragment instanceof Tab1Fragment){
((Tab1Fragment) fragment).refresh();
}
else if(fragment instanceof Tab2Fragment){
( (Tab2Fragment) fragment).refresh();
}
}
}
}
Try using the build it Tab Activity template, create an example and extract the code you want from there. I created a tabs based app, but I used the default options and customized those to fit my needs.
Check this open source proyect https://github.com/dkim0419/SoundRecorder
they use one activity with a viewPager and some fragments.
Also the use PagerSlidingTabStrip for page indicator.
Take a look it's very easy how they implemented it.

Categories

Resources