#android:id/list cannot resolve symbol - android

import android.app.ListFragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
/**
* Created by name on 3/13/17.
* Used for the specials tab to allow a list of days to choose what special one would like to view
*/
public class SpecialsScroll extends ListFragment implements AdapterView.OnItemClickListener{
public SpecialsScroll(){
//Empty Constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
super.onCreate(savedInstanceState);
return inflater.inflate(R.layout.fragment_specials_scroll, container, false);
}
#Override
public void onActivityCreated(Bundle savedInstanceState){
super.onActivityCreated(savedInstanceState);
setListAdapter(ArrayAdapter.createFromResource(getActivity(), R.array.days, android.R.layout.simple_list_item_1)); //Loads array into the ListFragment
getListView().setOnItemClickListener(this); //activates the listener for this Fragment class
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id){ // For checking when a user taps on an option
SpecialsPage specialsPage = new SpecialsPage();
Bundle foodArgs = new Bundle();
switch (position){ // checks what option is chosen and sends respective keys as parameters
case 0:
int[] keysMonday = {R.string.boom_boom_enchiladas_key, R.string.tacos_mexican_key};
foodArgs.putIntArray("keys", keysMonday);
break;
case 1:
int[] keysTuesday = {R.string.shrimp_avocado_tacos_key, R.string.green_chile_chicken_enchiladas_key};
foodArgs.putIntArray("keys", keysTuesday);
break;
}
specialsPage.setArguments(foodArgs);
getActivity().getFragmentManager().beginTransaction().replace(R.id.container, specialsPage).addToBackStack(null).commit();
}
}
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.BottomNavigationView;
import android.support.v7.app.AppCompatActivity;
import android.view.MenuItem;
public class MainActivity extends AppCompatActivity{
private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener
= new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
if(getFragmentManager().findFragmentByTag("CURRENT") == null){
getFragmentManager().beginTransaction().add(R.id.container, new SpecialsScroll(), "CURRENT").commit();
}
switch (item.getItemId()) {
case R.id.special:
getFragmentManager().beginTransaction().replace(R.id.container, new SpecialsScroll(), "CURRENT").commit();
return true;
case R.id.locations:
getFragmentManager().beginTransaction().replace(R.id.container, new LocationsScroll(), "CURRENT").commit();
return true;
case R.id.order:
return true;
}
return false;
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
BottomNavigationView navigation = (BottomNavigationView) findViewById(R.id.navigation);
navigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener);
getFragmentManager().beginTransaction().add(R.id.container, new SpecialsScroll(), "CURRENT").commit();
}
}
So, I am trying to create a ListView and everything in the code works, but suddenly I am unable to get the xml to recognize the android:id/list attribute for some reason, I don't know why. When I click on an item in the listview in my app it still does what it should, I just really want to get rid of the error.
<?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"
android:background="#color/white">
<ListView
android:id="#android:id/list"
android:layout_width="match_parent"
android:layout_height="match_parent">
</ListView>
<TextView
android:id="#+id/text_specialsscroll"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
04-26 14:06:30.299 2576-2576
/com.namename.www.name
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.namename.www.name, PID: 2576
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.namename.www.name/com.namename.www.name.MainActivity}: java.lang.RuntimeException: Content has view with id attribute 'android.R.id.list' that is not a ListView class
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2665)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2726)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1477)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6119)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
Caused by: java.lang.RuntimeException: Content has view with id attribute 'android.R.id.list' that is not a ListView class
at android.app.ListFragment.ensureList(ListFragment.java:402)
at android.app.ListFragment.onViewCreated(ListFragment.java:203)
at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:1010)
at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:1171)
at android.app.BackStackRecord.run(BackStackRecord.java:816)
at android.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1578)
at android.app.FragmentController.execPendingActions(FragmentController.java:371)
at android.app.Activity.performStart(Activity.java:6695)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2628)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2726) 
at android.app.ActivityThread.-wrap12(ActivityThread.java) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1477) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:154) 
at android.app.ActivityThread.main(ActivityThread.java:6119) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)

Change your id to this:
<ListView
android:id="#+id/list"
android:layout_width="match_parent"
android:layout_height="match_parent">
</ListView>

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.

ViewPager obj is null even though it initilized correctly and also present in the defined layout xml

Before posting I checked many questions but they didn't helped me. Most of the answers says that the ViewPager is in different layout, so that is why it generating null pointer exception.
Below is my stacktrace
E/AndroidRuntime: FATAL EXCEPTION: main Process: pdfshare.hemanthreddy.com.pdfshare, PID: 29092
java.lang.RuntimeException: Unable to start activity ComponentInfo{pdfshare.hemanthreddy.com.pdfshare/pdfshare.hemanthreddy.com.pdfshare.activities.HomeScreen}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.v4.view.ViewPager.setAdapter(android.support.v4.view.PagerAdapter)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2426)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2490)
at android.app.ActivityThread.access$900(ActivityThread.java:154)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1354)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5443)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:728)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.v4.view.ViewPager.setAdapter(android.support.v4.view.PagerAdapter)' on a null object reference
at pdfshare.hemanthreddy.com.pdfshare.activities.HomeScreen.onCreate(HomeScreen.java:39)
at android.app.Activity.performCreate(Activity.java:6259)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1130)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2379)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2490)
at android.app.ActivityThread.access$900(ActivityThread.java:154)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1354)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5443)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:728)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618)
This is my xml file where I have declared Viewpager
activity_home_screen.xml
<?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:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto"
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="pdfshare.hemanthreddy.com.pdfshare.activities.HomeScreen">
<android.support.v4.view.ViewPager
android:id="#+id/viewpagerhome"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior" />
</RelativeLayout>
Activity class HomeScreen.java
package pdfshare.hemanthreddy.com.pdfshare.activities;
import android.graphics.Color;
import android.support.annotation.IdRes;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;
import com.roughike.bottombar.BottomBar;
import com.roughike.bottombar.BottomBarBadge;
import com.roughike.bottombar.BottomBarTab;
import com.roughike.bottombar.OnMenuTabSelectedListener;
import com.roughike.bottombar.OnTabSelectedListener;
import pdfshare.hemanthreddy.com.pdfshare.R;
import pdfshare.hemanthreddy.com.pdfshare.fragments.GroupsFragment;
import pdfshare.hemanthreddy.com.pdfshare.fragments.HomeFragment;
import pdfshare.hemanthreddy.com.pdfshare.fragments.NotificationsFragment;
import pdfshare.hemanthreddy.com.pdfshare.fragments.ProfileFragment;
public class HomeScreen extends AppCompatActivity {
ViewPager pager;
BottomBar bottomBar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home_screen);
bottomBar = BottomBar.attach(this,savedInstanceState);
pager = (ViewPager) findViewById(R.id.viewpagerhome);
MyPagerAdapter obj = new MyPagerAdapter(getSupportFragmentManager());
//the following two if statements are used to check if objects are null
if(obj.getCount()==4)
Log.e("obj","not null");
if(pager == null)
Log.e("pager","null");
pager.setAdapter(obj);
bottomBar.setItems(new BottomBarTab(R.mipmap.ic_action_home_24,"home"),
new BottomBarTab(R.mipmap.ic_action_user_group,"groups"),
new BottomBarTab(R.mipmap.ic_action_notification,"notifications"),
new BottomBarTab(R.mipmap.ic_action_profile,"profile")
);
bottomBar.setOnItemSelectedListener(new OnTabSelectedListener() {
#Override
public void onItemSelected(int position) {
T oast.makeText(getApplicationContext(),position,Toast.LENGTH_LONG).show();
pager.setCurrentItem(position);
}
});
BottomBarBadge message = bottomBar.makeBadgeForTabAt(2,"red",10);
message.show();
}
private class MyPagerAdapter extends FragmentStatePagerAdapter
{
public MyPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
switch (position)
{
case 0:
return new HomeFragment();
case 1:
return new GroupsFragment();
case 2:
return new NotificationsFragment();
case 3:
return new ProfileFragment();
default:
return new HomeFragment();
}
}
#Override
public int getCount() {
return 4;
}
}
}
E/obj: not null
E/pager: null
dont know why pager object is null.
Please help me I am trying to load 4 fragments in viewPager, thank you.
it means your variable obj of type MyPagerAdapter is null, there is an error with it's return value.
MyPagerAdapter obj = new MyPagerAdapter(getSupportFragmentManager());
That line is the problem, the problem could be in your custom adapter, or your get support fragment manager. if they were working the obj would not be null.
i bet if you comment out that line and the setadapter line it won't crash anymore, unless you have bigger problems

Android Studio - Dynamic Fragment crashing App

I am trying to link a Fragment, RecycleView and CardView using a variation of the tutorial found on:
http://www.treyrobinson.net/blog/android-l-tutorials-part-3-recyclerview-and-cardview/
Unfortunately my app crashes with the following error message:
"java.lang.IllegalStateException: RecyclerView has no LayoutManager"
I am fairly new with Android development. I tried to find similar issues on Stackoverflow but am unable to find the issue. Any help would be greatly appreciated!
Layout of the main activity: "activity_library.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"
tools:context=".LibraryActivity">
<android.support.v7.widget.RecyclerView
android:id="#+id/library_activity_recycler_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".LibraryActivity"
/>
</RelativeLayout>
The main activity class "LibraryActivity.java":
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
public class LibraryActivity extends AppCompatActivity{
private static final String TAG = LibraryActivity.class.getSimpleName();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); /**Create the activity and populate the savedInstanceState if the activity existed but has been destroyed (otherwise savedInstanceState will return 'null'*/
setContentView(R.layout.activity_library); /** Call to the XML layout library which display the activity */
if (savedInstanceState != null) {
// Restore value of members from saved state
} else {
// Probably initialize members with default values for a new instance
}
try {
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
BooksFragment bookFragment = new BooksFragment();
fragmentTransaction.add(R.id.library_activity_recycler_view,bookFragment);
/*The line below is the one generating the error - java.lang.IllegalStateException: RecyclerView has no LayoutManager*/
fragmentTransaction.commit();
}
catch(Exception e){
Log.d(TAG,"[ERROR] " + e.getMessage());
}
}
}
The layout of the fragment "fragment_books.xml":
<?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="match_parent"
android:orientation="vertical" >
<android.support.v7.widget.RecyclerView
android:id="#+id/Book_Recycler_View"
android:layout_width="match_parent"
android:layout_height="match_parent">
</android.support.v7.widget.RecyclerView>
</LinearLayout>
And the fragment class:
import android.app.Fragment;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class BooksFragment extends Fragment {
public BooksFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.activity_library, container, false);
LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
RecyclerView bookRecycler = (RecyclerView) v.findViewById(R.id.library_activity_recycler_view);
bookRecycler.setLayoutManager(layoutManager);
BookRecyclerViewAdapter adapter = new BookRecyclerViewAdapter();
bookRecycler.setAdapter(adapter);
/*In the line below should we return the view 'v' or the RecyclerView 'bookRecycler'??*/
return bookRecycler;
}
}
As I said I am fairly new to Android and therefore apologies if my code contains quite a few errors. Thanks for your help!
For reference the complete error log:
04-18 14:04:52.323 11225-11225/com.wldtaster.tellmeastory E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.wldtaster.tellmeastory, PID: 11225
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.wldtaster.tellmeastory/com.wldtaster.tellmeastory.LibraryActivity}: java.lang.IllegalStateException: RecyclerView has no LayoutManager
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2325)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387)
at android.app.ActivityThread.access$800(ActivityThread.java:151)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5254)
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:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
Caused by: java.lang.IllegalStateException: RecyclerView has no LayoutManager
at android.support.v7.widget.RecyclerView.generateLayoutParams(RecyclerView.java:3393)
at android.view.LayoutInflater.inflate(LayoutInflater.java:492)
at android.view.LayoutInflater.inflate(LayoutInflater.java:414)
at com.wldtaster.tellmeastory.BooksFragment.onCreateView(BooksFragment.java:23)
at android.app.Fragment.performCreateView(Fragment.java:2053)
at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:894)
at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:1067)
at android.app.BackStackRecord.run(BackStackRecord.java:834)
at android.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1452)
at android.app.Activity.performStart(Activity.java:6005)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2288)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387) 
at android.app.ActivityThread.access$800(ActivityThread.java:151) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:135) 
at android.app.ActivityThread.main(ActivityThread.java:5254) 
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:903) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698) 
You must return the view ie. v in the onCreateView method of the Fragment inherited class.

Unable to start activity ComponentInfo : android.view.InflateException: Binary XML file line #7: Error inflating class fragment

I'm getting the below error when trying out the Fragments in Android Studio. The below exception occurs when launching the app :
04 - 24 21: 02: 16.830 21108 - 21108 / com.example.user.samplefragments E / AndroidRuntime: FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to start activity ComponentInfo {
com.example.user.samplefragments / com.example.user.samplefragments.MainActivity
}: android.view.InflateException: Binary XML file line #7: Error inflating class fragment
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2245)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2299)
at android.app.ActivityThread.access$700(ActivityThread.java:150)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1280)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5283)
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:1102)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:869)
at dalvik.system.NativeStart.main(Native Method)
Caused by: android.view.InflateException: Binary XML file line # 7: Error inflating class fragment
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java: 710)
at android.view.LayoutInflater.rInflate(LayoutInflater.java: 752)
at android.view.LayoutInflater.inflate(LayoutInflater.java: 495)
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: 364)
at android.app.Activity.setContentView(Activity.java: 1930)
at com.example.user.samplefragments.MainActivity.onCreate(MainActivity.java: 19)
at android.app.Activity.performCreate(Activity.java: 5283)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java: 1097)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java: 2209)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java: 2299) 
at android.app.ActivityThread.access$700(ActivityThread.java: 150) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java: 1280) 
at android.os.Handler.dispatchMessage(Handler.java: 99) 
at android.os.Looper.loop(Looper.java: 137) 
at android.app.ActivityThread.main(ActivityThread.java: 5283) 
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: 1102) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java: 869) 
at dalvik.system.NativeStart.main(Native Method) 
Caused by: java.lang.NullPointerException
at com.example.user.samplefragments.MenuFragment.onCreateView(MenuFragment.java: 23)
at android.app.Fragment.performCreateView(Fragment.java: 1699)
at android.app.FragmentManagerImpl.moveToState(FragmentManager.java: 879)
at android.app.FragmentManagerImpl.moveToState(FragmentManager.java: 1053)
at android.app.FragmentManagerImpl.addFragment(FragmentManager.java: 1155)
at android.app.Activity.onCreateView(Activity.java: 4872)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java: 686)
at android.view.LayoutInflater.rInflate(LayoutInflater.java: 752) 
at android.view.LayoutInflater.inflate(LayoutInflater.java: 495) 
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: 364) 
at android.app.Activity.setContentView(Activity.java: 1930) 
at com.example.user.samplefragments.MainActivity.onCreate(MainActivity.java: 19) 
at android.app.Activity.performCreate(Activity.java: 5283) 
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java: 1097) 
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java: 2209) 
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java: 2299) 
at android.app.ActivityThread.access$700(ActivityThread.java: 150) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java: 1280) 
at android.os.Handler.dispatchMessage(Handler.java: 99) 
at android.os.Looper.loop(Looper.java: 137) 
at android.app.ActivityThread.main(ActivityThread.java: 5283) 
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: 1102) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java: 869) 
at dalvik.system.NativeStart.main(Native Method) 
This is my MainActvity.java :
package com.example.user.samplefragments;
import android.app.Activity;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v4.app.FragmentActivity;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
public class MainActivity extends Activity implements MenuFragment.OnItemSelectedListener{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
public void onItemSelected(String link) {
DetailFragment fragment = (DetailFragment)getFragmentManager().findFragmentById(R.id.detailfragment);
fragment.setText(link);
}
}
This is my Fragment 1 :
package com.example.user.samplefragments;
import android.app.Fragment;
import android.content.Context;
import android.os.Bundle;
import android.provider.Settings;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
/**
* Created by USER on 24-04-2016.
*/
public class MenuFragment extends Fragment{
private OnItemSelectedListener listener;
public MenuFragment(){}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.menu,container,false);
Button btn = (Button)getView().findViewById(R.id.button);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
updateDetail("fake");
}
});
return view;
}
public void updateDetail(String uri){
String newTime = String.valueOf(System.currentTimeMillis());
listener.onItemSelected(newTime);
}
public interface OnItemSelectedListener {
public void onItemSelected(String link);
}
}
This is my Fragment 2 :
package com.example.user.samplefragments;
import android.app.Fragment;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
/**
* Created by USER on 24-04-2016.
*/
public class DetailFragment extends Fragment{
public DetailFragment(){}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.detail,container,false);
return view;
}
public void setText(String url){
TextView tv = (TextView)getView().findViewById(R.id.textView);
tv.setText(url);
}
}
This is my activity_main.xml :
Just using two fragments inside the main layout.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:baselineAligned="false"
android:orientation="horizontal" >
<fragment
android:id="#+id/menufragment"
class="com.example.user.samplefragments.MenuFragment" /**Declaring the class of the fragment*/
android:layout_height="match_parent"
android:layout_width="5dp">
</fragment>
<fragment
android:id="#+id/detailfragment"
class="com.example.user.samplefragments.DetailFragment"
android:layout_height="match_parent"
android:layout_width="5dp">
</fragment>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="New Button"
android:id="#+id/button2" />
</LinearLayout>
As you can see, the error I'm getting :
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.user.samplefragments/com.example.user.samplefragments.MainActivity}: android.view.InflateException: Binary XML file line #7: Error inflating class fragment.
I know this issue occurs when the package name is wrong, but I have given the correct package name. How can I resolve this?
Solution:
You can modify your MenuFragment using follow:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.menu, container, false);
Button btn = (Button)view.findViewById(R.id.button);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
updateDetail("fake");
}
});
return view;
}
Why:
Every time onCreateView is invoked, the view in the fragment is just about to create.At that time there is no view in your fragment.So getView() always returns null invoked in onCreateView. That's why you've got NullPointerException when inflating fragment in your xml.
To avoid NullPointer, try this:
public void updateDetail(String uri){
String newTime = String.valueOf(System.currentTimeMillis());
if ( listener != null ){
listener.onItemSelected(newTime);
}
}
I think This line makes the app crashing,
Button btn = (Button)getView().findViewById(R.id.button);
Replace this line with
Button btn = (Button)view.findViewById(R.id.button);
It will work if your button contains in the fragment xml (R.layout.menu).

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.

Categories

Resources