Fragment opened from button in activity - java

MainActivity.java
btn_search.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
FragmentOne fragment = new FragmentOne();
fragmentTransaction.add(R.id.layoutFragmentContainer, fragment);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
}
});
...
FragmentOne.java
public class FragmentOne extends Fragment {
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.list,container,false);
}
}
When I click the button search , the fragment appears , but when I click it again the application crashes.Can someone help , I am new in android and I can't solve this problem.
....
log:
Process: com.example.user1.volleyballmanager, PID: 26892
java.lang.IllegalStateException: commit already called
at android.support.v4.app.BackStackRecord.commitInternal(BackStackRecord.java:625)
at android.support.v4.app.BackStackRecord.commit(BackStackRecord.java:617)
at com.example.user1.volleyballmanager.MainActivity$2.onClick(MainActivity.java:52)---
line 52 : fragmentTransaction.commit();
at android.view.View.performClick(View.java:5156)
at android.view.View$PerformClick.run(View.java:20755)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:145)
at android.app.ActivityThread.main(ActivityThread.java:5832)
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:1399)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1194)

Put this method into your main activity
//FRAGMENT BACK STACK
public void getFragmentWithTag(Fragment fragment, String tag) {
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.addToBackStack(null);
transaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
transaction.replace(R.id.activityFrame, fragment, tag).commit();
}
You can call it from your fragment like this..
activity.getFragmentWithTag(Fragment, FragmentTag)

you cannot have multiple transaction commits.
So you need to begin and close the transaction. So when you click one, it works. Then you click again, and it give you error which says one transaction<--> one commit.

Related

Access a view inside Fragment which is initialised by using getFragmentbyTag()

The app is crashing using getFragmentManager().findFragmentByTag("HELLO");. I want to refer the textview inside HelloFragment after getting the fragment from the back stack.
MainActivity.java
HelloFragment helloFragment;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btnLoad = (Button) findViewById(R.id.btn_load);
FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction();
fragmentTransaction.add(R.id.fragment_container, new HelloFragment(), "HELLO");
fragmentTransaction.commit();
btnLoad.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction();
fragmentTransaction.add(R.id.fragment_container, new HiFragment(), "Hi");
fragmentTransaction.addToBackStack("HELLO");
fragmentTransaction.commit();
}
});
helloFragment = (HelloFragment) getFragmentManager().findFragmentByTag("HELLO");
helloFragment.textView.setText("aufa");
}
}
HelloFragment.java
TextView textView;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
/** Inflating the layout for this fragment **/
View v = inflater.inflate(R.layout.fragment, null);
textView = v.findViewById(R.id.idhai);
textView.setText("Hello");
return v;
}
}
In short I want to access a fragments textview when I get it from the stack using FindFragmentbyTag()
Log
Process: com.example.test, PID: 23551
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.test/com.example.test.MainActivity}: java.lang.NullPointerException: Attempt to read from field 'android.widget.TextView com.example.test.HelloFragment.textView' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2946)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3081)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1831)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:201)
at android.app.ActivityThread.main(ActivityThread.java:6823)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:547)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:873)
Caused by: java.lang.NullPointerException: Attempt to read from field 'android.widget.TextView com.example.test.HelloFragment.textView' on a null object reference
at com.example.test.MainActivity.onCreate(MainActivity.java:37)
at android.app.Activity.performCreate(Activity.java:7224)
at android.app.Activity.performCreate(Activity.java:7213)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1272)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2926)

Nested Fragments with MapView

I have a fragment that contains a MapView and it works by itself. When I launch that same fragment inside another fragment the app crashes.
My app crashes after mapView.onCreate(null) with the following stack. However it only crashes when it is nested in another fragment.
java.lang.ClassCastException: android.widget.ImageView cannot be cast to android.view.ViewGroup
at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:1282)
at android.app.FragmentManagerImpl.addAddedFragments(FragmentManager.java:2426)
at android.app.FragmentManagerImpl.executeOpsTogether(FragmentManager.java:2205)
at android.app.FragmentManagerImpl.removeRedundantOperationsAndExecute(FragmentManager.java:2161)
at android.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:2062)
at android.app.FragmentManagerImpl.dispatchMoveToState(FragmentManager.java:3051)
at android.app.FragmentManagerImpl.dispatchActivityCreated(FragmentManager.java:2998)
at android.app.Fragment.performActivityCreated(Fragment.java:2537)
at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:1318)
at android.app.FragmentManagerImpl.addAddedFragments(FragmentManager.java:2426)
at android.app.FragmentManagerImpl.executeOpsTogether(FragmentManager.java:2205)
at android.app.FragmentManagerImpl.removeRedundantOperationsAndExecute(FragmentManager.java:2161)
at android.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:2062)
at android.app.FragmentManagerImpl$1.run(FragmentManager.java:738)
at android.os.Handler.handleCallback(Handler.java:873)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6649)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:826)
This is my fragment which works by itself
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
view = inflater.inflate(R.layout.fragment_map_view, container, false);
setup();
return view;
}
private void setup() {
mapView = view.findViewById(R.id.mapViewFragment);
mapView.onCreate(null);
mapView.onResume();
MapsInitializer.initialize(this.getActivity().getApplicationContext());
}
and this is how I am nesting the fragments
FragmentTransaction transaction = getChildFragmentManager().beginTransaction();
transaction.add(R.id.frameLayoutBuffer, new MapViewFragment()).commit();
The id is from a framelayout.
If I change to another Fragment, the other fragment displays just fine, so it something to do with the MapView.
Both fragments also do not contain any ImageView, any help about this problem will be appreciated.
I fixed by calling the setup method inside the onResume() and changing view.findViewById() to getView().findViewbyId()
Edit: Actually that did not fix the problem. I added a delay before creating the map in another thread, and that seemed to fix.

FragmentTransaction is throwing null reference

I have loader fragment and I am calling another fragment from the loader fragment.Everything is working fine but suddenly my fragment loader is giving me an error.In the loader fragment I am displaying progress bar for 5sec and after that another fragment will display.
Here is my code:-
loader fragment.java
package com.example.user.attendance;
public class Loader_fragment extends Fragment {
AVLoadingIndicatorView Loader;
Runnable runnable;
Handler handler;
FragmentManager fragmentManager;
FragmentTransaction fragmentTransaction;
Timer timer;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View loadder_fragment=inflater.inflate(R.layout.fragment_loader_fragment, container, false);
Loader=(AVLoadingIndicatorView)loadder_fragment.findViewById(R.id.loder_login);
handler=new Handler();
runnable=new Runnable() {
#Override
public void run() {
Loader.setVisibility(View.INVISIBLE);
timer.cancel();
fragmentManager=getFragmentManager();
fragmentTransaction=fragmentManager.beginTransaction();
fragmentTransaction.setCustomAnimations(R.animator.slide_in_left,R.animator
.slide_out_left,R.animator.slide_in_right,R.animator.slide_out_right);
Home_Screen home_screen=new Home_Screen();
fragmentTransaction.replace(R.id.Home_screen_fragment,home_screen);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
}
};
timer=new Timer();
timer.schedule(new TimerTask() {
#Override
public void run() {
handler.post(runnable);
}
}, 5000,5000);
/* if(Loader.setVisibility(View.INVISIBLE)==1){
}*/
return loadder_fragment;
}
}
Logcat is showing an error:-
Process: com.example.user.attendance, PID: 1200
java.lang.NullPointerException: Attempt to invoke virtual method 'android.app.FragmentTransaction android.app.FragmentManager.beginTransaction()' on a null object reference
at com.example.user.attendance.Loader_fragment$1.run(Loader_fragment.java:44)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:7402)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)
Why it is showing null object reference in the fragment.
Don't perform View manipulation in onCreateView. Instead, move it to onViewCreated method. Reason: your fragment has not yet setup the views.
Besides, replace:
fragmentManager = getFragmentManager();
with the following:
fragmentManager = getChildFragmentManager();
Try this
FragmentTransaction fragmentTransaction = getActivity()
.getFragmentManager().beginTransaction();
fragmentTransaction.setCustomAnimations(R.animator.slide_in_left,
R.animator.slide_out_left,
R.animator.slide_in_right,
R.animator.slide_out_right);
fragmentTransaction.replace(R.id.Home_screen_fragment, home_screen);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();

Android, Fragments: Problems with Replace and remove methods

I'm learning to use the fragments and I met some problems about replace and remove methods.
Here is my activity class:
public class MainActivity extends AppCompatActivity implements BlankFragment.OnFragmentInteractionListener {
private BlankFragment fragment1;
private BlankFragment fragment2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragment1 = BlankFragment.newInstance("Fragment 1","");
fragmentTransaction.add(R.id.linearLayout,fragment1);
fragmentTransaction.commit();
}
public void onClick(View arg0)
{
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
switch (arg0.getId())
{
case R.id.button:
fragment2 = BlankFragment.newInstance("Fragment 2", "");
fragmentTransaction.add(R.id.linearLayout, fragment2);
fragmentTransaction.commit();
break;
case R.id.button2:
Toast.makeText(this,"REMOVE",Toast.LENGTH_SHORT).show();
if(fragment2!=null)
{
fragmentTransaction.remove(fragment2);
fragmentTransaction.commit();
}
break;
case R.id.button3:
fragmentTransaction.replace(R.id.linearLayout,fragment2);
fragmentTransaction.commit();
break;
}
}
public void onFragmentInteraction(Uri uri)
{
}
}
Here is the Fragment Class:
public class BlankFragment extends Fragment {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
private OnFragmentInteractionListener mListener;
public BlankFragment() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* #param param1 Parameter 1.
* #param param2 Parameter 2.
* #return A new instance of fragment BlankFragment.
*/
// TODO: Rename and change types and number of parameters
public static BlankFragment newInstance(String param1, String param2) {
BlankFragment fragment = new BlankFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.fragment_blank, container, false);
TextView textView = ((TextView) rootView.findViewById(R.id.textView));
textView.setText(mParam1);
return rootView;
}
// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentInteractionListener) {
mListener = (OnFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentInteractionListener");
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
/**
* This interface must be implemented by activities that contain this
* fragment to allow an interaction in this fragment to be communicated
* to the activity and potentially other fragments contained in that
* activity.
* <p>
* See the Android Training lesson <a href=
* "http://developer.android.com/training/basics/fragments/communicating.html"
* >Communicating with Other Fragments</a> for more information.
*/
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
void onFragmentInteraction(Uri uri);
}
}
Here is the manifest:
<?xml version="1.0" encoding="utf-8"?>
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
Well, I have 2 fragments. When I click the first button, I want to add the second fragment.
If I click this button 10 times, will there be 11 fragments in the back stack (10 fragments number 2 and 1 number 1)? Or only two fragments?
When I click the second button, I remove the fragment number 2, if there is, of course.
But if I click two or more times the first button, if I click 200 times the second button, the second fragment remains...why?
When I click the third button, I want to replace the second fragment with the previous fragment.
If I click two or more times the first button, if I click the third button and then the second button, the second fragment doesn't remain...why?
If I open the app and I click the third button or I click first the second button and then the third, the app crashes
Here is the logcat
02-07 21:33:31.040 17090-17090/com.example.utente.fragment E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.utente.fragment, PID: 17090
java.lang.IllegalStateException: Could not execute method for android:onClick
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:293)
at android.view.View.performClick(View.java:5610)
at android.view.View$PerformClick.run(View.java:22265)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6077)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Method.invoke(Native Method)
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:288)
at android.view.View.performClick(View.java:5610) 
at android.view.View$PerformClick.run(View.java:22265) 
at android.os.Handler.handleCallback(Handler.java:751) 
at android.os.Handler.dispatchMessage(Handler.java:95) 
at android.os.Looper.loop(Looper.java:154) 
at android.app.ActivityThread.main(ActivityThread.java:6077) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755) 
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.Class java.lang.Object.getClass()' on a null object reference
at android.support.v4.app.BackStackRecord.doAddOp(BackStackRecord.java:380)
at android.support.v4.app.BackStackRecord.replace(BackStackRecord.java:430)
at android.support.v4.app.BackStackRecord.replace(BackStackRecord.java:421)
at com.example.utente.fragment.MainActivity.onClick(MainActivity.java:50)
at java.lang.reflect.Method.invoke(Native Method) 
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:288) 
at android.view.View.performClick(View.java:5610) 
at android.view.View$PerformClick.run(View.java:22265) 
at android.os.Handler.handleCallback(Handler.java:751) 
at android.os.Handler.dispatchMessage(Handler.java:95) 
at android.os.Looper.loop(Looper.java:154) 
at android.app.ActivityThread.main(ActivityThread.java:6077) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755) 
If I click the first button and then the third, the app doesn't crash...why?
Where are the errors?
The buttons aren't in the fragments but in the activity
First of all, check out this post.
Well, I have 2 fragments. When I click the first button, I want to add
the second fragment. If I click this button 10 times, will there be 11
fragments in the back stack (10 fragments number 2 and 1 number 1)? Or
only two fragments?
If you want to add the transaction to the back stack, add
fragmentTransaction.addToBackStack(null);
before you commit the transaction. Then you can later use popBackStack() on the FragmentManager.
When I click the second button, I remove the fragment number 2, if
there is, of course. But if I click two or more times the first
button, if I click 200 times the second button, the second fragment
remains...why?
This is because when you click the first button, you set fragment2 to a new instance of the fragment, even if it already is one, and thus losing the reference to the old one.
Every time you press the second button after you have pressed the first button two times, it will try to remove the latest created fragment every time. Therefore it will always show the second latest fragment you created, which will always be "Fragment 2".
When I click the third button, I want to replace the second fragment
with the previous fragment. If I click two or more times the first
button, if I click the third button and then the second button, the
second fragment doesn't remain...why?
The replace() method will remove all the previously added fragments and add the one you are trying to add. When you press the third button, you will remove all of the other fragments you have and add fragment2. When you then press the second button it will remove fragment2, and then there is nothing else to show.
If I open the app and I click the third button or I click first the
second button and then the third, the app crashes
This is because if you don't press the first button, fragment2 will be null. Pressing the second button will do nothing, since fragment2 is null. Pressing the third button will try to add fragment2, which is null, which then shows the error.
It seems like your second and third button practically is meant to do the same. Maybe reduce it to two buttons, where the first adds a fragment, and the second pops the backstack.
Remove the onClick() method, you could do it the primary times you do it:
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
Button button = (Button)findViewById(R.id.button);
Button button2 = (Button)findViewById(R.id.button2);
Button button3 = (Button)findViewById(R.id.button3);
button.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
fragment2 = BlankFragment.newInstance("Fragment 2", "");
fragmentTransaction.add(R.id.linearLayout, fragment2);
fragmentTransaction.commit();
}
});
button2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
Toast.makeText(this,"REMOVE",Toast.LENGTH_SHORT).show();
if(fragment2!=null)
{
fragmentTransaction.remove(fragment2);
fragmentTransaction.commit();
}
}
});
button3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
fragmentTransaction.replace(R.id.linearLayout,fragment2);
fragmentTransaction.commit();
}
});

IllegalArgumentException caused by binary XML file (Android)

i have a basic navigation with 3 tabs. One of them contains a fragment with google maps in it. However the navigation isn't good, it keeps crashing after i select the tab for the second time.
It says it is because of the XML file of the maps which in my opinion doesn't have anything wrong. Can anyone see my error which i am blinded for right now?
Logcat :
android.view.InflateException: Binary XML file line #7: Error inflating class fragment
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:719)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:761)
at android.view.LayoutInflater.inflate(LayoutInflater.java:498)
at android.view.LayoutInflater.inflate(LayoutInflater.java:398)
at com.example.dell.animalz.MapsFragment.onCreateView(MapsFragment.java:22)
at android.support.v4.app.Fragment.performCreateView(Fragment.java:1504)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:942)
at android.support.v4.app.FragmentManagerImpl.attachFragment(FragmentManager.java:1297)
at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:672)
at
android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1484)
at
android.support.v4.app.FragmentManagerImpl.executePendingTransactions(FragmentManager.java:482)
at
android.support.v4.app.FragmentPagerAdapter.finishUpdate(FragmentPagerAdapter.java:141)
at android.support.v4.view.ViewPager.populate(ViewPager.java:1073)
at android.support.v4.view.ViewPager.setCurrentItemInternal(ViewPager.java:555)
at android.support.v4.view.ViewPager.setCurrentItemInternal(ViewPager.java:514)
at android.support.v4.view.ViewPager.setCurrentItem(ViewPager.java:495)
at com.example.dell.animalz.HomeActivity.onTabSelected(HomeActivity.java:67)
at com.android.internal.app.ActionBarImpl.selectTab(ActionBarImpl.java:674)
at com.android.internal.app.ActionBarImpl$TabImpl.select(ActionBarImpl.java:1217)
at
com.android.internal.widget.ScrollingTabContainerView$TabClickListener.onClick(ScrollingTabContainerView.java:976)
at android.view.View.performClick(View.java:4637)
at android.view.View$PerformClick.run(View.java:19422)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5586)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1268)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1084)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.IllegalArgumentException: Binary XML file line #7: Duplicate id 0x7f070067, tag null, or parent id 0x0 with another fragment for com.google.android.gms.maps.SupportMapFragment
at android.support.v4.app.FragmentActivity.onCreateView(FragmentActivity.java:297)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:691)
            
HomeActivity.java
public class HomeActivity extends FragmentActivity implements ActionBar.TabListener {
ViewPager mViewPager = null;
private TabsMenuAdapter mAdapter;
private ActionBar actionBar;
private String []tabs = {"News", "Animalz", "Maps"};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.home_layout);
mViewPager = (ViewPager)findViewById(R.id.viewpager1);
actionBar = getActionBar();
mAdapter = new TabsMenuAdapter(getSupportFragmentManager());
mViewPager.setAdapter(mAdapter);
actionBar.setHomeButtonEnabled(false);
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
for(String tab_names : tabs){
actionBar.addTab(actionBar.newTab().setText(tab_names).setTabListener(this));
}
mViewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener(){
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
actionBar.setSelectedNavigationItem(position);
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
}
#Override
public void onTabSelected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
mViewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
}
#Override
public void onTabReselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
mViewPager.setCurrentItem(tab.getPosition());
}
}
Maps.java
public class MapsFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.maps_layout, container, false);
return rootView;
}
}
Maps.xml
<?xml version="1.0" encoding="utf-8"?>
<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"/>
</RelativeLayout>
Any help would be appreciated, thanks in advance !
You have to remove the MapFragment in the onDestroyView() method of the Fragment that contains the map, with referring to this answer, you must do the following:
// override the onDestroyView of the fragment
#Override
public void onDestroyView() {
super.onDestroyView();
MapFragment f = (MapFragment) getFragmentManager()
.findFragmentById(R.id.the_map);
if (f != null)
getFragmentManager().beginTransaction().remove(f).commit();
}
Every time check your parent view empty or not. If yes then remove. Change your Maps.java.
private static View view;
#Override
public View onCreateView(LayoutInflater inflater,ViewGroup group,Bundle bundle)
{
if(view!=null)
{
ViewGroup parent =(ViewGroup)view.getParent();
if(parent!=null)
parent.removeView(view);
}
try{
view=inflater.inflate(R.layout.maps, group, false);
........
}
catch(Exception e)
{
Log.e("ERROR", ""+e);
}
return view;
}

Categories