Unable to attach Fragment to activity through XML - android

I created a new activity by right clicking on my project and selecting new > fragment > blank fragment.
Here is the auto generated fragment. The only thing I added was the lines under the onCreateView() method. I also implemented onFragmentInteractionListener on the activity that I want to attatch this fragment to. I made sure to implement the onFragmentInteraction(...) method on that Activity, but left it blank.
Whats the problem here?
import android.app.Activity;
import android.net.Uri;
import android.os.Bundle;
import android.text.Html;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.support.v4.app.Fragment;
public class FragmentHowToPlay 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;
/**
* 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 FragmentHowToPlay.
*/
// TODO: Rename and change types and number of parameters
public static FragmentHowToPlay newInstance(String param1, String param2) {
FragmentHowToPlay fragment = new FragmentHowToPlay();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
public FragmentHowToPlay() {
// Required empty public constructor
}
#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 v = inflater.inflate(R.layout.fragment_fragment_how_to_play, container, false);
TextView text1 = (TextView) v.findViewById(R.id.text1);
text1.setText(Html.fromHtml(getString(R.string.my_text)));
return v;
}
// 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(Activity activity) {
super.onAttach(activity);
try {
mListener = (OnFragmentInteractionListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.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
public void onFragmentInteraction(Uri uri);
}
}
Here is the logcat error:
Process: mjj.fling, PID: 8965
java.lang.RuntimeException: Unable to start activity ComponentInfo{mjj.fling/mjj.fling.HowToPlayActivity}: android.view.InflateException: Binary XML file line #19: Error inflating class fragment
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2379)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2441)
at android.app.ActivityThread.access$800(ActivityThread.java:162)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1349)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5431)
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:913)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:706)
Caused by: android.view.InflateException: Binary XML file line #19: Error inflating class fragment
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:763)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:806)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:809)
at android.view.LayoutInflater.inflate(LayoutInflater.java:504)
at android.view.LayoutInflater.inflate(LayoutInflater.java:414)
at android.view.LayoutInflater.inflate(LayoutInflater.java:365)
at com.android.internal.policy.impl.PhoneWindow.setContentView(PhoneWindow.java:402)
at android.app.Activity.setContentView(Activity.java:2214)
at mjj.fling.HowToPlayActivity.onCreate(HowToPlayActivity.java:16)
at android.app.Activity.performCreate(Activity.java:6093)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1106)
Caused by: android.app.Fragment$InstantiationException: Trying to instantiate a class mjj.fling.FragmentHowToPlay that is not a Fragment
at android.app.Fragment.instantiate(Fragment.java:606)
at android.app.Fragment.instantiate(Fragment.java:582)
at android.app.FragmentManagerImpl.onCreateView(FragmentManager.java:2108)
at android.app.Activity.onCreateView(Activity.java:5431)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:733)
Caused by: java.lang.ClassCastException
XML LAYOUT for Activity that Fragment is being attached to
<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="mjj.fling.HowToPlayActivity"
android:background="#01051D">
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/scrollView"
android:layout_alignParentTop="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:layout_marginTop="42dp" >
<fragment
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:name="mjj.fling.FragmentHowToPlay"
android:id="#+id/fragment"
tools:layout="#layout/fragment_fragment_how_to_play" />
</ScrollView>

You fragment extends android.support.v4.app.Fragment instead of android.app.Fragment -- see the import declaration. The former is meant to be used by FragmentActivity (or better yet the new AppCompatActivity) from the support library, not with regular android.app.Activity. You need to change one or the other and in general be consistent about what you are using throughout the app.

Related

Error while setting custom view for each tab in Tab layout

I am getting error while setting up custom views for tabs in tab layout. Every tab runs fine on the first run, but when I swipe between tabs, runtime error appears. I am just trying out tab layout for the first time, can somebody help me with this ?
E/AndroidRuntime: FATAL EXCEPTION: main Process: com.rocks.mafia.entrancesecurity, PID: 18095
android.view.InflateException: Binary XML file line #6: Binary XML file line #6: Error inflating class fragment
at android.view.LayoutInflater.inflate(LayoutInflater.java:539)
at android.view.LayoutInflater.inflate(LayoutInflater.java:423)
at com.rocks.mafia.entrancesecurity.MainActivity$PlaceholderFragment.onCreateView(MainActivity.java:137)
at android.support.v4.app.Fragment.performCreateView(Fragment.java:2080)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1108)
at android.support.v4.app.FragmentManagerImpl.attachFragment(FragmentManager.java:1468)
at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:791)
at android.support.v4.app.FragmentManagerImpl.execSingleAction(FragmentManager.java:1638)
at android.support.v4.app.BackStackRecord.commitNowAllowingStateLoss(BackStackRecord.java:679)
at android.support.v4.app.FragmentPagerAdapter.finishUpdate(FragmentPagerAdapter.java:143)
at android.support.v4.view.ViewPager.populate(ViewPager.java:1240)
at android.support.v4.view.ViewPager.populate(ViewPager.java:1088)
at android.support.v4.view.ViewPager$3.run(ViewPager.java:275)
at android.view.Choreographer$CallbackRecord.run(Choreographer.java:894)
at android.view.Choreographer.doCallbacks(Choreographer.java:696)
at android.view.Choreographer.doFrame(Choreographer.java:628)
at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:880)
at android.os.Handler.handleCallback(Handler.java:815)
at android.os.Handler.dispatchMessage(Handler.java:104)
at android.os.Looper.loop(Looper.java:207)
at android.app.ActivityThread.main(ActivityThread.java:5740)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:905)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:766)
Caused by: android.view.InflateException: Binary XML file line #6: Error inflating class fragment
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:782)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:704)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:835)
at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:798)
at android.view.LayoutInflater.inflate(LayoutInflater.java:515)
at android.view.LayoutInflater.inflate(LayoutInflater.java:423) 
at com.rocks.mafia.entrancesecurity.MainActivity$PlaceholderFragment.onCreateView(MainActivity.java:137) 
at android.support.v4.app.Fragment.performCreateView(Fragment.java:2080) 
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1108) 
at android.support.v4.app.FragmentManagerImpl.attachFragment(FragmentManager.java:1468) 
at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:791) 
at android.support.v4.app.FragmentManagerImpl.execSingleAction(FragmentManager.java:1638) 
at android.support.v4.app.BackStackRecord.commitNowAllowingStateLoss(BackStackRecord.java:679) 
at android.support.v4.app.FragmentPagerAdapter.finishUpdate(FragmentPagerAdapter.java:143) 
at android.support.v4.view.ViewPager.populate(ViewPager.java:1240) 
at android.support.v4.view.ViewPager.populate(ViewPager.java:1088) 
at android.support.v4.view.ViewPager$3.run(ViewPager.java:275) 
at android.view.Choreographer$CallbackRecord.run(Choreographer.java:894) 
at android.view.Choreographer.doCallbacks(Choreographer.java:696) 
at android.view.Choreographer.doFrame(Choreographer.java:628) 
at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:880) 
at android.os.Handler.handleCallback(Handler.java:815) 
at android.os.Handler.dispatchMessage(Handler.java:104) 
at android.os.Looper.loop(Looper.java:207) 
at android.app.ActivityThread.main(ActivityThread.java:5740) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:905) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:766) 
Caused by: java.lang.IllegalArgumentException: Binary XML file line #6: Duplicate id 0x7f0c009f, tag null, or parent id 0xffffffff with another fragment for com.rocks.mafia.entrancesecurity.HistoryFragment
at android.support.v4.app.FragmentManagerImpl.onCreateView(FragmentManager.java:2422)
at android.support.v4.view.LayoutInflaterCompatHC$FactoryWrapperHC.onCreateView(LayoutInflaterCompatHC.java:44)
at android.view.LayoutInflater$FactoryMerger.onCreateView(LayoutInflater.java:186)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:746)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:704) 
at android.view.LayoutInflater.rInflate(LayoutInflater.java:835) 
at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:798) 
at android.view.LayoutInflater.inflate(LayoutInflater.java:515) 
at android.view.LayoutInflater.inflate(LayoutInflater.java:423) 
at com.rocks.mafia.entrancesecurity.MainActivity$PlaceholderFragment.onCreateView(MainActivity.java:137) 
at android.support.v4.app.Fragment.performCreateView(Fragment.java:2080) 
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1108) 
at android.support.v4.app.FragmentManagerImpl.attachFragment(FragmentManager.java:1468) 
at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:791) 
at android.support.v4.app.FragmentManagerImpl.execSingleAction(FragmentManager.java:1638) 
at android.support.v4.app.BackStackRecord.commitNowAllowingStateLoss(BackStackRecord.java:679) 
at android.support.v4.app.FragmentPagerAdapter.finishUpdate(FragmentPagerAdapter.java:143) 
at android.support.v4.view.ViewPager.populate(ViewPager.java:1240) 
at android.support.v4.view.ViewPager.populate(ViewPager.java:1088) 
at android.support.v4.view.ViewPager$3.run(ViewPager.java:275) 
at android.view.Choreographer$CallbackRecord.run(Choreographer.java:894) 
at android.view.Choreographer.doCallbacks(Choreographer.java:696) 
at android.view.Choreographer.doFrame(Choreographer.java:628) 
at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:880) 
at android.os.Handler.handleCallback(Handler.java:815) 
at android.os.Handler.dispatchMessage(Handler.java:104) 
at android.os.Looper.loop(Looper.java:207) 
at android.app.ActivityThread.main(ActivityThread.java:5740) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:905) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:766) 
MainActivity.java
package com.rocks.mafia.entrancesecurity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.support.design.widget.TabLayout;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
/**
* The {#link android.support.v4.view.PagerAdapter} that will provide
* fragments for each of the sections. We use a
* {#link FragmentPagerAdapter} derivative, which will keep every
* loaded fragment in memory. If this becomes too memory intensive, it
* may be best to switch to a
* {#link android.support.v4.app.FragmentStatePagerAdapter}.
*/
private SectionsPagerAdapter mSectionsPagerAdapter;
/**
* The {#link ViewPager} that will host the section contents.
*/
private ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
// Create the adapter that will return a fragment for each of the three
// primary sections of the activity.
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.container);
mViewPager.setAdapter(mSectionsPagerAdapter);
mViewPager.setCurrentItem(1);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(mViewPager);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
}
#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_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
switch (id) {
case R.id.action_logout:
SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putBoolean(getString(R.string.isLogin), false);
editor.commit();
Intent intent = new Intent(this, WelcomeActivity.class);
startActivity(intent);
break;
case R.id.action_settings:
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
private static final String ARG_SECTION_NUMBER = "section_number";
public PlaceholderFragment() {
}
/**
* Returns a new instance of this fragment for the given section
* number.
*/
public static PlaceholderFragment newInstance(int sectionNumber) {
PlaceholderFragment fragment = new PlaceholderFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
if (getArguments().getInt(ARG_SECTION_NUMBER) == 1) {
View rootView = inflater.inflate(R.layout.fragment_profile, container, false);
return rootView;
} else if (getArguments().getInt(ARG_SECTION_NUMBER) == 3) {
View rootView = inflater.inflate(R.layout.history_display, container, false);
return rootView;
}
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
TextView textView = (TextView) rootView.findViewById(R.id.section_label);
textView.setText(getString(R.string.section_format, getArguments().getInt(ARG_SECTION_NUMBER)));
return rootView;
}
}
/**
* A {#link FragmentPagerAdapter} that returns a fragment corresponding to
* one of the sections/tabs/pages.
*/
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
// getItem is called to instantiate the fragment for the given page.
// Return a PlaceholderFragment (defined as a static inner class below).
return PlaceholderFragment.newInstance(position + 1);
}
#Override
public int getCount() {
// Show 3 total pages.
return 3;
}
#Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return "Profile";
case 1:
return "Requests";
case 2:
return "History";
}
return null;
}
}
}
`
history_display.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<fragment
android:id="#+id/historyFrag"
android:name="com.rocks.mafia.entrancesecurity.HistoryFragment"
android:layout_width="match_parent"
android:layout_height="match_parent">
</fragment>
</LinearLayout>
fragment_profile.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.rocks.mafia.entrancesecurity.ProfileFragment">
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true">
<android.support.design.widget.AppBarLayout
android:id="#+id/app_bar"
android:layout_width="match_parent"
android:layout_height="218dp"
android:background="#color/colorPrimary"
android:theme="#style/AppTheme.AppBarOverlay">
<android.support.design.widget.CollapsingToolbarLayout
android:id="#+id/toolbar_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
app:contentScrim="?attr/colorPrimary"
app:expandedTitleMarginEnd="64dp"
app:expandedTitleMarginStart="48dp"
app:layout_scrollFlags="scroll|exitUntilCollapsed">
<ImageView
android:layout_width="match_parent"
android:layout_height="150dp"
android:adjustViewBounds="true"
android:src="#drawable/ln_logo"
app:layout_collapseMode="parallax"
app:layout_collapseParallaxMultiplier="0.7" />
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?android:attr/actionBarSize"
android:minHeight="?android:attr/actionBarSize"
app:layout_collapseMode="pin"
app:layout_scrollFlags="scroll|exitUntilCollapsed"
app:popupTheme="#style/AppTheme.PopupOverlay" />
</android.support.design.widget.CollapsingToolbarLayout>
</android.support.design.widget.AppBarLayout>
<include layout="#layout/content_profile" />
<android.support.design.widget.FloatingActionButton
android:id="#+id/fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="#dimen/fab_margin"
android:src="#drawable/ic_star_black"
app:layout_anchor="#id/app_bar"
app:layout_anchorGravity="bottom|end" />
</android.support.design.widget.CoordinatorLayout>
</FrameLayout>
fragment_main.xml
<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:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.rocks.mafia.entrancesecurity.MainActivity$PlaceholderFragment">
<TextView
android:id="#+id/section_label"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</RelativeLayout>
The answer is simple : don't use xml fragments at all. It is bad supported, has a lot of limitations, like that with which you met. The problem is that two same xml fragments ( without workarounds) couldn't exist together, because them share same fragment id. The crash happends when history fragment tried to recreate it's view, due to page changing process, but previous one still hadn't been garbage collected.
Sure, you still could setOffscreenPageLimit on ViewPager to 2 in your case ( all views will stay in memory) , but you should just remove you xml fragment and attach it programmatically if really needed.

Android viewpager inside dialogfragment, app crashed with no view found for id using API 17

for the issue in question. Tried Searching for solutions and says getChildFragmentManager/getSupportFragmentManager should be used, but the problem is even with updated android sdk lib using the android support v13 (which has v4) installed, Eclipse Luna still cannot recognize getChildFragmentManager/getSupportFragmentManager. I also tried importing the support.app.v4 namespace but that will only make the ScreenSlidePagerAdapter's FragmentManager throw a type error.
DialogFragment Class which contains the view pager:
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.app.Fragment;
import android.app.FragmentManager;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v13.app.FragmentStatePagerAdapter;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
public class EnlargeItemPicture extends DialogFragment {
/**
* The number of pages to show in the view slider
*/
private static int NUM_PAGES = 1; // [Temp] set the total page number according to total items under current selected category instead next time
/**
* The pager widget, which handles animation and allows swiping horizontally to access previous
* and next wizard steps.
*/
private ViewPager pager;
/**
* The pager adapter, which provides the pages to the view pager widget.
*/
private PagerAdapter pagerAdapter;
private View customDialogView;
private String imagePath;
private String itemName;
#Override
public Dialog onCreateDialog(Bundle savedInstanceState)
{
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
// Get the layout inflater
LayoutInflater inflater = getActivity().getLayoutInflater();
// instead of inflating the activity with imageview only, inflate the viewpager activity here
customDialogView = inflater.inflate(R.layout.item_pager, null);
// Instantiate a ViewPager and a PagerAdapter.
pager = (ViewPager) customDialogView.findViewById(R.id.pager);
pagerAdapter = new ScreenSlidePagerAdapter(super.getFragmentManager());
pager.setAdapter(pagerAdapter);
/**
* Inflate and set the layout for the dialog
* Pass null as the parent view because its going in the dialog layout
* customDialogView = inflater.inflate(R.layout.dialog_item_picture, null);
* ImageView img = (ImageView) customDialogView.findViewById(R.id.enlargepicture);
* img.setImageBitmap(BitmapFactory.decodeFile(imagePath));
*/
builder.setView(customDialogView)
.setNeutralButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
return builder.create();
}
public EnlargeItemPicture(String picturePath, String itemName)
{
imagePath = picturePath;
this.itemName = itemName;
}
/**
* A simple pager adapter that represents n objects, in
* sequence.
*/
private class ScreenSlidePagerAdapter extends FragmentStatePagerAdapter {
public ScreenSlidePagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
return ScreenSlidePageItemViewFragment.create(position, "");
}
#Override
public int getCount() {
return NUM_PAGES;
}
}
}
ScreenSlidePageItemViewFragment Class that holds the fragment to be inserted to viewpager:
import android.os.Bundle;
import android.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class ScreenSlidePageItemViewFragment extends Fragment {
/**
* The argument key for the page number this fragment represents.
*/
public static final String ARG_PAGE = "page";
/**
* The argument key for the item Title this fragment represents.
*/
public static final String ARG_ITEM_TITLE = "item_title";
/**
* The fragment's page number, which is set to the argument value for {#link #ARG_PAGE}.
*/
private int pageNumber;
private String itemTitle;
/**
* Factory method for this fragment class. Constructs a new fragment for the given page number and Title.
*/
public static ScreenSlidePageItemViewFragment create(int pageNumber, String itemTitle) {
ScreenSlidePageItemViewFragment fragment = new ScreenSlidePageItemViewFragment();
Bundle args = new Bundle();
args.putInt(ARG_PAGE, pageNumber);
args.putString(ARG_ITEM_TITLE, itemTitle);
fragment.setArguments(args);
return fragment;
}
/**
* Factory method for this fragment class. Constructs a new fragment.
*/
public ScreenSlidePageItemViewFragment()
{ }
/**
* Gets the arguments and pass to this properties
*/
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
pageNumber = getArguments().getInt(ARG_PAGE);
itemTitle = getArguments().getString(ARG_ITEM_TITLE);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout containing a title and body text.
ViewGroup rootView = (ViewGroup) inflater
.inflate(R.layout.item_page_view, container, true);
/// TODO: add listeners to each views here
return rootView;
}
/**
* Returns the page number represented by this fragment object.
*/
public int getPageNumber() {
return pageNumber;
}
/**
* Returns the item title represented by this fragment object.
*/
public String getItemTitle(){
return itemTitle;
}
}
Here is the XML file for layout with viewpager:
<android.support.v4.view.ViewPager xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/pager"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
Here is the XML file for layout that will be inserted to viewpager:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:id="#+id/content">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<ImageView
android:id="#+id/itemimage"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</RelativeLayout>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<TextView
android:id="#+id/itemDesc"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Medium Text"
android:textAppearance="?android:attr/textAppearanceMedium" />
</RelativeLayout>
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<Button
android:id="#+id/minusbtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:text="-" />
<Button
android:id="#+id/addbtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_toLeftOf="#+id/minusbtn"
android:text="+" />
<TextView
android:id="#+id/itemTotal"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/addbtn"
android:layout_alignBottom="#+id/addbtn"
android:layout_toLeftOf="#+id/addbtn"
android:text="Medium Text"
android:textAppearance="?android:attr/textAppearanceMedium" />
</RelativeLayout>
</LinearLayout>
I'm at lost here, or perhaps i had it implemented wrong? or something that i had missed?
Plenty of Thanks in Advance!
It may not be an answer in a way, at least it solve one of the causes which gives a new type of exception in which i will post another question if i cannot resolved it with answers from similar problems. The one that got resolved here is I am now able to use the getChildFragmentManager and getSupportFragmentManager function and the answer can be found here: Eclipse Android missing getSupportedFragmentManager and getChildFragmentManager.
I think you should use:
View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState);
Instead of:
Dialog onCreateDialog(Bundle savedInstanceState);
It's helped for me.
Also, check out this link:
fragments in viewpager, no view found error

Fragment crashes on orientation change

Every time orientation changes Fragment crashes with error:
01-26 12:46:43.215 2895-2895/com.cbsystematic.mobile.itvdn
E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.cbsystematic.mobile.itvdn, PID: 2895
java.lang.RuntimeException: Unable to destroy activity {com.cbsystematic.mobile.itvdn/com.cbsystematic.mobile.itvdn.NavigationActivity}: java.lang.IllegalStateException: Can not perform this action after onSaveInstanceState
at android.app.ActivityThread.performDestroyActivity(ActivityThread.java:3671)
at android.app.ActivityThread.handleDestroyActivity(ActivityThread.java:3689)
at android.app.ActivityThread.handleRelaunchActivity(ActivityThread.java:3889)
at android.app.ActivityThread.access$900(ActivityThread.java:144)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1284)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5221)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
Caused by: java.lang.IllegalStateException: Can not perform this action after onSaveInstanceState
at android.support.v4.app.FragmentManagerImpl.checkStateLoss(FragmentManager.java:1365)
at android.support.v4.app.FragmentManagerImpl.popBackStackImmediate(FragmentManager.java:516)
at com.cbsystematic.mobile.itvdn.LessonsFragment.replaceFragment(LessonsFragment.java:126)
at com.cbsystematic.mobile.itvdn.LessonsFragment.onDetach(LessonsFragment.java:119)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1080)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1126)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1108)
at android.support.v4.app.FragmentManagerImpl.dispatchDestroy(FragmentManager.java:1954)
at android.support.v4.app.FragmentActivity.onDestroy(FragmentActivity.java:313)
at android.support.v7.app.ActionBarActivity.onDestroy(ActionBarActivity.java:169)
at android.app.Activity.performDestroy(Activity.java:6112)
at android.app.Instrumentation.callActivityOnDestroy(Instrumentation.java:1140)
at android.app.ActivityThread.performDestroyActivity(ActivityThread.java:3658)
            at android.app.ActivityThread.handleDestroyActivity(ActivityThread.java:3689)
            at android.app.ActivityThread.handleRelaunchActivity(ActivityThread.java:3889)
            at android.app.ActivityThread.access$900(ActivityThread.java:144)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1284)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:135)
            at android.app.ActivityThread.main(ActivityThread.java:5221)
            at java.lang.reflect.Method.invoke(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:372)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
I need to save state of current Fragment.
Fragment class code:
public class LessonsFragment extends Fragment implements AbsListView.OnItemClickListener {
private OnFragmentInteractionListener mListener;
/**
* The fragment's ListView.
*/
private AbsListView mListView;
/**
* The Adapter which will be used to populate the ListView/GridView with
* Views.
*/
private ListAdapter mAdapter;
private static String courseUrl;
private ParserJson parserJson = new ParserJson();
private TextView descriptionTextView;
private DescriptionData descriptionData;
// TODO: Rename and change types of parameters
public static LessonsFragment newInstance(String url) {
LessonsFragment fragment = new LessonsFragment();
courseUrl = url;
return fragment;
}
/**
* Mandatory empty constructor for the fragment manager to instantiate the
* fragment (e.g. upon screen orientation changes).
*/
public LessonsFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// TODO: Change Adapter to display your content
mAdapter = new LessonsItemAdapter(getActivity(),
R.layout.lessons_list_item, parserJson.getLessons(courseUrl).getLessonsArray());
descriptionData = parserJson.getLessons(courseUrl).getDescriptionData();
}
// #Override
// public void onSaveInstanceState(Bundle outState) {
// //No call for super(). Bug on API Level > 11.
// }
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_lessons_list, container, false);
descriptionTextView = (TextView) view.findViewById(R.id.lessons_description);
descriptionTextView.setText("Описание курса:\n" +
descriptionData.getShortDescription());
// Set the adapter
mListView = (AbsListView) view.findViewById(android.R.id.list);
((AdapterView<ListAdapter>) mListView).setAdapter(mAdapter);
// Set OnItemClickListener so we can be notified on item clicks
mListView.setOnItemClickListener(this);
return view;
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mListener = (OnFragmentInteractionListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement OnFragmentInteractionListener");
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
//this occurs when we move out of this Fragment
replaceFragment(CatalogFragment.newInstance(1));
}
private void replaceFragment (Fragment fragment){
String backStateName = fragment.getClass().getName();
String fragmentTag = backStateName;
boolean fragmentPopped = getFragmentManager().popBackStackImmediate (backStateName, 0);
if (!fragmentPopped && getFragmentManager().findFragmentByTag(fragmentTag) == null){ //fragment not in back stack, create it.
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.replace(R.id.container, fragment, fragmentTag);
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
ft.addToBackStack(backStateName);
ft.commit();
}
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if (null != mListener) {
mListener.onLessonFragmentInteraction(parserJson.getLessons(courseUrl).getLessonsArray().get(position).getId());
}
}
/**
* 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
public void onLessonFragmentInteraction(String id);
}
}
Manifest:
<?xml version="1.0" encoding="utf-8"?>
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".AuthorizationActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".NavigationActivity"
android:parentActivityName="com.cbsystematic.mobile.itvdn.AuthorizationActivity" >
<!-- The meta-data element is needed for versions lower than 4.1 -->
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value="com.cbsystematic.mobile.itvdn.AuthorizationActivity" />
>
</activity>
</application>
Fragment's layout:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/fragment_lessons"
android:background="#FAF9F9"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.cbsystematic.mobile.itvdn.LessonsFragment">
<TextView
android:id="#+id/lessons_description"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textColor="#acacac" />
<ListView android:id="#android:id/list"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#id/lessons_description"/>
I know that such problems are like pain in the neck. But please give your assumptions.
Will appreciate any help.
It crashes because the fragment gets recreated everytime you change the orientation.
Add this line to your activity in the manifest:
android:configChanges="keyboardHidden|orientation|screenSize"

Android studio, XML Inflation error on main activity creation android.view.InflateException

Hours have gone by and i still can't get round this really frustrating error.
i'm new to android programming so i'm pretty much following tutorials and trying to understand them as i move along. i've also tryed different approaches but keep getting the same error.
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.testapp.scott.mpt/com.testapp.scott.mpt.MyActivity}: android.view.InflateException: Binary XML file line #34: Error inflating class fragment
Here's my Fragment Layout (I'm using a shape as a background button. that's not the problem because i've tryed removing it and nothing changed...)
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:orientation="horizontal"
android:layout_height="match_parent"
tools:context="com.testapp.scott.mpt.MainToolbarFrag"
android:background="#ff434343">
<Button
android:layout_width="96dp"
android:layout_height="fill_parent"
android:text="My desk"
android:id="#+id/BT_Toolbar_MyDesk"
android:background="#drawable/toolbar_buttonbk"
android:textSize="18sp" />
<Button
android:layout_width="96dp"
android:layout_height="fill_parent"
android:text="Exercises"
android:id="#+id/BT_Toolbar_Exercises"
android:background="#drawable/toolbar_buttonbk"
android:layout_gravity="left"
android:textSize="18sp" />
<Button
android:layout_width="96dp"
android:layout_height="fill_parent"
android:text="My\nProfile"
android:id="#+id/BT_Toolbar_MyProfile"
android:background="#drawable/toolbar_buttonbk"
android:layout_gravity="left"
android:textSize="18sp" />
<Button
android:layout_width="96dp"
android:layout_height="fill_parent"
android:text="Extras"
android:id="#+id/BT_Toolbar_Extras"
android:background="#drawable/toolbar_buttonbk"
android:layout_gravity="left"
android:textSize="18sp" />
</LinearLayout>
The activity in which i would want the fragment to be displayed:
<GridLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="horizontal"
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MyActivity"
tools:ignore="MergeRootFrame" >
<Space
android:layout_width="fill_parent"
android:layout_height="20dp"
android:layout_row="0"
android:layout_column="0"
android:id="#+id/Space0" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="#string/main_welcome"
android:id="#+id/TV_Main_Welcome"
android:layout_row="1"
android:layout_column="0"
android:textAlignment="center"
android:singleLine="true"
android:password="false"
android:inputType="none"
android:gravity="center"
android:textStyle="italic"
android:layout_gravity="left|top" />
<fragment
android:layout_width="wrap_content"
android:layout_height="74dp"
class="com.testapp.scott.mpt.MainToolbarFrag"
android:id="#+id/fragment"
android:layout_row="30"
android:layout_column="0"
tools:layout="#layout/fragment_maintoolbar" />
My Fragment Java Class:
package com.testapp.scott.mpt;
import android.app.Activity;
import android.net.Uri;
import android.os.Bundle;
import android.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
/**
* A simple {#link Fragment} subclass.
* Activities that contain this fragment must implement the
* {#link MainToolbarFrag.OnFragmentInteractionListener} interface
* to handle interaction events.
* Use the {#link MainToolbarFrag#newInstance} factory method to
* create an instance of this fragment.
*
*/
public class MainToolbarFrag 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;
/**
* 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 MainToolbarFrag.
*/
// TODO: Rename and change types and number of parameters
public static MainToolbarFrag newInstance(String param1, String param2) {
MainToolbarFrag fragment = new MainToolbarFrag();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
public MainToolbarFrag() {
// Required empty public constructor
}
#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
return inflater.inflate(R.layout.fragment_maintoolbar, container, false);
}
// 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(Activity activity) {
super.onAttach(activity);
try {
mListener = (OnFragmentInteractionListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.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
public void onFragmentInteraction(Uri uri);
}
}
And my main Activity class:
package com.testapp.scott.mpt;
import android.app.Activity;
import android.app.Fragment;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import com.testapp.scott.mpt.MyClasses.Constants;
import com.testapp.scott.mpt.MyClasses.Exercises;
import com.testapp.scott.mpt.MyClasses.UserData;
import com.testapp.scott.mpt.MyClasses.deskData;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;
import java.io.IOException;
import java.io.InputStream;
import java.text.ParseException;
public class MyActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
if (savedInstanceState == null) {
getFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment())
.commit();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.my, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.activity_my, container, false);
return rootView;
}
}
}
And FInally this is my Log:
10-13 20:51:54.974 1678-1678/com.testapp.scott.mpt D/dalvikvm﹕ Late-enabling CheckJNI
10-13 20:51:54.994 1678-1684/com.testapp.scott.mpt D/dalvikvm﹕ Debugger has detached; object registry had 1 entries
10-13 20:51:55.074 1678-1678/com.testapp.scott.mpt D/AndroidRuntime﹕ Shutting down VM
10-13 20:51:55.074 1678-1678/com.testapp.scott.mpt W/dalvikvm﹕ threadid=1: thread exiting with uncaught exception (group=0x41941d88)
10-13 20:51:55.074 1678-1678/com.testapp.scott.mpt E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.testapp.scott.mpt, PID: 1678
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.testapp.scott.mpt/com.testapp.scott.mpt.MyActivity}: android.view.InflateException: Binary XML file line #34: Error inflating class fragment
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2237)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2286)
at android.app.ActivityThread.access$800(ActivityThread.java:144)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1246)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:212)
at android.app.ActivityThread.main(ActivityThread.java:5135)
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:877)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:693)
at dalvik.system.NativeStart.main(Native Method)
Caused by: android.view.InflateException: Binary XML file line #34: Error inflating class fragment
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:713)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:755)
at android.view.LayoutInflater.inflate(LayoutInflater.java:492)
at android.view.LayoutInflater.inflate(LayoutInflater.java:397)
at android.view.LayoutInflater.inflate(LayoutInflater.java:353)
at com.android.internal.policy.impl.PhoneWindow.setContentView(PhoneWindow.java:297)
at android.app.Activity.setContentView(Activity.java:1929)
at com.testapp.scott.mpt.MyActivity.onCreate(MyActivity.java:32)
at android.app.Activity.performCreate(Activity.java:5231)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2201)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2286)
at android.app.ActivityThread.access$800(ActivityThread.java:144)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1246)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:212)
at android.app.ActivityThread.main(ActivityThread.java:5135)
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:877)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:693)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.ClassCastException: com.testapp.scott.mpt.MyActivity#44aea5d0 must implement OnFragmentInteractionListener
at com.testapp.scott.mpt.MainToolbarFrag.onAttach(MainToolbarFrag.java:84)
at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:853)
at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:1044)
at android.app.FragmentManagerImpl.addFragment(FragmentManager.java:1146)
at android.app.Activity.onCreateView(Activity.java:4786)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:689)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:755)
at android.view.LayoutInflater.inflate(LayoutInflater.java:492)
at android.view.LayoutInflater.inflate(LayoutInflater.java:397)
at android.view.LayoutInflater.inflate(LayoutInflater.java:353)
at com.android.internal.policy.impl.PhoneWindow.setContentView(PhoneWindow.java:297)
at android.app.Activity.setContentView(Activity.java:1929)
at com.testapp.scott.mpt.MyActivity.onCreate(MyActivity.java:32)
at android.app.Activity.performCreate(Activity.java:5231)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2201)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2286)
at android.app.ActivityThread.access$800(ActivityThread.java:144)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1246)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:212)
at android.app.ActivityThread.main(ActivityThread.java:5135)
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:877)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:693)
at dalvik.system.NativeStart.main(Native Method)
I've already fixed the missing implementation in my activity class.
The real problem here is the inflation error.
Thanks!
your problem is from these lines of code:
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mListener = (OnFragmentInteractionListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement OnFragmentInteractionListener");
}
}
your activity must implement OnFragmentInteractionListener, but you do not implement that in your MyActivity.
There really is no point in answering questions if the answer doesn't reply to the question asked (Please note the last two lines of my question)...
That being said, i figured out how to solve the problem and for anyone having the same issue the problem resided in the fact that MyActivity was not pointing to the fragment in it's onCreate() Method.
i solved it by changing
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
if (savedInstanceState == null) {
getFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment())
.commit();
}
}
in particular the line:
.add(R.id.container, new PlaceholderFragment())
to:
.add(R.id.container, new MainToolbarFrag())
where MainToolbarFrag() is the class of your fragment.

android.view.InflateException: Binary XML file line #9: Error inflating class fragment

There are a lot of articles pointing to the same error but none appeared to fix my problem. So I am posting it
I have a fragment layout below
<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=".MyAppointmentFragment" >
<!-- TODO: Update blank fragment layout -->
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="#string/fragment_text" />
</FrameLayout>
And the activity layout below
<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:orientation="horizontal"
android:baselineAligned="false"
tools:context=".IndexActivity"
>
<fragment
android:name="com.example.helloworld.MyAppointmentFragment"
android:id="#+id/myappointment_fragment"
android:layout_weight="1"
android:layout_width="0dp"
android:layout_height="match_parent" />
</LinearLayout>
Below is the java source for the activity that is throwing this error
package com.example.helloworld;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.view.Menu;
public class IndexActivity extends FragmentActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_index);
}
}
package com.example.helloworld;
import android.app.Activity;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
/**
* A simple {#link android.support.v4.app.Fragment} subclass. Activities that
* contain this fragment must implement the
* {#link MyAppointmentFragment.OnFragmentInteractionListener} interface to
* handle interaction events. Use the {#link MyAppointmentFragment#newInstance}
* factory method to create an instance of this fragment.
*
*/
public class MyAppointmentFragment 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;
/**
* 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 MyAppointmentFragment.
*/
// TODO: Rename and change types and number of parameters
public static MyAppointmentFragment newInstance(String param1, String param2) {
MyAppointmentFragment fragment = new MyAppointmentFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
public MyAppointmentFragment() {
// Required empty public constructor
}
#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
return inflater.inflate(R.layout.fragment_my_appointment, container,
false);
}
// 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(Activity activity) {
super.onAttach(activity);
try {
mListener = (OnFragmentInteractionListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.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
public void onFragmentInteraction(Uri uri);
}
}
When launched in an emulator I get the following error
02-20 13:21:42.530: E/AndroidRuntime(1290): FATAL EXCEPTION: main
02-20 13:21:42.530: E/AndroidRuntime(1290): java.lang.RuntimeException: Unable to start
activity
ComponentInfo{com.example.helloworld/com.example.helloworld.IndexActivity}:
android.view.InflateException: Binary XML file line #9: Error inflating class fragment
02-20 13:21:42.530: E/AndroidRuntime(1290): at
android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2211)
The Android version I am using is 4.3 and minSdkVersion="13" and targetSdkVersion="18"
I would appreciate any help to resolve this issue
Complete Stack Trace Below
FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.helloworld/com.example.helloworld.IndexActivity}: android.view.InflateException: Binary XML file line #9: Error inflating class fragment
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2211)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2261)
at android.app.ActivityThread.access$600(ActivityThread.java:141)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1256)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5103)
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:737)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
at dalvik.system.NativeStart.main(Native Method)
Caused by: android.view.InflateException: Binary XML file line #9: Error inflating class fragment
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:713)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:755)
at android.view.LayoutInflater.inflate(LayoutInflater.java:492)
at android.view.LayoutInflater.inflate(LayoutInflater.java:397)
at android.view.LayoutInflater.inflate(LayoutInflater.java:353)
at com.android.internal.policy.impl.PhoneWindow.setContentView(PhoneWindow.java:267)
at android.app.Activity.setContentView(Activity.java:1895)
at com.example.helloworld.IndexActivity.onCreate(IndexActivity.java:11)
at android.app.Activity.performCreate(Activity.java:5133)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2175)
... 11 more
Caused by: java.lang.ClassCastException: com.example.helloworld.IndexActivity#4174c9f8 must implement OnFragmentInteractionListener
at com.example.helloworld.MyAppointmentFragment.onAttach(MyAppointmentFragment.java:85)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:883)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1082)
at android.support.v4.app.FragmentManagerImpl.addFragment(FragmentManager.java:1184)
at android.support.v4.app.FragmentActivity.onCreateView(FragmentActivity.java:285)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:685)
... 21 more
java.lang.ClassCastException: com.example.helloworld.IndexActivity#4174c9f8 must implement OnFragmentInteractionListener
Your IndexActivity class is supposed to implement some OnFragmentInteractionListener interface, and it does not.
My answer is quite late cause I also faced the same problem and no solution was working for me. If none of the other areas like onFragmentInteractionListener() have problem then check for
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mListener = (OnFragmentInteractionListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement OnFragmentInteractionListener");
}
}
as this method is deprecated replace it with
public void onAttach(Context context) {
super.onAttach(context);
try {
mListener = (OnFragmentInteractionListener) context;
} catch (ClassCastException e) {
throw new ClassCastException(context.toString()
+ " must implement OnFragmentInteractionListener");
}
}
Make sure you have a string named fragment_text
android:text="#string/fragment_text"
in your strings.xml file in the values folder. Even if you have, try doing a project 'clean' as well.

Categories

Resources