Can't get PreferenceFragmentCompat to work - android

I am trying to create an Activity that extends AppCompatActivity and has two fragments inside of it (one below another - just by using a LinearLayout). I would like the first fragment to extend the PreferenceFragmentCompat class from the support-v7 library.
I followed Google's short example regarding PreferenceFragmentCompat as shown at https://developer.android.com/reference/android/support/v7/preference/PreferenceFragmentCompat.html.
Here is my current code:
GroupDetailsActivity.java
public class GroupDetailsActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_group_details);
GroupDetailsPrefFragment prefFragment = GroupDetailsPrefFragment.newInstance();
GroupDetailsMembersFragment membersFragment = GroupDetailsMembersFragment.newInstance();
FragmentManager fm = getSupportFragmentManager();
fm.beginTransaction()
.add(R.id.flPrefFragment, prefFragment, GroupDetailsPrefFragment.TAG)
.add(R.id.flMembersFragment, membersFragment, GroupDetailsMembersFragment.TAG)
.commit();
}
}
GroupDetailsPrefFragment .java - The problematic fragment
public class GroupDetailsPrefFragment extends PreferenceFragmentCompat {
public static final String TAG = "GroupDetailsPrefFragment";
#Override
public void onCreatePreferences(Bundle bundle, String s) {
setPreferencesFromResource(R.xml.group_details_preferences, s);
}
public static GroupDetailsPrefFragment newInstance() {
GroupDetailsPrefFragment fragment = new GroupDetailsPrefFragment();
return fragment;
}
}
GroupDetailsMembersFragment.java - Completely empty for now..
public class GroupDetailsMembersFragment extends Fragment {
public static final String TAG = "GroupDetailsMembersFragment";
public static GroupDetailsMembersFragment newInstance() {
GroupDetailsMembersFragment fragment = new GroupDetailsMembersFragment();
return fragment;
}
}
activity_group_details.xml - Activity's layout
<?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">
<FrameLayout
android:id="#+id/flPrefFragment"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
<FrameLayout
android:id="#+id/flMembersFragment"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</LinearLayout>
group_details_preferences.xml - The preference XML file
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
<Preference
android:title="#string/remove_me"
android:key="#string/pref_key_settings_remove_me"/>
<Preference
android:title="#string/delete_group"
android:key="#string/pref_key_settings_delete_group"/>
</PreferenceScreen>
Trying to compile and run the code above lead me into a few errors, the first one was regarding a preference theme that was not set. I have quickly scanned the internet and found you need to add the following line into your Activity's theme : <item name="preferenceTheme">#style/PreferenceThemeOverlay.v14.Material</item>
To do so, I was needed to add the support-v14 library to gradle!
Trying to run the code again, lead me to another error, which is the reason I am posting this, and so far I didn't find any way to solve this issue. Here is the crash log :
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.cochat.android/com.cochat.android.ui.groups.details.GroupDetailsActivity}: java.lang.RuntimeException: Content has view with id attribute 'android.R.id.list_container' that is not a ViewGroup class
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2305)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2363)
at android.app.ActivityThread.access$900(ActivityThread.java:161)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1265)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:157)
at android.app.ActivityThread.main(ActivityThread.java:5356)
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:1265)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1081)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.RuntimeException: Content has view with id attribute 'android.R.id.list_container' that is not a ViewGroup class
at android.support.v7.preference.PreferenceFragmentCompat.onCreateView(PreferenceFragmentCompat.java:269)
at android.support.v4.app.Fragment.performCreateView(Fragment.java:2184)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1298)
at android.support.v4.app.FragmentManagerImpl.moveFragmentsToInvisible(FragmentManager.java:2323)
at android.support.v4.app.FragmentManagerImpl.executeOpsTogether(FragmentManager.java:2136)
at android.support.v4.app.FragmentManagerImpl.optimizeAndExecuteOps(FragmentManager.java:2092)
at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1998)
at android.support.v4.app.FragmentController.execPendingActions(FragmentController.java:388)
at android.support.v4.app.FragmentActivity.onStart(FragmentActivity.java:607)
at android.support.v7.app.AppCompatActivity.onStart(AppCompatActivity.java:181)
at android.app.Instrumentation.callActivityOnStart(Instrumentation.java:1189)
at android.app.Activity.performStart(Activity.java:5441)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2278)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2363) 
at android.app.ActivityThread.access$900(ActivityThread.java:161) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1265) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:157) 
at android.app.ActivityThread.main(ActivityThread.java:5356) 
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:1265) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1081) 
at dalvik.system.NativeStart.main(Native Method) 
Been stuck on this for a while now, tried looking up different posts on stackoverflow or other websites, seen some solutions, but for some reason none of them managed to solve my problem.
Edit:
My gradle file contains the following:
compileSdkVersion 25
buildToolsVersion '25.0.2'
...
compile 'com.android.support:preference-v7:25.1.0'
compile 'com.android.support:preference-v14:25.1.0'
Update Jan 02 '17
I've been looking into the source code of PreferenceFragmentCompat and seen it is trying to load the following layout: R.layout.preference_list_fragment.
In the onCreateView() method of the class, it is inflating the layout, and trying to look for the id android.R.id.list_container.
The problem is that there is no such id within the layout.
Here is a code snippet from the PreferenceFragmentCompat:
final View view = themedInflater.inflate(mLayoutResId, container, false);
final View rawListContainer = view.findViewById(AndroidResources.ANDROID_R_LIST_CONTAINER);
if (!(rawListContainer instanceof ViewGroup)) {
throw new RuntimeException("Content has view with id attribute "
+ "'android.R.id.list_container' that is not a ViewGroup class");
}
While
private int mLayoutResId = R.layout.preference_list_fragment;
Still looking for a solution, thanks!

I got past this using the following bugfix:
https://github.com/Gericop/Android-Support-Preference-V7-Fix
Simple 3 step process is to update the app's build.gradle,
Remove:
compile 'com.android.support:preference-v7:25.0.1'
compile 'com.android.support:preference-v14:25.0.1'
Add
compile 'com.takisoft.fix:preference-v7:25.0.1.0'
Then update your app's theme for preferences to use PreferenceFixTheme
(You're already using PreferenceFragmentCompat so good to go).
UPDATE:
On further investigation, with api 25.1.0, AppCompat worked fine once I realized the very strict restrictions on the style for Preferences.
I found this resource very helpful in getting everything set up nicely:

According to this article:
Note that Google changed the needed id from R.id.list_container (in
revision 23.4.0) to android.R.id.list_container (in revision 24.0.0).
Android Studio says the new id requires API 24, but it also works on
older APIs.
ViewGroup in your layout file (activity_group_details.xml) should have id "#android:id/list_container”. to make it work. It can look like this:
<FrameLayout
android:id="#android:id/list_container"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
<FrameLayout
android:id="#+id/flMembersFragment"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
And you have to use this id for your transaction too, note that the other fragment of yours can use any Id for container, only pref is 'special'

So I have found a work around for this, might not be the best, but it is the only thing I have managed to get working! It seems like a problem/bug with the support library..
I have copied the original PreferenceFragmentCompat to a local class, and made minor changed to it. I have replace the following line
private int mLayoutResId = android.support.v7.preference.R.layout.preference_list_fragment;
with
private int mLayoutResId = R.layout.preference_fragment_compat_container;
which is a layout I have made, that it very simple and only contains a container for the list. Here is the layout code:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#android:id/list_container"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
Doing the above will allow you to use PreferenceFragmentCompat with the specific gradle settings above (see original post) without any problems.
The down side is that upgrading the support libraries will not upgrade your PreferenceFragmentCompat since it is copied of course. You will need to keep track of the support libraries, and when ever the problem is fixed, you may delete the copied class and use the original one.
If you have any other solutions or ideas please share!

I think you just need to use the support PreferenceScreen and Preferences:
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.preference.PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
<android.support.v7.preference.Preference
android:title="#string/remove_me"
android:key="#string/pref_key_settings_remove_me"/>
<android.support.v7.preference.Preference
android:title="#string/delete_group"
android:key="#string/pref_key_settings_delete_group"/>
</android.support.v7.preference.PreferenceScreen>

Checked out my answer here https://stackoverflow.com/a/53560798/1247248
you need a layout resource with that id

Adding this line to your AppTheme in the styles.xml file should do the trick:
<item name="preferenceTheme">#style/PreferenceThemeOverlay</item>

Related

How to create an app setting in an xamarin android app that shows in the Android Settings/Apps/App Setting for that app?

I have been over the documentation here:
https://developer.android.com/guide/topics/ui/settings
The above page talks about creating a settings UI in your app, and shows using an XML file (that it doesn't tell you where to put by the way).
I do not want to add a settings UI in my app. I just want a setting to appear in android settings app under Apps when you pick my app from that list, it already has a section called "App settings". I want to add a setting for my app here, and be able to read it from my app. (Would be a bonus to be able to write to it from my app as well.)
Is this possible to do this and if so, can someone point me to an example.
Thanks for your time.
If you want to achieve that, you should add following nuget package firstly.
Xamarin.Android.Support.v7.Preference
Then create xml folder, Add the preferences.xml.
Here is code add preferences.xml for testing.
<PreferenceScreen
xmlns:app="http://schemas.android.com/apk/res-auto">
<SwitchPreferenceCompat
app:key="notifications"
app:title="Enable message notifications"/>
<Preference
app:key="feedback"
app:title="Send feedback"
app:summary="Report technical issues or suggest new features"/>
</PreferenceScreen>
Then create a class called MySettingsFragment.cs, PreferenceFragmentCompat comes from Android.Support.V7.Preferences, populator the preferences.xml by SetPreferencesFromResource method.
using Android.OS;
using Android.Runtime;
using Android.Support.V7.Preferences;
using Android.Views;
using Android.Widget;
namespace App32
{
public class MySettingsFragment : PreferenceFragmentCompat
{
public override void OnCreatePreferences(Bundle savedInstanceState, string rootKey)
{
SetPreferencesFromResource(Resource.Xml.preferences, rootKey);
}
}
}
In the end, we can add a FrameLayout in your layout.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/settings_container"/>
</RelativeLayout>
In the activity to use MySettingsFragment like Fragment's transaction.
public class MainActivity : AppCompatActivity
{
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
Xamarin.Essentials.Platform.Init(this, savedInstanceState);
// Set our view from the "main" layout resource
SetContentView(Resource.Layout.activity_main);
SupportFragmentManager.BeginTransaction().Replace(Resource.Id.settings_container,new MySettingsFragment()).Commit();
}
}
}
Here is running sceenshot.
I ended up going with Xamarin.Essentials: Preferences as this was the closest I could find to what I wanted and I didn't have to have a settings UI in the app.
https://learn.microsoft.com/en-us/xamarin/essentials/preferences?context=xamarin%2Fandroid&tabs=android

Could not find a method onClick_Foo(View) - first time running on Android Lollipop

I have an app that is about a year old, is on the Play store in beta, has gone through dozens of revisions. All of a sudden I'm getting an error:
Could not find a method onClick_Foo(View) in the activity class
android.view.ContextThemeWrapper for onClick handler on view class
android.widget.Button with id 'Foo_Button'
I'm getting this error on every one of the 7 buttons defined in my XML. Since yesterday I've updating appcompat-v7 from 21.0.3 to 22.0.0 but also upgraded my testing device from KitKat to Lollipop for the first time.
I've double-checked spellings, capitalizations, none of the usual suspects explains this. Here's a sample of the relevant code. Let me know if you feel more would be helpful. (The activity has 915 lines of code and the xml 186, so don't ask for the whole thing). Testing on a Verizon Note 4 running Lollipop 5.0.1
activity_pick.xml:
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:theme="#style/AppTheme"
tools:context="com.myapp.Pick"
android:layout_height="match_parent"
android:layout_width="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
android:orientation="vertical">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/Ratings_Button"
android:textSize="16dp"
android:text="#string/Pick_Ratings_Button"
android:onClick="onClick_Ratings"
android:background="#android:drawable/btn_default"/>
</LinearLayout>
</ScrollView>
Pick.java:
public class Pick_Restaurant extends ActionBarActivity {
public void onClick_Ratings (View v) {
Intent intent = new Intent(mContext, Ratings.class);
startActivityForResult(intent,RATINGS);
}
}
build.gradle:
apply plugin: 'com.android.application'
android {
compileSdkVersion 22
buildToolsVersion "22.0.1"
defaultConfig {
minSdkVersion 15
targetSdkVersion 22
versionCode 59
versionName "0.6.4"
}
...
dependencies {
compile fileTree(include: ['*.jar'], dir: 'libs')
compile 'com.android.support:appcompat-v7:22.0.0'
compile 'com.google.android.gms:play-services:7.0.0'
compile files('libs/mobileservices-1.1.5.jar')
}
Full Error on Log:
04-08 17:06:40.578 3508-3508/com.myapp.debug E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.myapp.debug, PID: 3508
java.lang.IllegalStateException: Could not find a method onClick_Ratings(View) in the activity class android.view.ContextThemeWrapper for onClick handler on view class android.widget.Button with id 'Ratings_Button'
at android.view.View$1.onClick(View.java:4234)
at android.view.View.performClick(View.java:5191)
at android.view.View$PerformClick.run(View.java:20916)
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:5974)
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:1388)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1183)
Caused by: java.lang.NoSuchMethodException: onClick_Ratings [class android.view.View]
at java.lang.Class.getMethod(Class.java:665)
at android.view.View$1.onClick(View.java:4227)
            at android.view.View.performClick(View.java:5191)
            at android.view.View$PerformClick.run(View.java:20916)
            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:5974)
            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:1388)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1183)
It looks like this is a new issue with Android 5.0.
From this anwer, removing the Theme from the layout xml fixed this issue for them.
So in your case, remove the theme from your layout:
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools">
<!--android:theme="#style/AppTheme"--> <!-- Remove this -->
<!--................-->
</ScrollView>
And add the theme in the AndroidManifest.xml instead:
android:theme="#android:style/AppTheme"
I have just answered a similar question here
Basically, since Android 5.0 individual views can be themed.
To facilitate this, a ContextThemeWrapper is used to modify the underlying theme assigned to the Activity and assigned as the Context of the View. Since this Context is not your Activity anymore (the Activity has to be separate because it still has to return the original theme) the callbacks don't exist and you get the error you see.
If you don't really want to theme individual views the obvious solution is to not do so and theme the activity instead, as already suggested.
If you do indeed want to theme individual views, it appears that the android:onClick attribute cannot be used and you will have to fall back to manually assign an OnClickListener.
The question is, why did this work pre Lollipop? I can only speculate that because the functionality to theme individual views didn't exist, applying a theme attribute to a view would just change the default theme on the Activity as well.
Such things usually happens when you declare onClick in xml like you did:
android:onClick="onClick_Ratings"
Just make sure you are using this layout in that activity. Because the exception is clearly saying that your activity don't have the corresponding method which you did show you have:
public void onClick_Ratings (View v) {
Intent intent = new Intent(mContext, Ratings.class);
startActivityForResult(intent,RATINGS);
}
Also I guess you should declare the activity in your xml like:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".SendMessageActivity">
And actually log says:
Could not find a method onClick_Ratings(View) in the activity class
android.view.ContextThemeWrapper
there is something wrong since android.view.ContextThemeWrapper is not an Activity and not the activity from your xml com.myapp.Pick (I assume Pick is an activity and not the fragment). Maybe try to clean up the project, ivalidate caches and restart.
If nothing helps I suggest you to return back to previuos version of support lib you'd mentioned OR to set onClickListener in code instead of xml.
Removing android:theme works. But this is caused because using android:onclick in xml. If you use onClick in Java file, you can still use android:theme.
According to your code,
activity_pick.xml [Remove onclick here]
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/Ratings_Button"
android:textSize="16dp"
android:text="#string/Pick_Ratings_Button"
android:background="#android:drawable/btn_default" />
Go to your Java File, that is, pick.java in your case:
final Button button = (Button) findViewById(R.id.Ratings_Button);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent activityChangeIntent = new Intent(CurrentActivity.this, SecondActivity.class);
SplashScreen.this.startActivity(activityChangeIntent);
}
});
Experienced the same error, app has stopped working, when material button was clicked programmatically helped me. Check it out :)

Google Android tutorial - not compiling

I did everything just as stated in this tutorial:
google android basic tutorial
and despite everything being done just as described, the code refuses to compile with 3 errors. Looks like the guys writing the turorial forgot to mention what are those things and where/how do I define them.
The errors I get:
Error:(24, 68) error: cannot find symbol variable container
Error:(36, 23) error: cannot find symbol variable action_settings
Error:(46, 54) error: cannot find symbol variable fragment_display_message
Neither of the 3 fields are defined anywhere (Perhaps one of the libraries is wrong?)
The file in question is:
package com.example.asteroth.first;
import android.app.Activity;
import android.app.Fragment;
import android.content.Intent;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.*;
import android.widget.TextView;
import android.R;
public class DisplayMessageActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent intent = getIntent();
String message = intent.getStringExtra(MainActivity.EXTRA_MESSAGE);
TextView textView = new TextView(this);
textView.setTextSize(40);
textView.setText(message);
setContentView(textView);
// setContentView(R.layout.activity_display_message);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction().add(R.id.container, new PlaceholderFragment()).commit();
}
}
#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
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() { }
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_display_message, container, false);
return rootView;
}
}
}
I am using Android Studio I just downloaded and no question from search or Similar Questions points at the problem like this one, hence I suspect authors of tutorial forgot to mention something minor. I've seen suggestion to place the "container" as a new ID in one of the XML files, but to no avail.
EDIT:
'cannot find symbol ActionBarActivity' following Android Development Tutorial?
This post suggest a solution, however it changes ActionBarActivity to just Activity which is very different from what the tutorial uses and I don't know how serious repercussions would it cause
EDIT2:
Problems found and removed:
import android.R //causes action_settings error
container missing //had to add it in the xml file as an id
xml file named wrong //If I got that correctly, I'm still waiting for someone experienced to clarify, but seems like the tutorial used different name for the xml file then the one that the java code references
Remaining problem is similar to this one
Cannot resolve method placeholderfragment error
however, I both extend Fragment and include android.app.Fragment as can be seen in the included file.
I tried the same tutorial and here is how I fixed my errors:
R.id.container cannot be resolved error
I had to import android.support.v4.app.Fragment to fix this problem and add android:id = "#+id/container" to the RelativeLayout section in my activity_display_message.xml file.
fragment_display_message cannot be resolved error
Change R.layout.fragment_display_message to R.layout.activity_display_message instead. There is no need for creating a new xml file for fragment_display_message.
This should fix these two errors.
But you would probably be better off if you comment out the if(savedInstanceState............ statement as otherwise your program would crash once you try to run it if it doesn't give you any errors.
Your onCreate method should look like this:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView(R.layout.activity_display_message);
Intent intent=getIntent();
String message=intent.getStringExtra(MainActivity.EXTRA_MESSAGE);
TextView textView=new TextView(this);
textView.setTextSize(40);
textView.setText(message);
setContentView(textView);
/*if (savedInstanceState==null){
getSupportFragmentManager().beginTransaction().add(R.id.container, new PlaceholderFragment()).commit();
}*/
}
I'm doing the tutorial for the first time now on Feb. 23, 2015 and ran into this compilation error though I feel like I've closely followed the steps. I changed fragment_display_message to activity_display_message which is an XML file they have us create in the tutorial. This seems to solve the error, and allow the app to run.
// 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_display_message,
container, false);
return rootView;
}
}
Add this line to take care of your first error: android:id = "#+id/container"
You get that error because container isn't in the XML.
Add <string name="action_settings">Action Settings</string>so that the "Action settings" which I'm assuming doesn't exist in your XML code since you have that error.
Create your own XML file with this exact name fragment_display_message.xmlto handle that error and check what code you might need to insert into it in your google tutorial. Often times with Eclipse, these files are not included for reasons outside my knowledge. So you have to create them or insert them yourself. (Make sure you have the latest version of the SDK by the way.
EDIT: Be sure to have the correct imports matching with your "tutorial". I took a gander at it and see you missing two imports. One of which another user answered.
It's a copy paste error.
If you paste code with "R." in it, the development environment always imports the android.R:
import android.R;
If you use R.id.... it is always looking up the android.R and not your own generated R class.
Delete the import and it should be fine. This general works for me.
After that you have to check if you already defined the id's and layout.
You can check Layouts by looking on the package explorer under res->layout. In your example there has to be an fragment_display_message.xml in it.
For id's you have to look up all of your layouts and check if there are the specific views like the container.
I got a similar error on the Building a Simple User Interface step:
Error:(18, 54) error: cannot find symbol variable toolbar
I've narrowed the cause down to res/layout/activity_my.xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<EditText android:id="#+id/edit_message"
android:layout_weight="1"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:hint="#string/edit_message" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/button_send" />
The original version that did compile (but no button or text box) is:
<?xml version="1.0" encoding="utf-8"?>
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" android:fitsSystemWindows="true"
tools:context=".MyActivity">
<android.support.design.widget.AppBarLayout android:layout_height="wrap_content"
android:layout_width="match_parent" android:theme="#style/AppTheme.AppBarOverlay">
<android.support.v7.widget.Toolbar android:id="#+id/toolbar"
android:layout_width="match_parent" android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary" app:popupTheme="#style/AppTheme.PopupOverlay" />
</android.support.design.widget.AppBarLayout>
<include layout="#layout/content_my" />
<android.support.design.widget.FloatingActionButton android:id="#+id/fab"
android:layout_width="wrap_content" android:layout_height="wrap_content"
android:layout_gravity="bottom|end" android:layout_margin="#dimen/fab_margin"
android:src="#android:drawable/ic_dialog_email" />
fragment_display_message
Make sure you have a file named fragment_display_message.xml in your res/layout folder.
action_settings
Make sure you have that item in your menu.xml file in res/menu
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
tools:context=
".MenuExampleActivity" >
<item
android:id="#+id/action_settings"
android:orderInCategory="1"
app:showAsAction="never"
android:title="My menu option"/>
</menu>
container
Make sure you have a layout (ex. RelativeLayout) with the id set to "container" in your activity_main.xml file in res/layout, given that it's the reference for the code to insert the fragment there.

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

I have a very frustrating error that I cannot explain. I created an Android application that uses Android AppCompat to make it compatible with older versions. Here is my main activity layout file:
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<!-- As the main content view, the view below consumes the entire
space available using match_parent in both dimensions. -->
<FrameLayout
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<!-- android:layout_gravity="start" tells DrawerLayout to treat
this as a sliding drawer on the left side for left-to-right
languages and on the right side for right-to-left languages.
If you're not building against API 17 or higher, use
android:layout_gravity="left" instead. -->
<!-- The drawer is given a fixed width in dp and extends the full height of
the container. -->
<fragment android:id="#+id/navigation_drawer"
android:layout_width="#dimen/navigation_drawer_width"
android:layout_height="match_parent"
android:layout_gravity="start"
android:name="com.fragment.NavigationDrawerFragment" />
</android.support.v4.widget.DrawerLayout>
And here is main code of my activity :
public class MainActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
The main problem here is : above code run smoothly on almost devices (stimulated device, or some real devices). But when I run it on Samsung S3. It notices this error:
java.lang.RuntimeException: Unable to start activity ComponentInfo{view.MainActivity}: android.view.InflateException: Binary XML file line #25: Error inflating class fragment
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2081)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2106)
at android.app.ActivityThread.access$700(ActivityThread.java:134)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1217)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4856)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1007)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:774)
at dalvik.system.NativeStart.main(Native Method)
Caused by: android.view.InflateException: Binary XML file line #25: Error inflating class fragment
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:704)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:746)
at android.view.LayoutInflater.inflate(LayoutInflater.java:489)
at android.view.LayoutInflater.inflate(LayoutInflater.java:396)
at android.view.LayoutInflater.inflate(LayoutInflater.java:352)
at com.android.internal.policy.impl.PhoneWindow.setContentView(PhoneWindow.java:316)
at android.app.Activity.setContentView(Activity.java:1901)
at android.support.v7.app.ActionBarActivity.superSetContentView(ActionBarActivity.java:208)
at android.support.v7.app.ActionBarActivityDelegateICS.setContentView(ActionBarActivityDelegateICS.java:111)
at android.support.v7.app.ActionBarActivity.setContentView(ActionBarActivity.java:76)
Please tell me how to fix error, thanks :)
After long time for debugging, I have fixed this problem. (Although I still cannot explain why). That I change property android:name to class. (although on Android Document, they say those properties are same, but it works !!!)
So, it should change from :
android:name="com.fragment.NavigationDrawerFragment"
to
class = "com.fragment.NavigationDrawerFragment"
So, new layout should be :
<!-- As the main content view, the view below consumes the entire
space available using match_parent in both dimensions. -->
<FrameLayout
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<!-- android:layout_gravity="start" tells DrawerLayout to treat
this as a sliding drawer on the left side for left-to-right
languages and on the right side for right-to-left languages.
If you're not building against API 17 or higher, use
android:layout_gravity="left" instead. -->
<!-- The drawer is given a fixed width in dp and extends the full height of
the container. -->
<fragment android:id="#+id/navigation_drawer"
android:layout_width="#dimen/navigation_drawer_width"
android:layout_height="match_parent"
android:layout_gravity="start"
class = "com.fragment.NavigationDrawerFragment" />
Hope this help :)
TL/DR: An exception occurred during the creation of a fragment referenced from a higher-level layout XML. This exception caused the higher-level layout inflation to fail, but the initial exception was not reported; only the higher-level inflation failure shows up in the stack trace. To find the root cause, you have to catch and log the initial exception.
The initial cause of the error could be a wide variety of things, which is why there are so many different answers here as to what fixed the problem for each person. For some, it had to do with the id, class, or name attributes. For others it was due to a permissions issue or a build setting. For me, those didn't fix the problem; instead there was a drawable resource that existed only in drawable-ldrtl-xhdpi, instead of in an applicable place like drawable.
But those are just details. The big-picture problem is that the error message that shows up in logcat doesn't describe the exception that started it all. When a higher-level layout XML references a fragment, the fragment's onCreateView() is called. When an exception occurs in a fragment's onCreateView() (for example while inflating the fragment's layout XML), it causes the inflation of the higher-level layout XML to fail. This higher-level inflation failure is what gets reported as an exception in the error logs. But the initial exception doesn't seem to travel up the chain well enough to be reported.
Given that situation, the question is how to expose the initial exception, when it doesn't show up in the error log.
The solution is pretty straightforward: Put a try/catch block around the contents of the fragment's onCreateView(), and in the catch clause, log the exception:
public View onCreateView(LayoutInflater inflater, ViewGroup contnr, Bundle savedInstSt) {
try {
mContentView = inflater.inflate(R.layout.device_detail_frag, null);
// ... rest of body of onCreateView() ...
} catch (Exception e) {
Log.e(TAG, "onCreateView", e);
throw e;
}
}
It may not be obvious which fragment class's onCreateView() to do this to, in which case, do it to each fragment class that's used in the layout that caused the problem. For example, in the OP's case, the app's code where the exception occurred was
at android.app.Activity.setContentView(Activity.java:1901)
which is
setContentView(R.layout.activity_main);
So you need to catch exceptions in the onCreateView() of any fragments referenced in layout activity_main.
In my case, the root cause exception turned out to be
Caused by: android.content.res.Resources$NotFoundException: Resource
"com.example.myapp:drawable/details_view" (7f02006f) is not a
Drawable (color or path): TypedValue{t=0x1/d=0x7f02006f a=-1
r=0x7f02006f}
This exception didn't show up in the error log until I caught it in onCreateView() and logged it explicitly. Once it was logged, the problem was easy enough to diagnose and fix (details_view.xml existed only under the ldrtl-xhdpi folder, for some reason). The key was catching the exception that was the root of the problem, and exposing it.
It doesn't hurt to do this as a boilerplate in all your fragments' onCreateView() methods. If there is an uncaught exception in there, it will crash the activity regardless. The only difference is that if you catch and log the exception in onCreateView(), you won't be in the dark as to why it happened.
P.S. I just realized this answer is related to #DaveHubbard's, but uses a different approach for finding the root cause (logging vs. debugger).
I couldn't solve my problem using provided answers. Finally I changed this:
<fragment
android:id="#+id/fragment_food_image_gallery"
android:name="ir.smartrestaurant.ui.fragment.ImageGalleryFragment"
android:layout_width="match_parent"
android:layout_height="200dp"
android:layout="#layout/fragment_image_gallery"
tools:layout="#layout/fragment_image_gallery" />
to this :
<FrameLayout
android:id="#+id/fragment_container"
android:layout_width="match_parent"
android:layout_height="200dp" />
,
private void showGallery() {
ImageGalleryFragment fragment = new ImageGalleryFragment()
getSupportFragmentManager().beginTransaction()
.replace(R.id.fragment_container, fragment)
.commit();
}
and it works.
If you are using it inside fragment, use getChildFragmentManager instead of getSupportFragmentManager.
I had the same problem, issue, tried all the answers in this thread to no avail. My solution was, I hadn't added an ID in the Activity XML. I didn't think it would matter, but it did.
So in the Activity XML I had:
<fragment
android:name="com.covle.hellocarson.SomeFragment"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
But should've had:
<fragment
android:id="#+id/some_fragment"
android:name="com.covle.hellocarson.SomeFragment"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
If someone would be happy to comment on why this is, I'm all ears, to other, I hope this helps.
It might not be needed for you anymore, but if further readers find it helpful. I have exact same android.view.InflateException:...Error inflating class fragment. I had all right libraries included. Solved by adding one more user permission in the AndroidManifest.xml file i.e. <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
Btw I was running Android Studio 0.8.9 on Ubuntu 12.04.
I have the same problem because I did not implement the listener. See the following code with /*Add This!*/.
public class SomeActivity extends AppCompatActivity
implements BlankFragment.OnFragmentInteractionListener /*Add this!*/
{
#Override /*Add This!*/
public void onFragmentInteraction(Uri uri){ /*Add This!*/
} /*Add This!*/
}
FYI, my fragment class is something like the following:
public class SomeFragment extends Fragment {
private OnFragmentInteractionListener mListener;
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mListener = (OnFragmentInteractionListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement OnFragmentInteractionListener");
}
}
public interface OnFragmentInteractionListener {
public void onFragmentInteraction(Uri uri);
}
}
Edit:
I also notice this same error message under another circumstances when there is an exception in the onCreate function of the Fragment. I have something as the following:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
int ID = getArguments().getInt("val");
return rootView;
}
Because I reuse this fragment, I total forget to set arguments. Then the result of getArguments() is null. Obviously, I get a null pointer exception here. I will suggest you keep an eye on mistakes like this as well.
Is your NavigationDrawerFragment extending the android.support.v4.app.Fragment? In other words, are you importing the correct package?
import android.support.v4.app.Fragment;
I also had this issue. I solved it by replacing the import in MainActivity and NavigationDrawerFragment
From
import android.app.Activity;
import android.app.ActionBar;
To
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarActivity;
I updated MainActivity to extends ActionBarActivity instead of Activity
public class MainActivity extends ActionBarActivity implements NavigationDrawerFragment.NavigationDrawerCallbacks
Also use ActionBar actionBar = getSupportActionBar(); to get the ActionBar
And I updated the following function in NavigationDrawerFragment
private ActionBar getActionBar()
{
return ((ActionBarActivity)getActivity()).getSupportActionBar();
}
i faced this problem and solved it by using following codes. I was beginning fragment transaction by using childfragment manager.
layout:
<fragment
class="com.google.android.youtube.player.YouTubePlayerSupportFragment"
android:id="#+id/youtube_fragment"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
this is how i began fragment transaction:
youTubePlayerFragment = (YouTubePlayerSupportFragment) getChildFragmentManager().findFragmentById(R.id.youtube_fragment);
the following codes explains how i removed the fragment which added by using childfragmentmanger.
#Override
public void onDestroyView() {
super.onDestroyView();
youTubePlayerFragment = (YouTubePlayerSupportFragment) getChildFragmentManager().findFragmentById(R.id.youtube_fragment);
if (youTubePlayerFragment != null)
{
getChildFragmentManager().beginTransaction().remove(youTubePlayerFragment).commitAllowingStateLoss();
}
youTubePlayer = null;
}
I have had similar problems on and off. The error message often provides very little detail, regardless of actual cause. But I found a way to get more useful info. It turns out that the internal android class 'LayoutInflater.java' (in android.view package) has an 'inflate' method that re-throws an exception, but does not pick up the details, so you lose info on the cause.
I used AndroidStudio, and set a breakpoint at LayoutInflator line 539 (in the version I'm working in), which is the first line of the catch block for a generic exception in that 'inflate' method:
} catch (Exception e) {
InflateException ex = new InflateException(
parser.getPositionDescription()
+ ": " + e.getMessage());
ex.initCause(e);
throw ex;
If you look at 'e' in the debugger, you will see a 'cause' field. It can be very helpful in giving you a hint about what really occurred. This is how, for example, I found that the parent of an included fragment must have an id, even if not used in your code. Or that a TextView had an issue with a dimension.
Just in case someone needs this.
Assumptions: Device phone hooked up to USB cable and your IDE reading to launch
the app.
Go to the command prompt to determine issue:
enter adb logcat
Then launch your app from IDE.
You will an exception.
In my case: I was deploying an Android app of Version 2.3 to a mobile device
that did not support the widget "Space"
Add this name field in navigation
android:name="androidx.navigation.fragment.NavHostFragment"
<fragment
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="0dp"
android:name="androidx.navigation.fragment.NavHostFragment"
app:navGraph="#navigation/navigation"
app:layout_constraintBottom_toTopOf="#+id/bottomNavigationView"
app:layout_constraintTop_toTopOf="parent">
This problem arises when you have a custom class that extends a different class (in this case a view) and does not import all the constructors required by the class.
For eg : public class CustomTextView extends TextView{}
This class would have 4 constructors and if you miss out on any one it would crash. For the matter of fact I missed out the last one which was used by Lollipop added that constructor and worked fine.
we must also need to add following in build.gradle(app)
compile 'com.android.support:appcompat-v7:23.1.1'
compile 'com.android.support:design:23.1.1'
whenever we are using new layouts or new design features.
hope this helps you.
As mentioned in a previous post,
rename
android:name="com.fragment.NavigationDrawerFragment"
to
class = "com.fragment.NavigationDrawerFragment"
Still, it did not work for me. I then just used the Class Name without the com.fragment part and voila it worked. So change it finally to
class = "NavigationDrawerFragment"
After none of the answers here helped me, I opted to run app in debug mode moving across every line of onCreateView in my fragment (NavigationDrawerFragment in your case). And noticed that fragment was having difficulty with inflating because of a NullPointerException.
E.g.
mySeekBar = (SeekBar) getActivity().findViewById(R.id.mySeekBar);
mySeekBar.setOnSeekBarChangeListener(this);
Here mySeekBar was set to null (because I had missed adding the control in appropriate layout) and the next line got into NPE which came out as InflateException.
Also, as suggested above, rename android:name to class.
This issue can arise for various reasons mentioned above. I would recommend line-by-line debug flow to know what is wrong.
After long time of tries, this is how I solved the problem after none of the above answers could.
Extend AppCompatActivity for your Main activity instead of Activity.
Add android:theme="#style/Theme.AppCompat.Light" to your <Activity..../> in the AndroidManifest.xml
In your NavigationDrawerFragment Class, change your ActionBar instances to
ActionBar mActionBar=((AppCompatActivity)getActivity()).getSupportActionBar();
EDIT
It should be a consistency between the Activity and Layout.
If the Layout has one of the AppCompat Theme such like Theme.AppCompat.Light, your Activity should extends AppCompatActivity.
I wanted to have the burger icon and a Navigation Drawer that looks like the Android Gmail App, but I ended up with an ugly Navigation Drawer.
All that because all my Classes extends Activity instead of AppCompatActivity.
I re-factored the entire project to extend AppCompatActivity, then Right-Click on the Layout Folder, chose new -> Activity then Navigation Drawer Activity and Boom, everything is done for me!
android.view.InflateException: Binary XML file line #16: Error inflating class com.google.android.material.bottomappbar.BottomAppBar
The view can be anything that is failing to get inflated, this kind of error comes when there is a clash in resolving the class names or name attribute of a view referred in the XML file.
When I get the same error I just got everything clean and safe in UI-XML file,
the view I was using,
<com.google.android.material.bottomappbar.BottomAppBar
android:id="#+id/bottomAppBar"
style="#style/Widget.MaterialComponents.BottomAppBar.Colored"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="bottom"
app:hideOnScroll="true"
app:menu="#menu/bottom_app_bar"
app:navigationIcon="#drawable/ic__menu_24"/>
I was using a style attribute which was referring the Material components property.
But my styles.xml had...
<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
....
</style>
Where the class resolving was facing the conflict. My view attributes referred a property that was not defined in my app theme. The right parent theme from material components helped me.
So I changed the parent attribute to...
<style name="AppTheme" parent="Theme.MaterialComponents.Light.NoActionBar">
...
</style>
Which resolved the issue.
For some of you that still haven't found a solution for this, in my case it was happening because I had an OOM (Out of Memory) issue. This can happen when you have for example a memory leak in your app when using it for a long time. In my stack trace, this was the main reason.
I don't know if this will help.
I had this problem with a TextView I had in the layout I was trying to inflate (android.view.InflateException: Binary XML file line #45: Error inflating class TextView).
I had set the following XML attribute android:textSize="?android:attr/textAppearanceLarge" which wasn't allowing for the layout to be inflated.
Don't know exactly why, (I'm still a bit new to Android - less than a year of experience), might have something to do with calling system attributes, idk, all I know is as soon as I used plain old #dimen/md_text_16sp (which is a custom of mine), problem solved :)
Hope this helps...
I had this on a 4.4.2 device, but 5+ was fine. The cause: inside a custom view's initialisation, I was creating a TextView(Context context, AttributeSet attrs, #AttrRes int defStyleAttr, #StyleRes int defStyleRes), which is API 21+.
Android Studio 2.1 doesn't complain about it even though it is annotated TargetApi(21). Apparently, Android Studio 2.2 will correct this and properly show it as an error.
Hope this helps someone.
I am a bit late to the party but Non of these answer helped me in my case. I was using Google map as SupportMapFragment and PlaceAutocompleteFragment both in my fragment. As all the answers pointed to the fact that the problem is with SupportMapFragment being the map to be recreated and redrawn.
But I also had problem with PlaceAutocompleteFragment. So here is the working solution for those who are facing this problem because of SupportMapFragment and SupportMapFragment
mapFragment = (SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.mapFragment);
FragmentManager fm = getChildFragmentManager();
if (mapFragment == null) {
mapFragment = SupportMapFragment.newInstance();
fm.beginTransaction().replace(R.id.mapFragment, mapFragment).commit();
fm.executePendingTransactions();
}
mapFragment.getMapAsync(this);
//Global PlaceAutocompleteFragment autocompleteFragment;
if (autocompleteFragment == null) {
autocompleteFragment = (PlaceAutocompleteFragment) getActivity().getFragmentManager().findFragmentById(R.id.place_autoCompleteFragment);
}
And in onDestroyView clear the SupportMapFragment and SupportMapFragment
#Override
public void onDestroyView() {
super.onDestroyView();
if (getActivity() != null) {
Log.e("res","place dlted");
android.app.FragmentManager fragmentManager = getActivity().getFragmentManager();
android.app.FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.remove(autocompleteFragment);
fragmentTransaction.commit();
autocompleteFragment = null;
}
}
In my particular case the problem was I added this line to a TextView :
android:background="?attr/selectableItemBackground"
After removing this, everything started to work fine.
I don`t know what happened, but Changing Fragment to FrameLayout solved my problem after many hours of struggle.
<FrameLayout
android:id="#+id/fragment_container"
android:layout_width="match_parent"
android:layout_height="match_parent" />
I think the basic problem is with "android:targetSdkVersion" which is defined in AndroidManifest.xml. In my case, the initial value which I have defined as:
android:targetSdkVersion=16
I changed it to:
android:targetSdkVersion=22
which resolved my all of the error. So, setting up the correct "targetSdkVersion" is also important before building an android app.
In case someone else comes here and the answers do not help solve the problem, one more thing to try.
As others have mentioned, this usually is caused by an issue nested in the XML itself as opposed to something you did wrong in your Java. In my case, it was a super easy (and stupid) mistake to fix.
I had code like this:
<view
android:layout_width="fill_parent"
android:layout_height="1dip"
android:id="#+id/view44"
android:background="#color/gray"
/>
When all I had to do was capitalize the v in 'View' so that the system recogized it. Check that your custom views (Or Fragments, recyclerviews, etc) all have the proper capitalized declaration up front so that the XML auto-complete will match it to the appropriate view.
I had this error too, and after very long debugging the problem seamed to be that my MainClass extended Activity instead of FrameActivity, in my case, the xml wasn't a problem. Hope to help you.
In my case .
The layout i was trying to inflate had
<include
layout = "...."
/>
tag, removing it fixed it.
I was trying to inflate a previous layout designed for a Actvity into the view-pager adapter.
My error was caused by a different problem.
I was passing a bundle from an Activity to its fragment.
When I commented the code receiving the bundle in the fragment the error was gone.
As it turns out, my error was due to the below "getArguments();" part which was returning null.
Bundle args = getArguments();
Upon checking the Activity sending code, I realized I had a silly mistake in the below;
Bundle bundle =new Bundle();
bundle.putInt("recipeID", recipe_position);
Fragment mainFragment = new MainActivityFragment();
mainFragment.setArguments(bundle);
FragmentManager fragmentManager = getSupportFragmentManager();
--> fragmentManager.beginTransaction()
.replace(R.id.container, new MainActivityFragment(),
DetailRecipeActivityFragment.TAG)
.commit();
I was creating a NEW fragment in the line with the arrow. Whereas I should have used the pre-instantiated fragment that already had my bundle.
So it should have been:
Bundle bundle =new Bundle();
bundle.putInt("recipeID", recipe_position);
Fragment mainFragment = new MainActivityFragment();
mainFragment.setArguments(bundle);
Fragment mainFragment = new MainActivityFragment();
FragmentManager fragmentManager = getSupportFragmentManager();
-->fragmentManager.beginTransaction()
.replace(R.id.container, mainFragment,
DetailRecipeActivityFragment.TAG)
.commit();
I don't know why exactly it throws this error instead of an NPE, but this solved my error in case someone is having the same scenario
I was having the same problem, in my case the package name was wrong, fixing it solved the problem.

Unable to instantiate android.gms.maps.SupportMapFragment

I have a view with a facebook style side bar navigation. On the main view I want to display my map. I have followed Google's tutorial exactly! But I keep running into the error Unable to instantiate android.gms.maps.SupportMapFragment.
I did manage to run this on a plain project but when I merge it with my main project this error pops up:
07-25 13:27:53.778: E/AndroidRuntime(24841):
Caused by: android.support.v4.app.Fragment$InstantiationException: Unable to instantiate fragment com.google.android.gms.maps.SupportMapFragment:
make sure class name exists, is public, and has an empty constructor that is public
I tried the answers posted below but the problem persists.
"Error inflating class fragment" with google map
and also this one:
Error java.lang.ClassNotFoundException: com.google.android.gms.maps.MapFragment in Google Map V2
The reference to the google sdk in project properties is also set.
Here is the class:
public class SlideAnimationThenCallLayout extends FragmentActivity implements AnimationListener {
View menu;
View app;
boolean menuOut = false;
AnimParams animParams = new AnimParams();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_slide_animation_then_call_layout);
LinearLayout linearLayout = (LinearLayout) findViewById(R.id.menu);
linearLayout.setOnTouchListener(new OnSwipeTouchListener(){
public void onSwipeRight() {
swipeAnimation();
}
});
RelativeLayout listview3 = (RelativeLayout) findViewById(R.id.relativeLayout1);
listview3.setOnTouchListener(new OnSwipeTouchListener(){
public void onSwipeRight() {
swipeAnimation();
}
public void onSwipeLeft() {
swipeAnimation();
}
});
menu = findViewById(R.id.menu);
app = findViewById(R.id.relativeLayout1);
}
The xml file is:
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/frame_layout1"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<LinearLayout
android:id="#+id/menu"
android:layout_width="match_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<ListView
android:id="#+id/listView3"
android:layout_width="match_parent"
android:layout_height="100dp"
android:background="#drawable/action_eating">
</ListView>
</LinearLayout>
<RelativeLayout
android:id="#+id/relativeLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/android_homescreen">
<fragment
android:id="#+id/map"
android:layout_width="match_parent"
android:layout_height="match_parent"
class="com.google.android.gms.maps.SupportMapFragment" />
</RelativeLayout>
I don't know what is wrong here now. Any Help would be greatly appreciated.
Judging by you error:
Caused by: android.support.v4.app.Fragment$InstantiationException: Unable to instantiate fragment com.google.android.gms.maps.SupportMapFragment:
make sure class name exists, is public, and has an empty constructor that is public
and the fact the SupportManFragment class is part of the google-play-services library, you problem is surtenly in the way you reference this library or the library it self.
I would suggest you to re-download it using the SDK-Manager and move it to a location where it path would be shorter and then try to reference it again using the answer you have in this question:
Error java.lang.ClassNotFoundException: com.google.android.gms.maps.MapFragment in Google Map V2
Right click on project ---> Android Tools ---> Add Support Library.
Download it and clear the project and build again. Hope it will work

Categories

Resources