using google maps with swipe taps - android

I try to start a tab, which can be swiped. It works fine! But if I try to implement Google Maps, then it works unit I switch the tab and go to the map back. I get these kind of Error:
E/AndroidRuntime(25324): FATAL EXCEPTION: main
E/AndroidRuntime(25324): android.view.InflateException: Binary XML file line #21: Error inflating class fragment
I searched many times in google and couldn't find a solution.
This is the MainActivity class Code:
public class MainActivity extends FragmentActivity implements ActionBar.TabListener {
AppSectionsPagerAdapter mAppSectionsPagerAdapter;
ViewPager mViewPager;
GoogleMapOptions nMap;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Create the adapter that will return a fragment for each of the three primary sections
// of the app.
mAppSectionsPagerAdapter = new AppSectionsPagerAdapter(getSupportFragmentManager());
// Set up the action bar.
final ActionBar actionBar = getActionBar();
// Specify that the Home/Up button should not be enabled, since there is no hierarchical
// parent.
actionBar.setHomeButtonEnabled(false);
// Specify that we will be displaying tabs in the action bar.
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
// Set up the ViewPager, attaching the adapter and setting up a listener for when the
// user swipes between sections.
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mAppSectionsPagerAdapter);
mViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
#Override
public void onPageSelected(int position) {
// When swiping between different app sections, select the corresponding tab.
// We can also use ActionBar.Tab#select() to do this if we have a reference to the
// Tab.
actionBar.setSelectedNavigationItem(position);
}
});
// For each of the sections in the app, add a tab to the action bar.
for (int i = 0; i < mAppSectionsPagerAdapter.getCount(); i++) {
// Create a tab with text corresponding to the page title defined by the adapter.
// Also specify this Activity object, which implements the TabListener interface, as the
// listener for when this tab is selected.
actionBar.addTab(
actionBar.newTab()
.setText(mAppSectionsPagerAdapter.getPageTitle(i))
.setTabListener(this));
}
}
#Override
public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
}
#Override
public void onTabSelected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
// When the given tab is selected, switch to the corresponding page in the ViewPager.
mViewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabReselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
}
public static class AppSectionsPagerAdapter extends FragmentPagerAdapter {
public AppSectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int i) {
switch (i) {
case 0:
// The first section of the app is the most interesting -- it offers
// a launchpad into the other demonstrations in this example application.
Fragment f1 = new LayersDemoActivity2();
return f1;
default:
// The other sections of the app are dummy placeholders.
Fragment fragment = new DummySectionFragment();
Bundle args = new Bundle();
args.putInt(DummySectionFragment.ARG_SECTION_NUMBER, i + 1);
fragment.setArguments(args);
return fragment;
}
}
#Override
public int getCount() {
return 4;
}
#Override
public CharSequence getPageTitle(int position) {
switch(position){
case 0: return "Timeline";
case 1: return "Chat";
case 2: return "Fh";
case 3: return "Mehr";
default: return "Section " + (position + 1);
}
}
}
/**
* A dummy fragment representing a section of the app, but that simply displays dummy text.
*/
public static class DummySectionFragment extends Fragment {
public static final String ARG_SECTION_NUMBER = "section_number";
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_section_dummy, container, false);
Bundle args = getArguments();
((TextView) rootView.findViewById(android.R.id.text1)).setText(
getString(R.string.dummy_section_text, args.getInt(ARG_SECTION_NUMBER)));
return rootView;
}
}
}
Tab 1 calls this Fragment
public class LayersDemoActivity2 extends Fragment implements OnItemSelectedListener {
private GoogleMap mMap;
private CheckBox mTrafficCheckbox;
private CheckBox mMyLocationCheckbox;
//neu hinzugekommen
private LocationClient locationclient;
private String TAG = this.getClass().getSimpleName();
//neu hinzugekommen
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
View rootView = inflater.inflate(R.layout.layers_demo, container, false);
// Demonstration of a collection-browsing activity.
rootView.findViewById(R.id.traffic)
.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
updateTraffic();
}
});
// Demonstration of a collection-browsing activity.
rootView.findViewById(R.id.my_location)
.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
updateMyLocation();
}
});
// Demonstration of a collection-browsing activity.
rootView.findViewById(R.id.button1)
.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (!checkReady()) {
return;
}
try{
LatLng hier = new LatLng(mMap.getMyLocation().getLatitude(), mMap.getMyLocation().getLongitude());
Marker setzen = mMap.addMarker(new MarkerOptions().position(hier).title("Here I am!"));
}catch(Exception e){
}
}
});
return rootView;
}
#Override
public void onStart() {
super.onStart();
Spinner spinner = (Spinner) getView().findViewById(R.id.layers_spinner);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
getView().getContext(), R.array.layers_array, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(this);
mTrafficCheckbox = (CheckBox) getView().findViewById(R.id.traffic);
mMyLocationCheckbox = (CheckBox) getView().findViewById(R.id.my_location);
setUpMapIfNeeded();
}
#Override
public void onResume() {
super.onResume();
setUpMapIfNeeded();
if (mMap != null) {
updateTraffic();
updateMyLocation();
}
}
private void setUpMapIfNeeded() {
if (mMap == null) {
mMap = ((SupportMapFragment) getFragmentManager().findFragmentById(R.id.map))
.getMap();
}
}
private boolean checkReady() {
if (mMap == null) {
//getView().Toast.makeText(this, R.string.map_not_ready, Toast.LENGTH_SHORT).show();
return false;
}
return true;
}
private void updateTraffic() {
if (!checkReady()) {
return;
}
mMap.setTrafficEnabled(mTrafficCheckbox.isChecked());
}
private void updateMyLocation() {
if (!checkReady()) {
return;
}
mMap.setMyLocationEnabled(mMyLocationCheckbox.isChecked());
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
setLayer((String) parent.getItemAtPosition(position));
}
private void setLayer(String layerName) {
if (!checkReady()) {
return;
}
if (layerName.equals(getString(R.string.normal))) {
mMap.setMapType(MAP_TYPE_NORMAL);
} else if (layerName.equals(getString(R.string.hybrid))) {
mMap.setMapType(MAP_TYPE_HYBRID);
} else if (layerName.equals(getString(R.string.satellite))) {
mMap.setMapType(MAP_TYPE_SATELLITE);
} else if (layerName.equals(getString(R.string.terrain))) {
mMap.setMapType(MAP_TYPE_TERRAIN);
} else {
Log.i("LDA", "Error setting layer with name " + layerName);
}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
// Do nothing.
}
}
last but not least, this is layers_demo.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<fragment
android:id="#+id/map"
android:layout_width="match_parent"
android:layout_height="match_parent"
class="com.google.android.gms.maps.SupportMapFragment" />
<!-- A set of test checkboxes. -->
<LinearLayout
android:id="#+id/linearLayout1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignTop="#id/map"
android:background="#D000"
android:orientation="vertical"
android:padding="6dp" >
<Spinner
android:id="#+id/layers_spinner"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<CheckBox
android:id="#+id/traffic"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="onTrafficToggled"
android:text="#string/traffic" />
<CheckBox
android:id="#+id/my_location"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="onMyLocationToggled"
android:text="#string/my_location" />
</LinearLayout>
<Button
android:id="#+id/button1"
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:onClick="tagOnMyLocation"
android:text="#string/tag_me" />
and the activity_main.xml layout
<android.support.v4.view.ViewPager xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="match_parent" />
I guess it has something to do with fragment, but I dont know how and I dont know why. Please help. :(

Just paste this method after oncreatview method
#Override
public void onDestroyView() {
Fragment f = (Fragment) getFragmentManager().findFragmentById(R.id.map);
if (f != null) {
getFragmentManager().beginTransaction().remove(f).commit();
}
super.onDestroyView();
}

Related

Tabs execute the codes present in their next fragments in android

I am trying to implement Tabs with swipe using ViewPager and 4 Fragments. When I swipe the tabs the respective xml layouts of the fragmnets are displayed correctly on each tab but the code of the fragments are not executed correctly.
eg-The following tabs have the respective fragments in it.
Tab0-ButtonFragment
public class ButtonFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_button, container, false);
Log.i("inside", "button fragment");
return rootView;
}
Tab1-ImageFragment
public class ImageFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_image, container, false);
Log.i("inside", "image fragment");
return rootView;
}
Tab2-TextFragment
public class TextFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_text, container, false);
Log.i("inside", "text fragment");
return rootView;
}
Tab3-Test
public class Test extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.temp, container, false);
Log.i("inside", "tessssssssst fragment");
return rootView;
}
When the tabs are displayed
I get the log message for tab0 and tab1 simultaneously. Then after swiping and going to tab1 i get the log message for tab2. After swiping to tab2 i get log message for tab 3 and when tab 3 is reached no log message is dispalyed. Can anyone tell me how can I execute the respective codes for the respective tabs? My remaining codes are as below:
public class TabsPagerAdapter extends FragmentPagerAdapter { //Update - code formatting
public TabsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem( int index) {
Log.i("index", "" + index);
switch (index) {
case 0:
// Top Rated fragment activity
return new ButtonFragment();
case 1:
// Games fragment activity
return new ImageFragment();
case 2:
// Movies fragment activity
return new TextFragment();
case 3:
return new Test();
}
return null;
}
#Override
public int getCount() {
// get item count - equal to number of tabs
return 4;
}
MainActivity
public class MainActivity extends FragmentActivity implements OnTabChangeListener, OnPageChangeListener {
private TabsPagerAdapter mAdapter;
private ViewPager mViewPager;
private TabHost mTabHost;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mViewPager = (ViewPager) findViewById(R.id.viewpager);
// Tab Initialization
initialiseTabHost();
mAdapter = new TabsPagerAdapter(getSupportFragmentManager());
// Fragments and ViewPager Initialization
mViewPager.setAdapter(mAdapter);
mViewPager.setOnPageChangeListener(MainActivity.this);
}
// Method to add a TabHost
private static void AddTab(MainActivity activity, TabHost tabHost, TabHost.TabSpec tabSpec) {
tabSpec.setContent(new MyTabFactory(activity));
tabHost.addTab(tabSpec);
}
// Manages the Tab changes, synchronizing it with Pages
public void onTabChanged(String tag) {
int pos = this.mTabHost.getCurrentTab();
this.mViewPager.setCurrentItem(pos);
}
#Override
public void onPageScrollStateChanged(int arg0) {
}
// Manages the Page changes, synchronizing it with Tabs
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
int pos = this.mViewPager.getCurrentItem();
this.mTabHost.setCurrentTab(pos);
}
#Override
public void onPageSelected(int arg0) {
}
// Tabs Creation
private void initialiseTabHost() {
mTabHost = (TabHost) findViewById(android.R.id.tabhost);
mTabHost.setup();
// TODO Put here your Tabs
MainActivity.AddTab(this, this.mTabHost, this.mTabHost.newTabSpec("ButtonTab").setIndicator("ButtonTab"));
MainActivity.AddTab(this, this.mTabHost, this.mTabHost.newTabSpec("ImageTab").setIndicator("ImageTab"));
MainActivity.AddTab(this, this.mTabHost, this.mTabHost.newTabSpec("TextTab").setIndicator("TextTab"));
MainActivity.AddTab(this, this.mTabHost, this.mTabHost.newTabSpec("TestingTab").setIndicator("TestingTab"));
mTabHost.setOnTabChangedListener(this);
}
This is default behaviour of viewpager you can not change it as viewpager creates fragments so that the views exist, so the user can swipe between them, so that the old view sliding off the screen and the new view sliding onto the screen. You can write your code like this
#Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
if (isVisibleToUser) {
Log.i("inside", "button fragment");
}else{
// fragment is not visible
}
}
so that when fragment is visible your code execute
When change your tab recall your corresponding fragment.
Try this it will help you
Create TabFragment.java
public class TabFragment extends Fragment implements OnPageChangeListener,
OnTabChangeListener {
private TabHost tabHost;
private int currentTab = 0;
private SwipeDisableViewPager viewPager;
protected TabPagerAdapter pageAdapter;
private List<Fragment> fragments;
private final int TAB_BUTTON=0,TAB_IMAGE=1,TAB_TEXT=2,TAB_TEST=3;
#SuppressWarnings("unchecked")
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.activity_tabhost, null);
viewPager = (SwipeDisableViewPager) view.findViewById(R.id.viewpager);
tabHost = (TabHost) view.findViewById(android.R.id.tabhost);
viewPager.addOnPageChangeListener(this);
fragments = new ArrayList<>();
fragments.add(new ButtonFragment());
fragments.add(new ImageFragment());
fragments.add(new TextFragment());
fragments.add(new Test());
return view;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
pageAdapter = new TabPagerAdapter(getChildFragmentManager(), fragments, getArguments());
pageAdapter.notifyDataSetChanged();
viewPager.setAdapter(pageAdapter);
viewPager.setOffscreenPageLimit(3);
setupTabs();
}
private void setupTabs() {
tabHost.setup();
tabHost.addTab(newTab(R.string.home, R.drawable.menu_home_bg));
tabHost.addTab(newTab(R.string.likes, R.drawable.menu_likes_bg));
tabHost.addTab(newTab(R.string.matches, R.drawable.menu_matches_bg));
for (int i = 0; i < tabHost.getTabWidget().getChildCount(); i++) {
tabHost.getTabWidget().setShowDividers(LinearLayout.SHOW_DIVIDER_NONE);
}
tabHost.setOnTabChangedListener(this);
tabHost.setCurrentTab(currentTab);
}
private View getTabIndicator(Context context, int title, int icon) {
View view = LayoutInflater.from(context).inflate(R.layout.tab_view, null);
ImageView iv = (ImageView) view.findViewById(R.id.imageView);
iv.setImageResource(icon);
TextView tv = (TextView) view.findViewById(R.id.textView);
tv.setText(title);
return view;
}
private TabSpec newTab(int tabValue, int icon) {
TabSpec tabSpec = tabHost.newTabSpec(getString(tabValue));
tabSpec.setIndicator(getTabIndicator(tabHost.getContext(), tabValue, icon));
tabSpec.setContent(new Dummy(getActivity()));
return tabSpec;
}
#Override
public void onPageScrollStateChanged(int arg0) {
}
#Override
public void onPageScrolled(int currentPosition, float arg1, int arg2) {
}
#Override
public void onPageSelected(int position) {
if (position == 0)
viewPager.setSwipeEnabled(false);
else
viewPager.setSwipeEnabled(true);
tabHost.setCurrentTab(position);
if (listener != null)
listener.onTabChanged(position);
}
#Override
public void onTabChanged(String tabId) {
currentTab = tabHost.getCurrentTab();
viewPager.setCurrentItem(currentTab);
switch(currentTab){
case TAB_BUTTON:
((ButtonFragment) fragments.get(currentTab)).recall();
break;
case TAB_IMAGE:
((ImageFragment) fragments.get(currentTab)).recall();
break;
case TAB_TEXT:
((TextFragment) fragments.get(currentTab)).recall();
break;
case TAB_TEST:
((Test) fragments.get(currentTab)).recall();
break;
}
}
create tab_fragment.xml
<?xml version="1.0" encoding="utf-8"?>
<TabHost xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#android:id/tabhost"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
<TabWidget
android:id="#android:id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:background="#drawable/menu_bg"
android:fadingEdge="none"
android:gravity="center"
android:showDividers="none"
android:tabStripEnabled="false" />
<FrameLayout
android:id="#android:id/tabcontent"
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_weight="0" />
<com.mobellotech.shift.Widget.SwipeDisableViewPager
android:id="#+id/viewpager"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_gravity="bottom"
android:background="#FFFFFF" />
</LinearLayout>
</TabHost>
Create tab_view.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
<ImageView
android:id="#+id/imageView"
android:layout_width="45dp"
android:layout_height="45dp"
android:contentDescription="#string/menu_icon" />
<TextView
android:id="#+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
Create TabPagerAdaper
public class TabPagerAdapter extends FragmentPagerAdapter {
private Bundle args;
private List<Fragment> fragments;
public TabPagerAdapter(FragmentManager fm, List<Fragment> fragments,
Bundle args) {
super(fm);
this.fragments = fragments;
this.args = args;
}
#Override
public Fragment getItem(int position) {
Fragment fragment = fragments.get(position);
fragment.setArguments(args);
return fragment;
}
#Override
public int getCount() {
return fragments.size();
}
#Override
public int getItemPosition(Object object) {
return POSITION_NONE;
}
}
Create MainActivity.java
public class MainActivity extends AppCompatActivity {
protected TabFragment tabFragment;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tabFragment = new TabFragment();
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.frame_container, tabFragment).commit();
}
}
Create activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/DrawerLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<FrameLayout
android:id="#+id/frame_container"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
</android.support.v4.widget.DrawerLayout>
Finally add the recall method in your fragment class like this
public class ButtonFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_button, container, false);
Log.i("inside", "button fragment");
return rootView;
}
public void recall() {
Log.i("inside", "button fragment");
}
}

Navigating to the view pager tab from an activity

I am creating an android application which uses viewpager and PageSlidingTabLibrary.It has 4 tabs and each tab has a list view inside it.when the list view item is clicked a new activity opens and shows the details of the item clicked.The new activity has a back button in action bar to previous activity(ie MainActivity) in which tab view is present.
The problem is if the navigation to other activity is from second tab after comeback to the MainActivity the second tab should be shown but it doesn't happend it will go to the first tab.How can i get it done Help me.
Here is my code
xml layout
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
android:orientation="vertical"
>
<com.astuetz.PagerSlidingTabStrip
android:id="#+id/tabs"
android:layout_width="match_parent"
android:layout_height="48dip"
app:pstsDividerColor="#ff1abc9c"
app:pstsIndicatorColor="#ff1abc9c"
app:pstsIndicatorHeight="5dp"
app:pstsDividerPadding="5dp"
android:keepScreenOn="true"
app:pstsShouldExpand="true"
app:pstsUnderlineColor="#ff1abc9c"
/>
<android.support.v4.view.ViewPager
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="wrap_content"
tools:context=".MainActivity" >
<FrameLayout
android:id="#+id/content"
android:layout_height="match_parent"
android:layout_width="match_parent">
<!--you can put your existing views of your current xml here, so yes your entire xml is now inside this FrameLayout -->
</FrameLayout>
</android.support.v4.view.ViewPager>
</LinearLayout>
and Activity file
public class MainActivity extends FragmentActivity{
ViewPager pager;
PagerSlidingTabStrip tabStrip;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
pager= (ViewPager) findViewById(R.id.pager);
pager.setAdapter(new MyPagerAdapter(getSupportFragmentManager()));
tabStrip= (PagerSlidingTabStrip) findViewById(R.id.tabs);
tabStrip.setViewPager(pager);
Log.d("msg","Oncreate in main activity called");
if(savedInstanceState!=null)
{
onRestoreInstanceState(savedInstanceState);
}
}
public class MyPagerAdapter extends FragmentPagerAdapter implements PagerSlidingTabStrip.IconTitleProvider
{
public MyPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public CharSequence getPageTitle(int position) {
switch (position)
{
case 0:
return "Events";
case 1:
return "Users";
case 2:
return "Groups";
case 3:
return "Settlement";
}
return null;
}
#Override
public int getCount() {
return 4;
}
#Override
public Fragment getItem(int position) {
switch (position)
{
case 0:
return new EventFragment();
case 1:
return new UserFragment();
case 2:
return new GroupFragment();
case 3:
return new SettlementFragment();
}
return null;
}
#Override
public int getPageIconResId(int position) {
switch(position)
{
case 0:
return R.drawable.event;
case 1:
return R.drawable.user;
case 2:
return R.drawable.group;
case 3:
return R.drawable.settlement;
}
return 0;
}
}
}
Fragment class
public class EventFragment extends ListFragment {
String[] events={"Trip to Goa","Trip to Ooty"};
public EventFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
ListView eventlist=new ListView(getActivity());
eventlist.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT));
eventlist.setId(android.R.id.list);
ArrayAdapter<String> adapter=new ArrayAdapter<String>(getActivity(),android.R.layout.simple_list_item_1,events);
setListAdapter(adapter);
return eventlist;
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt("Tabno",1);
}
#Override
public void onViewStateRestored(#Nullable Bundle savedInstanceState) {
super.onViewStateRestored(savedInstanceState);
}
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
Intent expense = new Intent();
expense.setClass(getActivity(), ExpenseActivity.class);
startActivity(expense);
Bundle eventbundle=new Bundle();
eventbundle.putInt("Tabno",1);
onSaveInstanceState(eventbundle);
}
}
On your next activity add these codes :
#Override
public void onBackPressed() {
// TODO Auto-generated method stub
finish();
super.onBackPressed();
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// TODO Auto-generated method stub
switch (item.getItemId()) {
case android.R.id.home:
finish();
break;
}
return super.onOptionsItemSelected(item);
}
Override your device's back button:
#Override
public void onBackPressed() {
// TODO Auto-generated method stub
finish();
super.onBackPressed();
}
Just override the back button in your activity details:
#Override
public void onBackPressed() {
// TODO Auto-generated method stub
finish();
super.onBackPressed();
}
And it will shows the correct fragment in the viewpager

Event Handler in multiple instances of the same Fragment in Android

I have a fragment which consists of a Button and a TextView. By clicking the button, I need to change the TextView. But I need to create 18 instances of that fragment and set it to a ViewPager. My problem is how to write the button handler. Because I failed to change the corresponding TextView when I click the button. And it always changed the TextView of the same pages, no matter which the current page is.My code is like below:
fragment_first.xml
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" tools:context="com.mycompany.redotgolf.FirstFragment">
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
tools:context="com.mycompany.redotgolf.HoleRecord">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#drawable/unfilled_red_circle"
android:id="#+id/par_button"
android:layout_below="#+id/par_label"
android:layout_centerHorizontal="true"
android:gravity="center_vertical|center|center_horizontal" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/par"
android:id="#+id/par_label"
android:textSize="40dp"
android:editable="false"
android:gravity="center"
android:layout_below="#+id/flag"
android:layout_centerHorizontal="true" />
</RelativeLayout>
FirstFragme.java
public class FirstFragment extends Fragment implements View.OnClickListener {
// Store instance variables
private String title;
private int page;
public ContentItem contentItem;
public static FirstFragment newInstance(int page, String title,ContentItem contentItem) {
FirstFragment fragmentFirst = new FirstFragment();
fragmentFirst.contentItem=contentItem;
Bundle args = new Bundle();
args.putInt("someInt", page);
args.putString("someTitle", title);
fragmentFirst.setArguments(args);
return fragmentFirst;
}
// Store instance variables based on arguments passed
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
page = getArguments().getInt("someInt", 0);
title = getArguments().getString("someTitle");
}
// Inflate the view for the fragment based on layout XML
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_first, container, false);
v.setId(page);
View tv = v.findViewById(R.id.num_par);
((TextView)tv).setText(contentItem.par.toString());
return v;
}
#Override
public void onClick(View v) {
switch(v.getId()){
case R.id.par_button: {
Integer par;
View view=getView();
TextView textView=(TextView)view.findViewById(R.id.num_par);
if((par=Integer.parseInt(textView.getText().toString()))<5){
par++;
contentItem.par++;
textView.setText(par.toString());
}else{
textView.setText("3");
contentItem.par=3;
}
System.out.println(par);
break;
}
}
}
}
HoleRecord.java
public class HoleRecord extends FragmentActivity {
public FragmentPagerAdapter adapterViewPager;
static ArrayList<ContentItem> contentItems=getSampleContent();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_hole_record);
// Retrieve the ViewPager from the content view
ViewPager vp = (ViewPager) findViewById(R.id.viewpager);
// Set an OnPageChangeListener so we are notified when a new item is selected
vp.setOnPageChangeListener(mOnPageChangeListener);
// Finally set the adapter so the ViewPager can display items
adapterViewPager = new MyPagerAdapter(getSupportFragmentManager());
vp.setAdapter(adapterViewPager);
vp.setCurrentItem(1);
adapterViewPager.getItem(1);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_hole_record, menu);
return true;
}
public static class MyPagerAdapter extends FragmentPagerAdapter {
private static int NUM_ITEMS = 18;
//public FirstFragment f;
public MyPagerAdapter(FragmentManager fragmentManager) {
super(fragmentManager);
}
// Returns total number of pages
#Override
public int getCount() {
return NUM_ITEMS;
}
// Returns the fragment to display for that page
#Override
public Fragment getItem(int position) {
FirstFragment f= FirstFragment.newInstance(position, "Page"+position,contentItems.get(position));
return f;
}
// Returns the page title for the top indicator
#Override
public CharSequence getPageTitle(int position) {
return "Page " + position;
}
}
/* private final PagerAdapter mPagerAdapter = new PagerAdapter() {
LayoutInflater mInflater;
#Override
public int getCount() {
//return mItems.size();
return 10;
}
#Override
public boolean isViewFromObject(View view, Object o) {
return view == o;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
// Just remove the view from the ViewPager
container.removeView((View) object);
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
// Ensure that the LayoutInflater is instantiated
if (mInflater == null) {
mInflater =(LayoutInflater) container.getContext()
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
// Inflate item layout for images
View iv = (View) mInflater.inflate(R.layout.score_par_view, container, false);
// Add the view to the ViewPager
container.addView(iv);
return iv;
}
};*/
/**
* A OnPageChangeListener used to update the ShareActionProvider's share intent when a new item
* is selected in the ViewPager.
*/
private final ViewPager.OnPageChangeListener mOnPageChangeListener
= new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
// NO-OP
}
#Override
public void onPageSelected(int position) {
//setShareIntent(position);
}
#Override
public void onPageScrollStateChanged(int state) {
// NO-OP
}
};
static ArrayList<ContentItem> getSampleContent() {
ArrayList<ContentItem> items = new ArrayList<ContentItem>();
for(int i=1;i<=18;i++) {
items.add(new ContentItem(i));
}
return items;
}
}
activity_hole_record.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
tools:context="com.mycompany.redotgolf.HoleRecord">
<android.support.v4.view.ViewPager
android:id="#+id/viewpager"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</LinearLayout>
In above code, ContentItem class is used to store the value to be presented in the TextView

Android - Trying to open a row from SQLite into multiples fragments

I want to set the text of some EditTexts after clicking on an item of a list.
The activity:
- CadPersonActivity
And three fragments, each one having fields:
- FragmentPersonId
- FragmentPersonAddress
- FragmentPersonPhones
However those EditTexts insist on not showing what I expect.
There's no error, but blank fields.
I hope someone can help me.
Thanks in advance.
THE ACTIVITY
CadPersonActivity recover the Id in Bundle extras:
public class CadPersonActivity extends FragmentActivity implements TabListener {
private ActionBar actionBar;
private ViewPager viewPager;
private PersonPageAdapter pageAdapter;
private Person person;
private PersonDAO bd;
private Bundle extras;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_cad_person);
extras = getIntent().getExtras();
actionBar = getActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
pageAdapter = new PersonPageAdapter(getSupportFragmentManager());
viewPager = (ViewPager) findViewById(R.id.pager);
viewPager.setAdapter(pageAdapter);
viewPager.setPageTransformer(true, new ZoomOutPageTransformer());
viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageSelected(int position) {
actionBar.setSelectedNavigationItem(position);
}
#Override
public void onPageScrollStateChanged(int arg0) {
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
}
});
actionBar.addTab(actionBar.newTab().setText(getString(R.string.tab_id)).setTabListener(this));
actionBar.addTab(actionBar.newTab().setText(getString(R.string.tab_address)).setTabListener(this));
actionBar.addTab(actionBar.newTab().setText(getString(R.string.tab_phones)).setTabListener(this));
if (extras.getInt("id") > 0) {
bd = new PersonDAO(getApplicationContext());
person = bd.getPerson(extras.getInt("id"));
callSetFields();
}
}
#Override
protected void onDestroy() {
super.onDestroy();
if (bd != null)
bd.close();
}
public void onTabSelected(Tab tab, FragmentTransaction ft) {
viewPager.setCurrentItem(tab.getPosition());
}
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
}
public void onTabReselected(Tab tab, FragmentTransaction ft) {
}
private void callSetFields() {
try {
FragmentPersonId fragId = (FragmentPersonId) getSupportFragmentManager().findFragmentById(R.id.fragment_id);
fragId.setFields(person);
FragmentPersonAddress fragEndereco = (FragmentPersonAddress) getSupportFragmentManager().findFragmentById(R.id.fragment_endereco);
fragEndereco.setFields(person);
FragmentPersonPhones fragPhones = (FragmentPersonPhones) getSupportFragmentManager().findFragmentById(R.id.fragment_phones);
fragPhones.setFields(person);
} catch (Exception e) {
Toast.makeText(getApplicationContext(), "An error occurred while trying to open the record.", Toast.LENGTH_SHORT).show();
}
}
}
CallSetFields is called when a record is clicked and its Id is passed to CadPersonActivity.
The activity_cad_person.xml:
<android.support.v4.view.ViewPager xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="match_parent">
<fragment
android:id="#+id/fragment_id"
android:name="com.fragment.FragmentPersonId"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
tools:layout="#layout/fragment_id" />
<fragment
android:id="#+id/fragment_address"
android:name="com.fragment.FragmentPersonAddress"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
tools:layout="#layout/fragment_address" />
<fragment
android:id="#+id/fragment_phones"
android:name="com.fragment.FragmentPersonPhones"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
tools:layout="#layout/fragment_phones" />
</android.support.v4.view.ViewPager>
THE FRAGMENTS:
And each fragment have a code like this:
public class FragmentPersonId extends Fragment {
private EditText edtName;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_id, container,
false);
return view;
}
public void setFields(Pessoa pessoa) {
try {
edtName = (EditText) getView().findViewById(R.id.edtName);
edtName.setText(person.getName());
} catch (Exception e) {
Toast.makeText(getActivity().getApplicationContext(), "Error while setting fields.", Toast.LENGTH_SHORT).show();
}
}
}
Well, after some days searching and trying, I have this
Declare the class Person in CadPersonActivity as public static;
public static Person person;
Now, instantiate these EditTexts and call person.getName directly in onCreateView;
edtName = (EditText) view.findViewById(R.id.edtName);
edtName.setText(CadPersonActivity.person.getName());
I can't see this as a good solution, but it's the best I could find.

Send data from activity to fragment using Tab Layout with Swipeable Views in Android

I created a Tab Layout with Swipeable Views using this tutorial. I'm trying to pass a string from Activity to Fragment. I read about fragment communication and couple other topics on stackoverflow but still i get null pointer exception. Here's my code:
MainActivity.java
public class MainActivity extends FragmentActivity {
private static final int REQUEST_CODE_EMAIL = 1;
String password, email;
ViewPager viewPager;
TabsPagerAdapter tabsPagerAdapter;
ActionBar actionBar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tabsPagerAdapter = new TabsPagerAdapter(getSupportFragmentManager());
viewPager = (ViewPager) findViewById(R.id.pager);
viewPager.setOnPageChangeListener(
new ViewPager.SimpleOnPageChangeListener() {
#Override
public void onPageSelected(int position) {
actionBar = getActionBar();
actionBar.setSelectedNavigationItem(position);
}
});
viewPager.setAdapter(tabsPagerAdapter);
actionBar = getActionBar();
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) {
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(android.app.ActionBar.Tab tab,
FragmentTransaction ft) {
// TODO Auto-generated method stub
}
};
actionBar.addTab(actionBar.newTab().setText("Głowna").setTag("main").setTabListener(tabListener));
actionBar.addTab(actionBar.newTab().setText("Rachunki").setTag("bills").setTabListener(tabListener));
Bundle bundle=new Bundle();
bundle.putString("email", "emasiofnasdbjk");
EnterExitFragment enterExitFragment = new EnterExitFragment();
android.support.v4.app.FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.pager, enterExitFragment);
transaction.addToBackStack(null);
transaction.commit();
}
activity_main.xml
<android.support.v4.view.ViewPager xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="match_parent">
</android.support.v4.view.ViewPager>
TabsPagerAdapter.java
public class TabsPagerAdapter extends FragmentStatePagerAdapter {
public TabsPagerAdapter(FragmentManager fragmentManager){
super(fragmentManager);
}
#Override
public Fragment getItem(int i) {
switch (i){
case 0:
return new EnterExitFragment();
case 1:
return new BillsFragment();
}
return null;
}
#Override
public int getCount() {
return 2;
}
}
EnterExitFragment.java
public class EnterExitFragment extends Fragment{
TextView tvFloor1, tvFloor2, tvEmail;
Button btnSend;
Integer floorId, segmentId, spaceId, ticketId;
String floorName, segmentName, spaceName;
String email;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.activity_enter_exit, container, false);
tvEmail = ((TextView)rootView.findViewById(R.id.textEmail));
tvFloor1 = ((TextView)rootView.findViewById(R.id.textFloor1));
tvFloor2 = ((TextView)rootView.findViewById(R.id.textFloor2));
new FloorFreeSpaces(EnterExitFragment.this).execute();
btnSend = ((Button)rootView.findViewById(R.id.btnSend));
btnSend.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
new Floor(EnterExitFragment.this).execute();
email = getArguments().getString("email"); //line 55
tvEmail.setText(email);
}
});
return rootView;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
activity_enter_exit.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
xmlns:android="http://schemas.android.com/apk/res/android"
>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:id="#+id/textFloor1"
android:layout_gravity="center_horizontal" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:id="#+id/textFloor2"
android:layout_gravity="center_horizontal" />
<TextView
android:layout_width="354dp"
android:layout_height="93dp"
android:text="Email:"
android:id="#+id/textEmail"
android:layout_gravity="center_horizontal|bottom" />
<Button
android:layout_width="120dp"
android:layout_height="wrap_content"
android:text="SEND"
android:id="#+id/btnSend"
android:layout_gravity="center_horizontal|bottom" />
</LinearLayout>
error log
java.lang.NullPointerException
at com.carpark.EnterExitFragment$1.onClick(EnterExitFragment.java:55)
at android.view.View.performClick(View.java:4240)
at android.view.View$PerformClick.run(View.java:17722)
at android.os.Handler.handleCallback(Handler.java:730)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5303)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:739)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:555)
at dalvik.system.NativeStart.main(Native Method)
Has anyone solution for my problem? :)
EDIT: My suggestion is to make the following constructor which takes Bundle object as an argument:
public EnterExitFragment(Bundle bundle) {
super();
setArguments(bundle);
}
and call that constructor with bundle object as the argument instead of the default one in your program. That way you're sure to add the bundle before you attach it to your Activity.
Additionally, if that doesn't work, add a Bundle attribute to your EEF class, initialize it within your constructor and refer to it rather than getArguments() method:
public class EnterExitFragment extends Fragment{
TextView tvFloor1, tvFloor2, tvEmail;
Button btnSend;
Integer floorId, segmentId, spaceId, ticketId;
String floorName, segmentName, spaceName;
String email;
Bundle args;
public EnterExitFragment(Bundle bundle) {
super();
args = bundle;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.activity_enter_exit, container, false);
tvEmail = ((TextView)rootView.findViewById(R.id.textEmail));
tvFloor1 = ((TextView)rootView.findViewById(R.id.textFloor1));
tvFloor2 = ((TextView)rootView.findViewById(R.id.textFloor2));
new FloorFreeSpaces(EnterExitFragment.this).execute();
btnSend = ((Button)rootView.findViewById(R.id.btnSend));
btnSend.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
new Floor(EnterExitFragment.this).execute();
email = args.getString("email"); //line 55
tvEmail.setText(email);
}
});
return rootView;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
I do not see that you set your argument to fragment. If you did, but you forgotten to write please inform me...
Bundle bundle=new Bundle();
bundle.putString("email", "emasiofnasdbjk");
EnterExitFragment enterExitFragment = new EnterExitFragment();
enterExitFragment.setArguments(bundle); // This line is needed...
android.support.v4.app.FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.pager, enterExitFragment);
transaction.addToBackStack(null);
transaction.commit();

Categories

Resources