SlidingMenu with ViewPager and ActionBarSherlock Tabs - java

In my calendar application, I am using ActionBarSherlock to display two tabs - 1) Calendar 2) Converter. On the click event of an ActionBar menu item, I'm using SlidingMenu drawer to display event summary for that month.
I want to use viewpager specifically for the Calendar tab and I have implemented it this way:
Main.java:
public class BaseActivity extends SlidingSherlockFragmentActivity
{
private ViewPager pager;
CalendarFragmentPagerAdapter mPagerAdapter;
private static final int MONTHS_LIMIT = 5;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setTitle(R.string.app_name);
setContentView(R.layout.main);
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.main, new CalendarFragment())
.commit();
setBehindContentView(R.layout.content_frame);
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.content_frame, new EventsSummary())
.commit();
setSlidingActionBarEnabled(false);
final ActionBar bar = getSupportActionBar();
bar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
bar.setHomeButtonEnabled(true);
ActionBar.Tab calendar = bar.newTab();
ActionBar.Tab converter = bar.newTab();
calendar.setText(this.getResources().getString(R.string.calendar));
converter.setText(this.getResources().getString(R.string.converter));
calendar.setTabListener(new MyTabListener());
converter.setTabListener(new MyTabListener());
bar.addTab(calendar);
bar.addTab(converter);
// customize the SlidingMenu
SlidingMenu sm = getSlidingMenu();
sm.setShadowWidthRes(R.dimen.shadow_width);
sm.setShadowDrawable(R.drawable.shadow);
sm.setBehindOffsetRes(R.dimen.actionbar_home_width);
sm.setSlidingEnabled(false);
mPagerAdapter = new CalendarFragmentPagerAdapter(getSupportFragmentManager());
pager = (ViewPager) this.findViewById(R.id.viewpager);
pager.setAdapter(mPagerAdapter);
pager.setCurrentItem(MONTHS_LIMIT / 2);
}
private class MyTabListener implements ActionBar.TabListener
{
#Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
if(tab.getPosition()==0)
{
CalendarFragment frag = new CalendarFragment();
ft.replace(R.id.main, frag);
}
else
{
ConverterFragment frag = new ConverterFragment();
ft.replace(R.id.main, frag);
}
}
#Override
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
// TODO Auto-generated method stub
}
#Override
public void onTabReselected(Tab tab, FragmentTransaction ft) {
// TODO Auto-generated method stub
}
}
public boolean onOptionsItemSelected(MenuItem item) {
Intent newActivity;
// Handle item selection
switch (item.getItemId()) {
case R.id.menu_slidingmenu:
toggle();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
public class CalendarFragmentPagerAdapter extends FragmentPagerAdapter {
public CalendarFragmentPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
CalendarFragment fragment = new CalendarFragment();
Bundle args = new Bundle();
args.putInt("offset", position - MONTHS_LIMIT / 2);
fragment.setArguments(args);
return fragment;
}
#Override
public int getCount() {
return MONTHS_LIMIT;
}
}
}
CalendarFragment.java:
public class CalendarFragment extends Fragment
{
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bundle args = getArguments();
int offset = args.getInt("offset"); //throws NullPointerException
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.simple_calendar_view, container, false);
.....
return v;
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putBoolean("dummy", true);
}
}
The problem is at this line in the CalendarFragment:
int offset = args.getInt("offset");
It throws the error NullPointerException and debugging shows this is because Bundle args = getArguments() is null.
I tried to put the breakpoint at this line in the PagerAdapter:
Bundle args = new Bundle();
but it never reaches here and the application crashes throwing the NullPointerException.
Where am I going wrong?

Here
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.main, new CalendarFragment())
.commit();
and here
#Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
if (tab.getPosition() == 0) {
CalendarFragment frag = new CalendarFragment();
ft.replace(R.id.main, frag);
} else {
ConverterFragment frag = new ConverterFragment();
ft.replace(R.id.main, frag);
}
}
you're just creating an empty CalendarFragment instance without any arguments.
So your activity launches, creating an empty Fragment without arguments, and then crashes when trying to get those

Related

Android - NullPointerException in Fragment after callback

This is the first time I work with Fragments and I don't understand very well how to manage them. In this case I have two fragments that I show dinamically in a FrameLayout with id fragment_place. The issue is probably with the fragmentTransaction(addtobackstack / popbackstack).
In Fragment2 I show a popupmenu when I press the menubutton on the mobile and it works as expected the first time, but after I go back to the previous fragment and return to fragment2 now If I press the menubutton I get the following error
java.lang.NullPointerException
at android.support.v7.view.menu.MenuBuilder.<init>(MenuBuilder.java:216)
at android.support.v7.widget.PopupMenu.<init>(PopupMenu.java:103)
at android.support.v7.widget.PopupMenu.<init>(PopupMenu.java:78)
at android.support.v7.widget.PopupMenu.<init>(PopupMenu.java:63)
at package.Fragment2.showPopup(Fragment2.java:93)
Below is the code for the mainactivity and fragment2, this is driving me crazy, any help will be much appreciated.
public class MainActivity extends AppCompatActivity implements Fragment1.onEvent {
Fragment1 frag;
Fragment2 frag2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
frag = new Frag1();
// Begin the transaction
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.replace(R.id.fragment_place, frag);
ft.commit();
}
#Override
public void onEventSelected(String key) {
frag2 = new Frag2();
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.replace(R.id.fragment_place,frag2);
ft.addToBackStack(null);
ft.commit();
}
#Override
public void onBackPressed(){
FragmentManager ft = getSupportFragmentManager();
if (ft.getBackStackEntryCount() > 0) {
ft.popBackStack();
} else {
super.onBackPressed();
}
}
#Override
public boolean dispatchKeyEvent(KeyEvent event) {
int action = event.getAction();
int keyCode = event.getKeyCode();
switch (keyCode) {
case KeyEvent.KEYCODE_MENU:
if (action == KeyEvent.ACTION_UP) {
Fragment f = getSupportFragmentManager().findFragmentById(R.id.fragment_place);
if (f instanceof Fragment2) {
sendBroadcast();
}
}
return true;
default:
return super.dispatchKeyEvent(event);
}
}
private void sendBroadcast(){
Intent intent = new Intent("popup_menu");
LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
}}
This is the problematic fragment. The error lines are basically the method showPopup
public class Fragment2 extends Fragment {
private String key;
private View view;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup parent, Bundle savedInstanceState) {
view = inflater.inflate(R.layout.fragment, parent, false);
LocalBroadcastManager.getInstance(getActivity()).registerReceiver(mMessageReceiver,
new IntentFilter("popup_menu"));
return view;
}
private BroadcastReceiver mMessageReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
showPopup(view);
}
};
public void showPopup(View v) {
Button b = (Button) view.findViewById(R.id.b_attach);
PopupMenu popup = new PopupMenu(getActivity(), b);
popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem item) {
//dosomething
}
});
MenuInflater inflater = popup.getMenuInflater();
inflater.inflate(R.menu.menu_popup, popup.getMenu());
popup.show();
}}
this is the way i do and it works for me:
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction().replace(R.id.content_frame,new fragment() ).commit();
I solved the issue getting rid of sendbroadcast() and broadcastReceiver(), instead of that now I call showPopup() directly from the mainActivity when I need it.

How can i load WebView URL in fragment from another AppCompatActivity class

I am creating project for "Drawer with Swipe Tab". There i used a webview in fragment and i want to load Webview URL from Another AppCompatActivity. How can i do it?
Fragment Class:
public class SocialFragment extends Fragment {
ProgressBar pb_per;
public WebView mWebView;
View view;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
view = inflater.inflate(R.layout.social_layout, container, false);
pb_per = (ProgressBar) view.findViewById(R.id.progressBar_book1);
mWebView = (WebView) view.findViewById(R.id.web_book1); //This is the id you gave for webview
//--------------------------- to over ride keyboard error ------(1)
mWebView.setWebViewClient(new myWebClient());
mWebView.getSettings().setJavaScriptEnabled(true);
//--------------------------------------------------
mWebView.getSettings().setSupportZoom(true); //Zoom Control on web (You don't need this
//if ROM supports Multi-Touch
mWebView.getSettings().setBuiltInZoomControls(true); //Enable Multitouch if supported by ROM
mWebView.setBackgroundColor(Color.parseColor("#FFFFFF"));
mWebView.getSettings().setUseWideViewPort(true);
mWebView.getSettings().setLoadWithOverviewMode(false);
// Load URL
mWebView.loadUrl("http://www.twitter.com");
mWebView.setOnKeyListener(new View.OnKeyListener() {
#Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (event.getAction() == KeyEvent.ACTION_DOWN) {
WebView webView = (WebView) v;
switch (keyCode) {
case KeyEvent.KEYCODE_BACK:
if (webView.canGoBack()) {
webView.goBack();
return true;
}
break;
}
}
return false;
}
});
return view;
}
//===================================================================
public class myWebClient extends WebViewClient {
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
// TODO Auto-generated method stub
super.onPageStarted(view, url, favicon);
}
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
// TODO Auto-generated method stub
pb_per.setVisibility(View.VISIBLE);
// multi_per.setVisibility(ProgressBar.GONE);
view.loadUrl(url);
return true;
}
#Override
public void onPageFinished(WebView view, String url) {
// TODO Auto-generated method stub
super.onPageFinished(view, url);
pb_per.setVisibility(View.GONE);
// multi_per.setVisibility(ProgressBar.VISIBLE);
}
}
}
TabFragment.Java Class
public class TabFragment extends Fragment {
public static TabLayout tabLayout;
public static ViewPager viewPager;
public static int int_items = 2;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
/**
*Inflate tab_layout and setup Views.
*/
View x = inflater.inflate(R.layout.tab_layout,null);
tabLayout = (TabLayout) x.findViewById(R.id.tabs);
viewPager = (ViewPager) x.findViewById(R.id.viewpager);
/**
*Set an Apater for the View Pager
*/
viewPager.setAdapter(new MyAdapter(getChildFragmentManager()));
/**
* Now , this is a workaround ,
* The setupWithViewPager dose't works without the runnable .
* Maybe a Support Library Bug .
*/
tabLayout.post(new Runnable() {
#Override
public void run() {
tabLayout.setupWithViewPager(viewPager);
}
});
return x;
}
class MyAdapter extends FragmentPagerAdapter{
public MyAdapter(FragmentManager fm) {
super(fm);
}
// Return fragment with respect to Position .
#Override
public Fragment getItem(int position)
{
switch (position){
case 0 : return new PrimaryFragment();
case 1 : return new SocialFragment();
}
return null;
}
#Override
public int getCount() {
return int_items;
}
// This method returns the title of the tab according to the position.
#Override
public CharSequence getPageTitle(int position) {
switch (position){
case 0 :
return "Facebook";
case 1 :
return "Twitter";
}
return null;
}
}
}
AppCompatActivity class:
public class MainActivity extends AppCompatActivity {
DrawerLayout mDrawerLayout;
NavigationView mNavigationView;
FragmentManager mFragmentManager;
FragmentTransaction mFragmentTransaction;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Setup the DrawerLayout and NavigationView
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawerLayout);
mNavigationView = (NavigationView) findViewById(R.id.shitstuff);
// Lets inflate the very first fragment
// Here , we are inflating the TabFragment as the first Fragment
mFragmentManager = getSupportFragmentManager();
mFragmentTransaction = mFragmentManager.beginTransaction();
mFragmentTransaction.replace(R.id.containerView, new TabFragment()).commit();
// Setup click events on the Navigation View Items.
mNavigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
mDrawerLayout.closeDrawers();
if (menuItem.getItemId() == R.id.nav_item_sent) {
//###############################From Here I Call WEBVIEW URL #######################
SocialFragment.mWebView.loadUrl("http://www.busindia.com/busindia_TNSTC.jsp");
}
if (menuItem.getItemId() == R.id.nav_item_inbox) {
FragmentTransaction xfragmentTransaction = mFragmentManager.beginTransaction();
xfragmentTransaction.replace(R.id.containerView, new TabFragment()).commit();
}
return false;
}
});
// Setup Drawer Toggle of the Toolbar
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
ActionBarDrawerToggle mDrawerToggle
= new ActionBarDrawerToggle(this, mDrawerLayout, toolbar, R.string.app_name, R.string.app_name);
mDrawerLayout.setDrawerListener(mDrawerToggle);
mDrawerToggle.syncState();
}
}
I had Tried #cprakashagr Given Solutation but getting error See below Image
See Error ScreenShot
Use localBroadCastManager
WebViewHavingActivity
#Override
protected void onPause() {
// Unregister since the activity is paused.
LocalBroadcastManager.getInstance(this).unregisterReceiver(
mWebViewLoader);
super.onPause();
}
#Override
protected void onResume() {
// Register to receive messages.
// We are registering an observer (mWebViewLoader) to receive Intents
// with actions named "WebView".
LocalBroadcastManager.getInstance(this).registerReceiver(
mWebViewLoader, new IntentFilter("WebView"));
super.onResume();
}
// Our handler for received Intents. This will be called whenever an Intent
// with an action named "WebView" is broadcasted.
private BroadcastReceiver mWebViewLoader = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
mWebView.post(new Runnable() {
#Override
public void run() {
mWebView.loadUrl("http://google.com");
}
});
}
};
CallingActivity
LocalBroadcastManager.getInstance(JobDetailScreen.this).sendBroadcast(new Intent("WebView"));
This Work for me Thanks For trying me to Help
SocialFragment.mWebView.post(new Runnable() {
public void run() {
SocialFragment.mWebView.loadUrl("http://www.busindia.com/busindia_TNSTC.jsp");
}
});

Return to previously fragments

I am doing an Android app using fragments but i haven't previously experience with fragments.
I have a main FragmentActivity where i load a main view and i call my fragment class:
public class MainActivity extends FragmentActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_view);
FragmentTransaction FT = getFragmentManager().beginTransaction();
if (findViewById(R.id.fragmentAction) != null) {
FT.replace(R.id.fragmentAction, MainMenuFragment.newInstance(
getString(R.string.main_menu), getApplicationContext()));
}
FT.addToBackStack(null);
FT.commit();
}
#Override
public void onBackPressed() {
}
And this is my fragmet classm where when i push button call to other fragment:
public class MainMenuFragment extends Fragment {
private static String my_description = "";
private static Context my_context = null;
public static MainMenuFragment newInstance(String description,
Context context) {
my_description = description;
my_context = context;
MainMenuFragment f = new MainMenuFragment();
return f;
}
public MainMenuFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
View view = null;
if (my_description.compareTo(getString(R.string.main_menu)) == 0) {
view = inflater.inflate(R.layout.main_menu, container, false);
}
return view;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
if (my_description.compareTo(getString(R.string.main_menu)) == 0) {
Button new_user = (Button) getView().findViewById(
R.id.button_newUser);
new_user.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
FragmentTransaction FT = getFragmentManager()
.beginTransaction();
FT.replace(R.id.fragmentAction, LdapFragment.newInstance(
getString(R.string.new_user), my_context));
FT.commit();
}
});
}
}
}
My question is: how can i do to return to previously fragment when i push back key? I add onBackPressed function in my FragmentActivity and capture the event, but what have i to do?
Use this code
#Override
public void onBackPressed() {
// TODO Auto-generated method stub
if (getSupportFragmentManager().getBackStackEntryCount() == 0) {
this.finish();
} else {
getSupportFragmentManager().popBackStack();
removeCurrentFragment();
}
}
public void removeCurrentFragment() {
FragmentTransaction transaction = getSupportFragmentManager()
.beginTransaction();
Fragment currentFrag = getSupportFragmentManager().findFragmentById(
R.id.fragment_container);
setFragName("NONE");
if (currentFrag != null) {
setFragName(currentFrag.getClass().getSimpleName());
}
if (currentFrag != null) {
transaction.remove(currentFrag);
}
transaction.commit();
}
following is the code that i use. You need not do anything. Android system handles backpress and shows the appropriate fragment in the navigation order
#Override
public void onBackPressed() {
super.onBackPressed();
if (getFragmentManager().getBackStackEntryCount() == 0)
finish();
}
you missed the super.onBackPressed(); call. Try adding that to your code.
Just create method for add and back to fragment .
for example,
public void setFragment(Fragment fragment, boolean backStack, String tag) {
FragmentManager manager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = manager.beginTransaction();
if (backStack) {
fragmentTransaction.addToBackStack(tag);
}
fragmentTransaction.replace(R.id.fragmentAction, MainMenuFragment.newInstance(
getString(R.string.main_menu), tag);
fragmentTransaction.commit();
}
call method from onCreate() or onResume()of your Activity.
setFragment(Your FragmentClass object, true, "tag");

when i select the contacts tab the tab bar is vanished

i have four tabs in the tab bar when i select the contact tab from the tab bar the tab bar is disappeared.i want to show the tab bar when i select the contact tab.
Here is code
TabActivity.java
public class Tab_Activity extends TabActivity
{
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Resources obj_res = getResources();
TabHost tabHost = (TabHost)findViewById(android.R.id.tabhost);
TabSpec m_tab1 = tabHost.newTabSpec("First Tab");
TabSpec m_tab2 = tabHost.newTabSpec("Second Tab");
Intent intent1 = new Intent().setClass(this, Phone.class);
Intent intent3 = new Intent().setClass(this, Settings.class);
Intent intent4 = new Intent().setClass(this, Contact.class);
m_tab4.setIndicator("Tab4");
m_tab4=tabHost.newTabSpec("tab4").setIndicator("", obj_res.getDrawable(R.drawable.pic1)).setContent(intent3);
m_tab5.setIndicator("Tab4");
m_tab5=tabHost.newTabSpec("tab4").setIndicator("", obj_res.getDrawable(R.drawable.pic3)).setContent(intent4);
tabHost.addTab(m_tab2);
tabHost.addTab(m_tab4);
tabHost.addTab(m_tab5);
}}
Contact.java
public class Contact extends Activity
{
protected void onCreate(Bundle savedInstanceState)
{
//this.requestWindowFeature(Window.FEATURE_NO_TITLE);
//this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
super.onCreate(savedInstanceState);
//setContentView(R.layout.contact);
Intent Contacts = new Intent(Intent.ACTION_GET_CONTENT);
Contacts.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
Contacts.setType(ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE);
startActivityForResult(Contacts, 1);
}}
This is your activity in which u can put how many tab you want to display.
public class GuestListAdminActivity extends FragmentActivity implements
ActionBar.TabListener {
private ViewPager viewPager;
private TabsPagerAdapter mAdapter;
private ActionBar actionBar;
// Tab titles
private String[] tabs = { "Bride", "Groom", "Create Gueset List" };
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_guest_list_admin);
// Initilization
viewPager = (ViewPager) findViewById(R.id.pager);
actionBar = getActionBar();
mAdapter = new TabsPagerAdapter(getSupportFragmentManager());
viewPager.setAdapter(mAdapter);
actionBar.setHomeButtonEnabled(false);
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
getActionBar().setHomeButtonEnabled(true);
// Adding Tabs
for (String tab_name : tabs) {
actionBar.addTab(actionBar.newTab().setText(tab_name)
.setTabListener(this));
}
/**
* on swiping the viewpager make respective tab selected
* */
viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageSelected(int position) {
// on changing the page
// make respected tab selected
actionBar.setSelectedNavigationItem(position);
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
}
#Override
public void onPageScrollStateChanged(int arg0) {
}
});
}
#Override
public void onTabReselected(Tab tab, FragmentTransaction ft) {
}
#Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
// on tab selected
// show respected fragment view
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
}
}
This is pager adapter which will show your all fragments.
public class TabsPagerAdapter extends FragmentPagerAdapter {
public TabsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int index) {
switch (index) {
case 0:
return new BrideGuestList();
case 1:
return new GroomGuestList();
case 2:
return new NewGuestListActivity();
default:
break;
}
return null;
}
#Override
public int getCount() {
// get item count - equal to number of tabs
return 3;
}
}
And make your fragment activity like following
public class BrideGuestList extends android.support.v4.app.Fragment{
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.bride_guest_list, container, false);
return rootView;
}

android send data to fragment from activity

I have a map activity. When I click on the info window of the marker an intent will send the id to my fragment. In my map activity :
map.setOnInfoWindowClickListener(
new OnInfoWindowClickListener() {
#Override
public void onInfoWindowClick(Marker m) {
Intent nextScreen = new Intent (Map.this,
PHDetail.class);
Bundle bundle = new Bundle();
bundle.putString("test", "id");
Callfor c = new Callfor();
c.setArguments(bundle);
startActivityForResult(nextScreen, 101);
}
});
In my fragment :
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_call_for, container, false);
TextView TXT = (TextView) rootView.findViewById(R.id.test);
Bundle test = getArguments();
if(test!=null){
String d = test.getString("test", " ");
TXT.setText(d);
}
return rootView;
}
The problem is the bundle is null. How can I fix this?
This is my PHDetail FragmentActivity class :
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.phdetail);
Intent intent = getIntent();
if (intent != null) {
String id = intent.getStringExtra("test");
}
// Initialization :
viewPager = (ViewPager) findViewById(R.id.pager);
actionBar = getActionBar();
mAdapter = new TabsPagerAdapter(getSupportFragmentManager());
viewPager.setAdapter(mAdapter);
actionBar.setHomeButtonEnabled(false);
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
// Adding Tabs :
for (String tab_name : tabs){
actionBar.addTab(actionBar.newTab().setText(tab_name)
.setTabListener(this));
}
/**
* on swiping the viewpager make respective tab selected
* */
viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageSelected(int position) {
// on changing the page
// make respected tab selected
actionBar.setSelectedNavigationItem(position);
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
}
#Override
public void onPageScrollStateChanged(int arg0) {
}
});
}
#Override
public void onTabReselected(Tab tab, FragmentTransaction ft) {
}
#Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
// on tab selected
// show respected fragment view
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
}
}
UPDATE
On your onTabSelected you need to create your Fragment, set the bundle and then do the transaction like this.
#Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
// on tab selected
// show respected fragment view
viewPager.setCurrentItem(tab.getPosition());
Bundle bundle = new Bundle();
bundle.putString("id", id);
MyFragment fragment=new MyFragment();
fragment.setArguments(bundle);
ft = getFragmentManager().beginTransaction();
ft.add(R.id.fragment_container,fragment);
ft.commit();
}
FIRST ANSWER
The right way to pass values to other Activities like a FragmentActivity it´s adding those values to the intent that´s going to start them.
map.setOnInfoWindowClickListener(
new OnInfoWindowClickListener() {
#Override
public void onInfoWindowClick(Marker m) {
Intent nextScreen = new Intent (Map.this, PHDetail.class);
intent.putExtra("test", "id");
startActivityForResult(nextScreen, 101);
}
});
Then on your FragmentActivity called PHDetail you should get the values from the Intent.
Intent intent = getIntent();
if (intent != null) {
String id = intent.getStringExtra("test");
}
After that when you load your Fragment on your container view on PHDetail, you should add the Bundle and then do the transaction.
Bundle bundle = new Bundle();
bundle.putString("test", "id");
Callfor c = new Callfor();
c.setArguments(bundle);
After that you'll be able to retrieve the values inside your Fragment like you stated above
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_call_for, container, false);
TextView TXT = (TextView) rootView.findViewById(R.id.test);
Bundle test = getArguments();
if(test!=null){
String d = test.getString("test", " ");
TXT.setText(d);
}
return rootView;
}
Hope it helps! :)

Categories