How to pass Arguments to Fragment from Activity - android

I have an activity which instantiates and populates a Fragment through a adopter class. I want to pass values/objects to this Fragment adopter class so that i can dictate layout etc.
I have tried passing bundles using the setArgument method but my code bombs out and not sure why. As i understand, i can collect the bundle at the onCreate method in the adopter class. I see the arguments are set correctly immediately after the commented code but alas it crashes after that and i don't understand why. If i remove the bundle code it doesnt crash. :(
Below is my code, does anybody know where i should put the bundle code, commented out?
public class LoginScreen extends ActionBarActivity {
private final String ARG_SELECTED_LAYOUT_ID = "selectedLayoutId";
private final int DEFAULT_LAYOUT = R.layout.layout_list;
private int mSelectedLayoutId;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
ActionBar actionBar = getSupportActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
actionBar.setDisplayShowTitleEnabled(false);
actionBar.setDisplayShowHomeEnabled(false);
mSelectedLayoutId = DEFAULT_LAYOUT;
if (savedInstanceState != null) {
mSelectedLayoutId = savedInstanceState.getInt(ARG_SELECTED_LAYOUT_ID);
}
addLayoutTab(
actionBar, R.layout.layout_list, R.drawable.ic_list, "list");
addLayoutTab(
actionBar, R.layout.layout_grid, R.drawable.ic_grid, "grid");
addLayoutTab(
actionBar, R.layout.layout_staggered_grid, R.drawable.ic_staggered, "staggered");
addLayoutTab(
actionBar, R.layout.layout_spannable_grid, R.drawable.ic_spannable, "spannable");
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt(ARG_SELECTED_LAYOUT_ID, mSelectedLayoutId);
}
private void addLayoutTab(ActionBar actionBar, int layoutId, int iconId, String tag) {
ActionBar.Tab tab = actionBar.newTab()
.setText("")
.setIcon(iconId)
.setTabListener(new TabListener(layoutId, tag));
actionBar.addTab(tab, layoutId == mSelectedLayoutId);
}
public class TabListener implements ActionBar.TabListener {
private LayoutFragment mFragment;
private final int mLayoutId;
private final String mTag;
public TabListener(int layoutId, String tag) {
mLayoutId = layoutId;
mTag = tag;
}
#Override
public void onTabSelected(ActionBar.Tab tab, FragmentTransaction ft) {
mFragment = (LayoutFragment) getSupportFragmentManager().findFragmentByTag(mTag);
if (mFragment == null) {
mFragment = (LayoutFragment) LayoutFragment.newInstance(mLayoutId);
ft.add(R.id.content, mFragment, mTag);
} else {
ft.attach(mFragment);
}
/*
Bundle bundle = new Bundle();
bundle.putInt("noTiles", 4);
mFragment.setArguments(bundle);
*/
mSelectedLayoutId = mFragment.getLayoutId();
}
#Override
public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction ft) {
if (mFragment != null) {
ft.detach(mFragment);
}
}
#Override
public void onTabReselected(ActionBar.Tab tab, FragmentTransaction ft) {
}
}
}
Logcat
03-03 11:56:53.675 32507-32507/weebuns.predictionking E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: weebuns.predictionking, PID: 32507
java.lang.RuntimeException: Unable to start activity ComponentInfo{weebuns.predictionking/weebuns.predictionking.LoginScreen}: java.lang.NullPointerException: Attempt to invoke virtual method 'void weebuns.predictionking.LayoutFragment.setArguments(android.os.Bundle)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2298)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360)
at android.app.ActivityThread.access$800(ActivityThread.java:144)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5221)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void weebuns.predictionking.LayoutFragment.setArguments(android.os.Bundle)' on a null object reference

To pass argument to your fragment, it's recommended to create a public static method to instanciate your fragment like :
public static MyFragment newInstance(String firstArg) {
MyFragment f = new MyFragment ();
Bundle args = new Bundle();
args.putString("ARG1", firstArg);
f.setArguments(args);
return f;
}
And then retrieve your args in onCreateView() method like :
String arg = getArguments().getString("ARG1");
Use the static method to instanciate a new fragment with your arguments in other fragment or activities like :
MyFragment f = MyFragment.newInstance(myArg);

It's hard to say without seeing the logcat, but surely you are missing to call the commit() method on the FragmentTransaction. Also remember to set the arguments to the fragment before calling ft.commit().
#Override
public void onTabSelected(ActionBar.Tab tab, FragmentTransaction ft) {
mFragment = (LayoutFragment) getSupportFragmentManager().findFragmentByTag(mTag);
if (mFragment == null) {
Bundle bundle = new Bundle();
bundle.putInt("noTiles", 4);
mFragment = (LayoutFragment) LayoutFragment.newInstance(mLayoutId);
mFragment.setArguments(bundle);
//ft.add(R.id.content, mFragment, mTag).commit();
ft.add(R.id.content, mFragment, mTag);
} else {
ft.attach(mFragment);
}
mSelectedLayoutId = mFragment.getLayoutId();
}

In your activity
Bundle args = new Bundle();
args.putString("Menu", "Your String");
Fragment detail = new FragmeantOne();
detail.setArguments(args);
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction().replace(R.id.content_frame, detail).commit();
In your Fragment.. in onCreateView()
String menu = getArguments().getString("Menu");
someTextView.setText(menu);

You can use Bundle to transfer data from activity to fragments or transfre data from fragment to fragment.
Bundle bundle = new Bundle();
DisplayDataList fragment = new DisplayDataList();
bundle.putString("listitem", "Buyer,Seller");
fragment.setArguments(bundle);
getFragmentManager().beginTransaction().replace(
R.id.frame_container, fragment).addToBackStack(null).commit();
Where you want to recieve that bundle i.w in DisplayDataList Fragment class. You have to use getArguments() method.
DisplayDataList
Bundle bundle = getArguments();
String getdata = bundle.getString("listitem");
System.out.println("Data got-->>> " + getdata);
Hope this will help you.

You can use Bundle to transfer data between activity and fragment/Dialog fragment
Send data From Your Activity to Fragment() -> onClickBtn()
val f = PaymentBottomSheet()
val bundle = Bundle()
bundle.putString("coins", walletBinding.edCoins.text.toString())
bundle.putString("method", getJsonData()[adapter.selected].method)
bundle.putString("name", walletBinding.edNickName.text.toString())
bundle.putString("acc", walletBinding.edAccountId.text.toString())
f.arguments = bundle
f.show(supportFragmentManager, f.tag)
Retrieved Data from Your Activity (Your fragment code look like this) onCreateView()
val bundle = Bundle(arguments)
coins = bundle.getString("coins")
method = bundle.getString("method")
name = bundle.getString("name")
id = bundle.getString("acc")
Timber.d("Coins $coins, Method $method, Name $name, ID $id")
Thank You

Related

How to send Data from Fragment to other Fragment inside FirebaseAdapter, using model.class to getPid

i have being trying to solve this problem for while thought, i'm trying to pass the data from Fragment to other Fragment, the model.getPid suggesting me to be static!, and after running the app and clicking on the image then the app crachs!
thanks in advance!
holder.imageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ProductsDetailsFragment fragment = new ProductsDetailsFragment();
Bundle b1 = new Bundle();
b1.putString("pid", Products.getPid());
fragment.setArguments(b1);
FragmentManager fragmentManager =
getActivity().getSupportFragmentManager();
FragmentTransaction ft = fragmentManager.beginTransaction();
ft.replace(R.id.nav_host_fragment, fragment)
.addToBackStack(null)
.commit();
this is from the second Fragment
Bundle bundle = this.getArguments();
if (bundle != null) {
productID= bundle.getString("pid");
getProductDetails(productID);
}
in the FirebaseAdapter when i pass the ProductTD, it returns null
private void getProductDetails(String productID) {
DatabaseReference productRef = FirebaseDatabase.getInstance().getReference().child("Products");
productRef.child(productID).addValueEventListener(new ValueEventListener() {
#Override
this is from Logcat
java.lang.NullPointerException: Can't pass null for argument 'pathString' in child()
here is your error Intent intent = new Intent(getActivity(), ProductsDetailsFragment.class);
intent.putExtra("pid", model.getPid());
startActivity(intent)
remove this you can use intent for fragment

Add and remove fragment null pointer

I have two fragments that are in the main activity and i want to refresh them when something occurs.
Now the code works for second fragment, but won't work for the first, and i am not sure why.
I have been looking at the code for about an hour, and i can't seem to find a reason.
Here is the code
public class MainActivity extends FragmentActivity {
Fragment frag,frag2;
FragmentManager fm;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String screen = getString(R.string.screen_type);
/*
* Get a reference to fragment manager
* Wire the container to represent fragment
*/
fm = getSupportFragmentManager();
frag = fm.findFragmentById(R.id.container);
if(screen.equals("large")){
frag2 = fm.findFragmentById(R.id.containerDetails);
loadFragments(frag,frag2,fm);
}
/*Loads the fragment into the activity*/
else
loadFragment(frag,fm);
}
private void loadFragments(Fragment frag, Fragment frag2, FragmentManager fm) {
if(frag == null && frag2 == null){
frag = new DisplayFragment();
frag2 = new DetailsFragment();
fm.beginTransaction().add(R.id.container,frag).add(R.id.containerDetails, frag2).commit();
}
}
private void loadFragment(Fragment frag, FragmentManager fm) {
if(frag == null){
frag = new DisplayFragment();
fm.beginTransaction().add(R.id.container,frag).commit();
}
}
public void updateDetails(int position) {
// Reload current fragment
if(frag2!=null)fm.beginTransaction().remove(frag2).commit();
frag2 = new DetailsFragment();
Bundle b = new Bundle();
b.putInt("Id",position);
frag2.setArguments(b);
fm.beginTransaction().add(R.id.containerDetails, frag2).commit();
}
public void updateDisplay() {
// Reload current fragment
if(frag!=null)fm.beginTransaction().remove(frag).commit(); //THIS IS ALWAYS NULL FOR SOME REASON
frag = new DisplayFragment();
fm.beginTransaction().add(R.id.container, frag).commit();
}
public void refreshDetails() {
// Reload current fragment
if(frag2!=null)fm.beginTransaction().remove(frag2).commit();
frag2 = new DetailsFragment();
fm.beginTransaction().add(R.id.containerDetails, frag2).commit();
}
}
The first fragment is always null, and it doesn't get removed, instead another fragment is pasted over that, and creates a mess.
Try using replace() method rather than add()

Android rotation: Why fragment not restored by TAG?

I have an activity called MainActivity with a fragment inside called 'HomeFragment'. I want to restore fragment after screen rotation, however something seems missing.
I followed below process:
save fragment by using getSupportFragmentManager().putFragment(...) during onSaveInstanceState
try to restore fragment by fragmentManager.findFragmentByTag during onCreate (after checking that bundle is not null)
However findFragmentByTag returns null.
Here is code snippets inside MainActivity:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Set up the action bar to show a dropdown list.
final ActionBar actionBar = getSupportActionBar();
actionBar.setDisplayShowTitleEnabled(false);
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);
setupNavigationSpinner(actionBar);
FragmentManager fragmentManager = getSupportFragmentManager();
if (savedInstanceState != null) {
if (fragmentManager.findFragmentByTag("frag") != null) {
// findFragmentByTag always return null
homeFragment = (HomeFragment) fragmentManager
.findFragmentByTag(HomeFragment.ARG_ITEM_ID);
contentFragment = homeFragment;
}else{
homeFragment = new HomeFragment();
switchContent(homeFragment, HomeFragment.ARG_ITEM_ID);
}
} else {
homeFragment = new HomeFragment();
switchContent(homeFragment, HomeFragment.ARG_ITEM_ID);
}
}
#Override
public void onSaveInstanceState(Bundle outState) {
getSupportFragmentManager().putFragment(outState, "frag",homeFragment );
}
public void switchContent(Fragment fragment, String tag) {
FragmentManager fragmentManager = getSupportFragmentManager();
while (fragmentManager.popBackStackImmediate())
;
if (fragment != null) {
FragmentTransaction transaction = fragmentManager
.beginTransaction();
transaction.replace(R.id.content_frame, fragment, tag);
// Only ArticlDetailFragment is added to the back stack.
if (!(fragment instanceof Fragment)) {
transaction.addToBackStack(tag);
}
transaction.commit();
contentFragment = fragment;
}
}
There is no reason to call
getSupportFragmentManager().putFragment(outState, "frag",homeFragment );
A Fragment state will automatically be restored. The problem is that you're not calling the super of your onSaveInstanceState. It should simply look like this:
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
}
Also, you're setting the tag as HomeFragment.ARG_ITEM_ID then looking for "frag". Does HomeFragment.ARG_ITEM_ID == "frag"?

Unable to start activity componentInfo Tablistener suddenly crashing the app

So i'm getting this annoying problem. I'm pretty noob when it comes to android, so any help would be nice.
This is my MainActivity which seems to be crashing according to LogCat.
The app i'm trying to create must pull data from XML data, which i'm trying to get. Then from this data it must set the tabs name (that's what i'm trying to do).
public class MainActivity extends SherlockActivity {
private String uniqeAppId;
private ArrayList<StartupInfo> info;
private String ChannelTab;
private String VicinityTab;
private String CustomTab;
private String TrackingTab;
private String MoreTab;
public static Context appContext;
private DownloadXmlTask downloadxml = new DownloadXmlTask(this);
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
info = new ArrayList<StartupInfo>();
downloadxml.loadPage();
appContext = getApplicationContext();
ActionBar actionbar = getSupportActionBar();
actionbar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
actionbar.setTitle(uniqeAppId);
ActionBar.Tab Frag1 = actionbar.newTab().setText(ChannelTab);
ActionBar.Tab Frag2 = actionbar.newTab().setText(VicinityTab);
ActionBar.Tab Frag3 = actionbar.newTab().setText(CustomTab);
ActionBar.Tab Frag4 = actionbar.newTab().setText(TrackingTab);
ActionBar.Tab Frag5 = actionbar.newTab().setText(MoreTab);
Fragment Fragment1 = new Channeltab();
Fragment Fragment2 = new Vicinitytab();
Fragment Fragment3 = new Customtab();
Fragment Fragment4 = new Trackingtab();
Fragment Fragment5 = new Moretab();
Frag1.setTabListener(new MyTabListener(Fragment1));
Frag2.setTabListener(new MyTabListener(Fragment2));
Frag3.setTabListener(new MyTabListener(Fragment3));
Frag4.setTabListener(new MyTabListener(Fragment4));
Frag5.setTabListener(new MyTabListener(Fragment5));
actionbar.addTab(Frag1);
actionbar.addTab(Frag2);
actionbar.addTab(Frag3);
actionbar.addTab(Frag4);
actionbar.addTab(Frag5);
}
public void GetTextForTabs(ArrayList<StartupInfo> info2) {
this.info = info2;
StartupInfo info3 = info.get(0);
this.ChannelTab = info3.getChannelTab();
this.VicinityTab = info3.getVicinityTab();
this.CustomTab = info3.getCustomTab();
this.TrackingTab = info3.getTrackingTab();
this.MoreTab = info3.getMoreTab();
}
#Override
public void onStart() {
super.onStart();
}
public void setInfo(ArrayList<StartupInfo> info) {
this.info = info;
}
public void alert(String msg) {
Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_LONG).show();
}
public class MyTabListener implements ActionBar.TabListener {
public Fragment fragment;
public MyTabListener(Fragment fragment) {
this.fragment = fragment;
}
#Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
ft.replace(R.id.fragment_container, fragment);
}
#Override
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
ft.remove(fragment);
}
#Override
public void onTabReselected(Tab tab, FragmentTransaction ft) {
}
}
}
Then the LogCat:
It seems to be the TabListener. But I don't understand why. It wasn't doing that earlier. It was when i tried to add data it started to crash. Can anyone help me here ?
You have a null pointer exception at line 111 of your activity (in onTabSelected). It looks as though the null reference is probably to "fragment". Look at the section on "Performing fragment transactions":
http://developer.android.com/guide/components/fragments.html
This code will not fit your program exactly, but it gives you the general idea. You need to begin, do your add/replace/why and then commit.
By the by, since you are using ActionBarSherlock why not use the Support library so as to be able to support older versions of Android ?
Here is a simple example (it contains some superfluous stuff that you don't need) that might help:
public class ExtraContent extends SherlockFragmentActivity {
// Declare Tab Variable
com.actionbarsherlock.app.ActionBar.Tab tab;
boolean mDebugLog = false;
String mDebugTag="ian_";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//mDebugLog = true;
debugLog("ExtraContent onCreate" );
// Create the actionbar
com.actionbarsherlock.app.ActionBar bar = getSupportActionBar();
// Show Actionbar Home Icon (as normal)
bar.setDisplayShowHomeEnabled(true);
// Show Actionbar Title (as normal)
bar.setDisplayShowTitleEnabled(true);
// Create Actionbar Tabs
bar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
//enable home ...
bar.setDisplayHomeAsUpEnabled(true); // ?
bar.setHomeButtonEnabled(true); // this is the one that enables home navigation
//ib18 view for fragments ...
setContentView(R.layout.extra_content);
//create the fragment we want to use for display content
Fragment ExtraLogin = new ExtraLogIn();
// Create First Tab
ActionBar.Tab tab0 = bar.newTab();
tab0 = bar.newTab();
tab0.setText("Unlock");
tab0.setTabListener(new TabListener<ExtraTab0>(this, "tab0",ExtraTab0.class, null));
bar.addTab(tab0);
// Create Second Tab
ActionBar.Tab tab1 = bar.newTab();
tab1 = bar.newTab();
tab1.setText("Level 1");
tab1.setTabListener(new TabListener<ExtraTab1>(this, "tab1",ExtraTab1.class, null));
bar.addTab(tab1);
// Create Third Tab
ActionBar.Tab tab2 = bar.newTab();
tab2 = bar.newTab();
tab2.setText("Level 2");
tab2.setTabListener(new TabListener<ExtraTab2>(this, "tab2",ExtraTab2.class, null));
bar.addTab(tab2);
if (savedInstanceState != null) { //if there is a saved bundle use it ...
bar.setSelectedNavigationItem(savedInstanceState.getInt("tab", 0));
}
else {
//ib18 savedInstanceState null so fti so start Login frag ...
FragmentManager fm = getSupportFragmentManager();
fm.beginTransaction().replace(R.id.fb, ExtraLogin, "ExtraLogin").commit();
}
}
public boolean onMenuItemSelected(int featureId, MenuItem item) {
debugLog("ExtraContent onMenuItemSelected" );
int itemId = item.getItemId();
switch (itemId) {
case android.R.id.home:
// app icon in action bar clicked; go home
Intent intent = new Intent(this, QuizLaunch.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
#Override
protected void onSaveInstanceState(Bundle outState) {
debugLog("ExtraContent onSaveInstanceState");
super.onSaveInstanceState(outState);
outState.putInt("tab", getSupportActionBar().getSelectedNavigationIndex());
}
public class TabListener<T extends Fragment> implements ActionBar.TabListener{
private final FragmentActivity mActivity;
private final String mTag;
private final Class<T> mClass;
private final Bundle mArgs;
private Fragment mFragment;
public TabListener (FragmentActivity activity, String tag, Class<T> clz,
Bundle args) {
mActivity = activity;
mTag = tag;
mClass = clz;
mArgs = args;
debugLog("ExtraContent TabListener" );
FragmentTransaction ft = mActivity.getSupportFragmentManager().beginTransaction();
// Check to see if we already have a fragment for this tab, probably
// from a previously saved state. If so, deactivate it, because our
// initial state is that a tab isn't shown.
mFragment = mActivity.getSupportFragmentManager().findFragmentByTag(mTag);
//
if (mFragment != null && !mFragment.isDetached()) {
ft.detach(mFragment);
}
ft.commit();
}
#Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
debugLog("ExtraContent onTabSelected");
ft = mActivity.getSupportFragmentManager()
.beginTransaction();
if (mFragment == null) {
mFragment = Fragment.instantiate(mActivity, mClass.getName(),mArgs);
debugLog("adding fragment "+mTag );
ft.add(R.id.tab, mFragment, mTag); //ib18 add to "tab" holder
ft.show(mFragment); //ib1.6 show fragment ...
ft.commit();
} else {
debugLog("attaching fragment "+mTag );
ft.attach(mFragment);
ft.show(mFragment); //ib1.6 show fragment ...
ft.commit();
}
}
#Override
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
debugLog("ExtraContent onTabUnSelected");
ft = mActivity.getSupportFragmentManager()
.beginTransaction();
if (mFragment != null) {
debugLog("hide and detach fragment "+mFragment );
ft.hide(mFragment); //ib1.6 hide fragment ...
ft.detach(mFragment);
ft.commitAllowingStateLoss();
}
}
#Override
public void onTabReselected(Tab tab, FragmentTransaction ft) {
// TODO Auto-generated method stub
debugLog("ExtraContent onTabReSelected");
}
}
void debugLog(String message) {
if (mDebugLog)
Log.d(mDebugTag, message);
}
}

Tab and fragments no support intents

Hi I have a problem with tab+fragment, here frist I have the class which will create the tab:
public class TestSwipeABActivity extends FragmentActivity {
FragmentTransaction transaction;
static ViewPager mViewPager;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Fragment tabOneFragment = new TabOne();
Fragment tabTwoFragment = new TabTwo();
PagerAdapter mPagerAdapter = new PagerAdapter(getSupportFragmentManager());
mPagerAdapter.addFragment(tabOneFragment);
mPagerAdapter.addFragment(tabTwoFragment);
//transaction = getSupportFragmentManager().beginTransaction();
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mPagerAdapter);
mViewPager.setOffscreenPageLimit(2);
mViewPager.setCurrentItem(0);
mViewPager.setOnPageChangeListener(
new ViewPager.SimpleOnPageChangeListener() {
#Override
public void onPageSelected(int position) {
// When swiping between pages, select the
// corresponding tab.
getActionBar().setSelectedNavigationItem(position);
}
});
ActionBar ab = getActionBar();
ab.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
Tab tab1 = ab.newTab().setText("Tab One").setTabListener(new TabListener<TabOne>(
this, "tabone", TabOne.class));
Tab tab2 = ab.newTab().setText("Tab Two").setTabListener(new TabListener<TabTwo>(
this, "tabtwo", TabTwo.class));
ab.addTab(tab1);
ab.addTab(tab2);
}
public static class TabListener<T extends Fragment> implements ActionBar.TabListener {
private Fragment mFragment;
private final Activity mActivity;
private final String mTag;
private final Class<T> mClass;
/** Constructor used each time a new tab is created.
* #param activity The host Activity, used to instantiate the fragment
* #param tag The identifier tag for the fragment
* #param clz The fragment's Class, used to instantiate the fragment
*/
public TabListener(Activity activity, String tag, Class<T> clz) {
mActivity = activity;
mTag = tag;
mClass = clz;
}
/* The following are each of the ActionBar.TabListener callbacks */
public void onTabSelected(Tab tab, FragmentTransaction ft) {
// Check if the fragment is already initialized
if (mFragment == null) {
// If not, instantiate and add it to the activity
mFragment = Fragment.instantiate(mActivity, mClass.getName());
ft.add(android.R.id.content, mFragment, mTag);
} else {
// If it exists, simply attach it in order to show it
ft.attach(mFragment);
}
}
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
if (mFragment != null) {
// Detach the fragment, because another one is being attached
ft.detach(mFragment);
}
}
public void onTabReselected(Tab tab, FragmentTransaction ft) {
// User selected the already selected tab. Usually do nothing.
}
public void onTabReselected(Tab arg0,
android.app.FragmentTransaction arg1)
{
// TODO Auto-generated method stub
}
public void onTabSelected(Tab arg0, android.app.FragmentTransaction arg1)
{
// TODO Auto-generated method stub
mViewPager.setCurrentItem(arg0.getPosition());
}
public void onTabUnselected(Tab arg0,
android.app.FragmentTransaction arg1)
{
// TODO Auto-generated method stub
}
}
public class PagerAdapter extends FragmentPagerAdapter {
private final ArrayList<Fragment> mFragments = new ArrayList<Fragment>();
public PagerAdapter(FragmentManager manager) {
super(manager);
}
public void addFragment(Fragment fragment) {
mFragments.add(fragment);
notifyDataSetChanged();
}
#Override
public int getCount() {
return mFragments.size();
}
#Override
public Fragment getItem(int position) {
return mFragments.get(position);
}
}
}
And then here is the fragment for each tab, for example the two one:
public class TabTwo extends Fragment
{
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState)
{
View view = inflater.inflate(R.layout.tabtwo, container, false);
Button Activity1= (Button) view.findViewById(R.id.button1);
Activity1.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent intent = new Intent().setClass(this,ABActivity.class);
startActivity(intent);
}
});
return view;
}
}
The error was: The method setClass(Context, Class<?>) in the type Intent is not applicable for the arguments (new View.OnClickListener(){},
Class<ABActivity>)
I try out changing the context to TabTwo.this, tabtwo.getcontext.this, but nothing, eclipse says to change .setclassName but doesnt work.
If you could help... THANKS!!!
Try this
Intent intent = new Intent(getActivity(),ABActivity.class);
startActivity(intent );
HI I just have a solution:
public void onClick(View view) {
Activity activity = getActivity();
Intent intent = new Intent().setClass(activity, ABActivity.class);
startActivity(intent);
}
Explanation: "Another difference is that a Fragment is not a subclass of Context. This means that a Fragment can not be launched as a component inside your app and therefore always has to live inside of an Activity. This also means that whenever you need a Context inside of a Fragment, you need to get access to the parent Activity. You can do this by using the getActivity() method as we have done in the Fragment button's OnClickListener callback. You need to watch out because getActivity() can return null depending on where the Fragment is in the Activity's lifecycle. So, you should also include a check to see if the Activity is null before you use it."
FROM: http://neilgoodman.net/2012/01/29/working-with-fragments-on-android-part-1/

Categories

Resources