NullPointerException onCreate() Android Studio - java

I have an activity where it will display a ListView in a one of the 5 tabs. This is the MainActivity class:
public class MainActivity extends ActionBarActivity {
Toolbar toolbar;
ViewPager pager;
ViewPagerAdapter adapter;
SlidingTabLayout tabs;
CharSequence Titles[]={"Home","Courses","Jobs","Me","More"};
int Numboftabs =5;
MaterialTabHost tabHost;
ListView listView;
String[]me = new String[] {
"My Profile",
"My Bookmarks",
"My Application History"
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Creating The Toolbar and setting it as the Toolbar for the activity
toolbar = (Toolbar) findViewById(R.id.tool_bar);
setSupportActionBar(toolbar);
// Creating The ViewPagerAdapter and Passing Fragment Manager, Titles fot the Tabs and Number Of Tabs.
adapter = new ViewPagerAdapter(getSupportFragmentManager(),Titles,Numboftabs);
// Assigning ViewPager View and setting the adapter
pager = (ViewPager) findViewById(R.id.pager);
pager.setAdapter(adapter);
// Assigning the Sliding Tab Layout View
tabs = (SlidingTabLayout) findViewById(R.id.tabs);
tabs.setDistributeEvenly(true); // To make the Tabs Fixed set this true, This makes the tabs Space Evenly in Available width
// Setting Custom Color for the Scroll bar indicator of the Tab View
tabs.setCustomTabColorizer(new SlidingTabLayout.TabColorizer() {
#Override
public int getIndicatorColor(int position) {
return getResources().getColor(R.color.tabsScrollColor);
}
});
// Setting the ViewPager For the SlidingTabsLayout
tabs.setViewPager(pager);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, me);
listView = (ListView)findViewById(R.id.listMe);
listView.setAdapter(adapter);
}
#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
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
This is the activity_main 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="vertical"
tools:context=".MainActivity">
<include
layout="#layout/tool_bar"
android:layout_height="wrap_content"
android:layout_width="match_parent"
/>
<itp231.dba.sit.nyp.com.tab_2.SlidingTabLayout
android:id="#+id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:elevation="2dp"
android:background="#color/ColorPrimary"/>
<android.support.v4.view.ViewPager
android:id="#+id/pager"
android:layout_height="match_parent"
android:layout_width="match_parent"
android:layout_weight="1">
</android.support.v4.view.ViewPager>
</LinearLayout>
This is the layout tab_4 XML:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ListView
android:id="#+id/listMe"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:entries="#array/Me"
/>
</RelativeLayout>
When I attempt to run the app, the app crashes and displayed the following errors in the logcat:
06-30 01:39:24.105 1632-1632/? E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: itp231.dba.sit.nyp.com.tab_2, PID: 1632
java.lang.RuntimeException: Unable to start activity ComponentInfo{itp231.dba.sit.nyp.com.tab_2/itp231.dba.sit.nyp.com.tab_2.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ListView.setAdapter(android.widget.ListAdapter)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2298)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360)
at android.app.ActivityThread.access$800(ActivityThread.java:144)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5221)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ListView.setAdapter(android.widget.ListAdapter)' on a null object reference
at itp231.dba.sit.nyp.com.tab_2.MainActivity.onCreate(MainActivity.java:76)
at android.app.Activity.performCreate(Activity.java:5937)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1105)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2251)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360)
            at android.app.ActivityThread.access$800(ActivityThread.java:144)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:135)
            at android.app.ActivityThread.main(ActivityThread.java:5221)
            at java.lang.reflect.Method.invoke(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:372)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)

See here:
setContentView(R.layout.activity_main);
you are setting "activity_main" as Layout. But in your Layout xml file there is no ListView with id listMe.
So shift this code to activity_main:
<ListView
android:id="#+id/listMe"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:entries="#array/Me"
/>
I hope it will work then.

Related

ListActivity Crashes With Click On RadioButton Menu

I am trying to add a Settings menu item to my overflow menu. The Settings menu has RadioButtons. The problem is that when I click on the Settings menu item the activity crashes.
What is wrong with my code?
Thank you for your help.
Java code:
public class AudioPlayer extends ListActivity
#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_action, 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
if (id == R.id.action_settings) {
setContentView(R.layout.audio_player_settings);
makeText(this, "Settings Menu Item Clicked", LENGTH_SHORT).show();
return true;
}
return super.onOptionsItemSelected(item);
}
menu_action.xml
<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=".PlayerActivity">
<item android:id="#+id/action_popup" android:title="Sort Popup" android:icon="#drawable/ic_sort"
android:showAsAction="always" />
<item android:id="#+id/action_settings" android:title="Settings"
app:showAsAction="never" />
<item android:id="#+id/action_help" android:title="Help"
app:showAsAction="never" />
audio_player_settings.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" android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin" tools:context=".PlayerActivity">
<RadioGroup xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/radio_group"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<RadioButton android:id="#+id/high_quality"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="High"
android:onClick="onRadioButtonClicked"/>
<RadioButton android:id="#+id/medium_quality"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Medium"
android:onClick="onRadioButtonClicked"/>
<RadioButton android:id="#+id/low_quality"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Low"
android:onClick="onRadioButtonClicked"/>
</RadioGroup>
</RelativeLayout>
Logcat:
03-08 12:22:10.300 31930-31930/com.test.audio E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.test.audio, PID: 31930
java.lang.RuntimeException: Your content must have a ListView whose id attribute is 'android.R.id.list'
at android.app.ListActivity.onContentChanged(ListActivity.java:243)
at com.android.internal.policy.impl.PhoneWindow.setContentView(PhoneWindow.java:382)
at android.app.Activity.setContentView(Activity.java:2145)
at com.test.audio.TouchActivity.onOptionsItemSelected(TouchActivity.java:2833)
at android.app.Activity.onMenuItemSelected(Activity.java:2885)
at com.android.internal.policy.impl.PhoneWindow.onMenuItemSelected(PhoneWindow.java:1133)
at com.android.internal.view.menu.MenuBuilder.dispatchMenuItemSelected(MenuBuilder.java:761)
at com.android.internal.view.menu.MenuItemImpl.invoke(MenuItemImpl.java:152)
at com.android.internal.view.menu.MenuBuilder.performItemAction(MenuBuilder.java:904)
at com.android.internal.view.menu.MenuBuilder.performItemAction(MenuBuilder.java:894)
at com.android.internal.view.menu.MenuPopupHelper.onItemClick(MenuPopupHelper.java:186)
at android.widget.AdapterView.performItemClick(AdapterView.java:305)
at android.widget.AbsListView.performItemClick(AbsListView.java:1146)
at android.widget.AbsListView$PerformClick.run(AbsListView.java:3053)
at android.widget.AbsListView$3.run(AbsListView.java:3860)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
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)
Inside your onOptionsItemSelected you are calling setContentView() which will set the layout of you Activity to the layout you want to use as the menu layout.
That layout doesn't contain any ListView so that's why you get the error.
I think you wanted to open a new activity or fragment instead of changing the current one layout.
Example for Activity:
Inside onOptionsItemSelected if:
...
if (id == R.id.action_settings) {
makeText(this, "Settings Menu Item Clicked", LENGTH_SHORT).show();
Intent intent = new Intent(this, AudioPlayerSettings.class);
startActivity(intent);
return true;
}
...
Then create an AudioPlayerSettings class using the pretended layout like the following:
public class AudioPlayerSettings extends Activity{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.audio_player_settings);
}
}

How do I fix the error Binary XML file line #26: Error inflating class fragment?

public class MainActivity extends ActionBarActivity
implements NavigationDrawerCallbacks {
/**
* Fragment managing the behaviors, interactions and presentation of the navigation drawer.
*/
private NavigationDrawerFragment mNavigationDrawerFragment;
private Toolbar mToolbar;
FragmentManager fragmentManager;
FragmentTransaction fragmentTransaction;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mToolbar = (Toolbar) findViewById(R.id.toolbar_actionbar);
setSupportActionBar(mToolbar);
mNavigationDrawerFragment = (NavigationDrawerFragment)
getSupportFragmentManager().findFragmentById(R.id.fragment_drawer);
// Set up the drawer.
mNavigationDrawerFragment.setup(R.id.fragment_drawer, (DrawerLayout) findViewById(R.id.drawer), mToolbar);
// populate the navigation drawer
}
#Override
public void onNavigationDrawerItemSelected(int position) {
fragmentManager = getSupportFragmentManager();
fragmentTransaction = fragmentManager.beginTransaction();
switch (position) {
case 0:
salahtimesparser salahfragment = new salahtimesparser();
fragmentTransaction.replace(R.id.container, salahfragment);
break;
case 1:
Compass CompassFragment = new Compass();
fragmentTransaction.replace(R.id.container, CompassFragment);
break;
case 2:
YouTubeFragment You = new YouTubeFragment();
fragmentTransaction.replace(R.id.container, You);
break;
case 3:
MapsFragment Maps = new MapsFragment();
fragmentTransaction.replace(R.id.container, Maps);
break;
}
fragmentTransaction.commit();
// update the main content by replacing fragments
Toast.makeText(this, "Menu item selected -> " + position, Toast.LENGTH_SHORT).show();
}
#Override
public void onBackPressed() {
if (mNavigationDrawerFragment.isDrawerOpen())
mNavigationDrawerFragment.closeDrawer();
else
super.onBackPressed();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
if (!mNavigationDrawerFragment.isDrawerOpen()) {
// Only show items in the action bar relevant to this screen
// if the drawer is not showing. Otherwise, let the drawer
// decide what to show in the action bar.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
return super.onCreateOptionsMenu(menu);
}
#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);
}
logcat:
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.kazam.salahtimes/com.kazam.salahtimes.MainActivity}: android.view.InflateException: Binary XML file line #26: Error inflating class fragment
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2658)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2723)
at android.app.ActivityThread.access$900(ActivityThread.java:172)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1422)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:145)
at android.app.ActivityThread.main(ActivityThread.java:5832)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1399)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1194)
Caused by: android.view.InflateException: Binary XML file line #26: Error inflating class fragment
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:770)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:813)
at android.view.LayoutInflater.inflate(LayoutInflater.java:511)
at android.view.LayoutInflater.inflate(LayoutInflater.java:415)
at android.view.LayoutInflater.inflate(LayoutInflater.java:366)
at android.support.v7.app.AppCompatDelegateImplV7.setContentView(AppCompatDelegateImplV7.java:276)
at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:139)
at com.kazam.salahtimes.MainActivity.onCreate(MainActivity.java:30)
at android.app.Activity.performCreate(Activity.java:6221)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1119)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2611)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2723) 
at android.app.ActivityThread.access$900(ActivityThread.java:172) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1422) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:145) 
at android.app.ActivityThread.main(ActivityThread.java:5832) 
at java.lang.reflect.Method.invoke(Native Method) 
at java.lang.reflect.Method.invoke(Method.java:372) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1399) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1194) 
Caused by: java.lang.NullPointerException
at java.lang.VMClassLoader.findLoadedClass(Native Method)
at java.lang.ClassLoader.findLoadedClass(ClassLoader.java:362)
at java.lang.ClassLoader.loadClass(ClassLoader.java:499)
at java.lang.ClassLoader.loadClass(ClassLoader.java:469)
at android.support.v4.app.Fragment.isSupportFragmentClass(Fragment.java:454)
at android.support.v4.app.FragmentManagerImpl.onCreateView(FragmentManager.java:2252)
at android.support.v4.app.FragmentController.onCreateView(FragmentController.java:120)
at android.support.v4.app.FragmentActivity.dispatchFragmentsOnCreateView(FragmentActivity.java:357)
at android.support.v4.app.BaseFragmentActivityHoneycomb.onCreateView(BaseFragmentActivityHoneycomb.java:31)
at android.support.v4.app.FragmentActivity.onCreateView(FragmentActivity.java:80)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:740)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:813) 
at android.view.LayoutInflater.inflate(LayoutInflater.java:511) 
at android.view.LayoutInflater.inflate(LayoutInflater.java:415) 
at android.view.LayoutInflater.inflate(LayoutInflater.java:366) 
at android.support.v7.app.AppCompatDelegateImplV7.setContentView(AppCompatDelegateImplV7.java:276) 
at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:139) 
at com.kazam.salahtimes.MainActivity.onCreate(MainActivity.java:30) 
at android.app.Activity.performCreate(Activity.java:6221) 
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1119) 
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2611) 
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2723) 
at android.app.ActivityThread.access$900(ActivityThread.java:172) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1422) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:145) 
at android.app.ActivityThread.main(ActivityThread.java:5832) 
at java.lang.reflect.Method.invoke(Native Method) 
at java.lang.reflect.Method.invoke(Method.java:372) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1399) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1194) 
I am wondering if anyone has the solution for this fix or how I can fix this problem?
is there a work around this?
I am current using Android studio and all my fragments imports are import android.support.v4.app not the other 1.
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/drawer"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<include
android:id="#+id/toolbar_actionbar"
layout="#layout/toolbar_default"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
<FrameLayout
android:id="#+id/container"
android:clickable="true"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</LinearLayout>
<!-- android:layout_marginTop="?android:attr/actionBarSize"-->
<fragment
android:id="#+id/fragment_drawer"
android:layout_marginTop="#dimen/abc_action_bar_default_height_material"
android:layout_width="#dimen/navigation_drawer_width"
android:layout_height="match_parent"
android:layout_gravity="start"
app:layout="#layout/fragment_navigation_drawer"/>
</android.support.v4.widget.DrawerLayout>
If you use the fragment tag in your layout XML, you must provide the fragment class name in the android:name attribute.

Cannot include a RecyclerView inside a Navigation Drawer Fragment

I've been trying to display a CardView list inside the first Fragment of a Navigation Drawer. I'm currently using the Navigation Drawer template from Android Studio.
I have no trouble when defining the fragments, they are shown correctly within the Navigation Drawer, but when it's time to include a RecyclerView, I receive a java.lang.NullPointerException
Here is the MainActivity
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
public DrawerLayout drawer;
public Toolbar toolbar;
public NavigationView navigationView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Initialize Fragment
QuestListFragment fragment = new QuestListFragment();
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.fragment_container, fragment);
fragmentTransaction.commit();
//Toolbar
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
// DrawerLayout
drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.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
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_camera) {
QuestListFragment fragment = new QuestListFragment();
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.fragment_container, fragment);
fragmentTransaction.commit();
} else if (id == R.id.nav_gallery) {
TestFragment fragment = new TestFragment();
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.fragment_container, fragment);
fragmentTransaction.commit();
} else if (id == R.id.nav_slideshow) {
} else if (id == R.id.nav_manage) {
} else if (id == R.id.nav_share) {
} else if (id == R.id.nav_send) {
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}}
And the QuestListFragment
public class QuestListFragment extends Fragment {
private RecyclerView mQuestRecyclerView;
public QuestListFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_quest, container, false);
// RecyclerView
mQuestRecyclerView = (RecyclerView) view.findViewById(R.id.quest_recycler_view);
mQuestRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
return view;
}}
I have tried different ways to implement the RecyclerView but all of them end up in Fatal Exception just by declaring it. An empty Fragment should be seen instead of this error.
Thanks in advance.
EDIT:
Here is the XML where the fragment_container is located, "app_bar_main".
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
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="es.smoreno.tfg.MainActivity">
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
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>
<FrameLayout
android:id="#+id/fragment_container"
android:layout_width="match_parent"
android:layout_height="match_parent"></FrameLayout>
<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"/>
</android.support.design.widget.CoordinatorLayout>
The fragment_quest.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=".QuestListFragment">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="List Quest"
android:id="#+id/textView2"
android:layout_gravity="center"/>
And this is the full Logcat
04-11 22:31:13.178 2358-2358/es.smoreno.tfg E/AndroidRuntime: FATAL EXCEPTION: main
Process: es.smoreno.tfg, PID: 2358
java.lang.RuntimeException: Unable to start activity ComponentInfo{es.smoreno.tfg/es.smoreno.tfg.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.v7.widget.RecyclerView.setLayoutManager(android.support.v7.widget.RecyclerView$LayoutManager)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2416)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
at android.app.ActivityThread.-wrap11(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.v7.widget.RecyclerView.setLayoutManager(android.support.v7.widget.RecyclerView$LayoutManager)' on a null object reference
at es.smoreno.tfg.QuestListFragment.onCreateView(QuestListFragment.java:34)
at android.support.v4.app.Fragment.performCreateView(Fragment.java:1974)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1067)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1252)
at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:742)
at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1617)
at android.support.v4.app.FragmentController.execPendingActions(FragmentController.java:339)
at android.support.v4.app.FragmentActivity.onStart(FragmentActivity.java:602)
at android.app.Instrumentation.callActivityOnStart(Instrumentation.java:1237)
at android.app.Activity.performStart(Activity.java:6253)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2379)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476) 
at android.app.ActivityThread.-wrap11(ActivityThread.java) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:148) 
at android.app.ActivityThread.main(ActivityThread.java:5417) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616) 
There is no RecyclerView in your fragment_quest.xml

Android App Crashing at setSupportActionBar

I'm trying to follow the following tutorial to create a tab view layout: http://www.android4devs.com/2015/01/how-to-make-material-design-sliding-tabs.html
Unfortunately, the app kept crashing before anything came up. After inserting debug logs into my code, I found that the problem resided in the line setSupportActionBar(toolbar) in MainActivity. I have no idea why this is happening. I have pasted my entire MainActivity file below.
package com.example.rkhaj.tabstest;
import android.support.v4.view.ViewPager;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
public class MainActivity extends AppCompatActivity {
// Declaring Your View and Variables
Toolbar toolbar;
ViewPager pager;
ViewPagerAdapter adapter;
SlidingTabLayout tabs;
CharSequence Titles[]={"Home","Events"};
int Numboftabs =2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d("icecream", "position 1");
// Creating The Toolbar and setting it as the Toolbar for the activity
toolbar = (Toolbar) findViewById(R.id.tool_bar);
Log.d("icecream", "position 1.5");
setSupportActionBar(toolbar);
Log.d("icecream", "position 2");
// Creating The ViewPagerAdapter and Passing Fragment Manager, Titles fot the Tabs and Number Of Tabs.
adapter = new ViewPagerAdapter(getSupportFragmentManager(),Titles,Numboftabs);
Log.d("icecream", "position 3");
// Assigning ViewPager View and setting the adapter
pager = (ViewPager) findViewById(R.id.pager);
pager.setAdapter(adapter);
Log.d("icecream", "position 4");
// Assinging the Sliding Tab Layout View
tabs = (SlidingTabLayout) findViewById(R.id.tabs);
tabs.setDistributeEvenly(true); // To make the Tabs Fixed set this true, This makes the tabs Space Evenly in Available width
Log.d("icecream", "position 5");
// Setting Custom Color for the Scroll bar indicator of the Tab View
tabs.setCustomTabColorizer(new SlidingTabLayout.TabColorizer() {
#Override
public int getIndicatorColor(int position) {
return getResources().getColor(R.color.tabsScrollColor);
}
});
Log.d("icecream", "position 6");
// Setting the ViewPager For the SlidingTabsLayout
tabs.setViewPager(pager);
Log.d("icecream", "position 7");
}
#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
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
This is activity_main.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="vertical"
tools:context=".MainActivity">
<include
android:id="#+id/tool_bar"
layout="#layout/tool_bar"
android:layout_height="wrap_content"
android:layout_width="match_parent"
/>
<com.example.rkhaj.tabstest.SlidingTabLayout
android:id="#+id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:elevation="2dp"
android:background="#color/ColorPrimary"/>
<android.support.v4.view.ViewPager
android:id="#+id/pager"
android:layout_height="match_parent"
android:layout_width="match_parent"
android:layout_weight="1"
>
</android.support.v4.view.ViewPager>
</LinearLayout>
This is the logcat:
09-07 16:46:27.772 22833-22833/com.example.rkhaj.tabstest I/art﹕ Late-enabling -Xcheck:jni
09-07 16:46:27.772 22833-22833/com.example.rkhaj.tabstest I/art﹕ VMHOOK: rlim_cur : 0 pid:22833
09-07 16:46:27.812 22833-22833/com.example.rkhaj.tabstest E/Typeface﹕ SANS_LOC file not found.
09-07 16:46:27.882 22833-22833/com.example.rkhaj.tabstest D/icecream﹕ position 1
09-07 16:46:27.882 22833-22833/com.example.rkhaj.tabstest D/icecream﹕ position 1.5
09-07 16:46:27.882 22833-22833/com.example.rkhaj.tabstest E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.example.rkhaj.tabstest, PID: 22833
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.rkhaj.tabstest/com.example.rkhaj.tabstest.MainActivity}: java.lang.IllegalStateException: This Activity already has an action bar supplied by the window decor. Do not request Window.FEATURE_SUPPORT_ACTION_BAR and set windowActionBar to false in your theme to use a Toolbar instead.
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2411)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2474)
at android.app.ActivityThread.access$800(ActivityThread.java:144)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1359)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:155)
at android.app.ActivityThread.main(ActivityThread.java:5696)
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:1029)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:824)
Caused by: java.lang.IllegalStateException: This Activity already has an action bar supplied by the window decor. Do not request Window.FEATURE_SUPPORT_ACTION_BAR and set windowActionBar to false in your theme to use a Toolbar instead.
at android.support.v7.app.AppCompatDelegateImplV7.setSupportActionBar(AppCompatDelegateImplV7.java:197)
at android.support.v7.app.AppCompatActivity.setSupportActionBar(AppCompatActivity.java:99)
at com.example.rkhaj.tabstest.MainActivity.onCreate(MainActivity.java:34)
at android.app.Activity.performCreate(Activity.java:5958)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1129)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2364)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2474)
            at android.app.ActivityThread.access$800(ActivityThread.java:144)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1359)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:155)
            at android.app.ActivityThread.main(ActivityThread.java:5696)
            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:1029)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:824)
09-07 16:46:39.442 22833-22833/com.example.rkhaj.tabstest D/Process﹕ killProcess, pid=22833
09-07 16:46:39.442 22833-22833/com.example.rkhaj.tabstest D/Process﹕ com.android.internal.os.RuntimeInit$UncaughtHandler.uncaughtException:138 java.lang.ThreadGroup.uncaughtException:693 java.lang.ThreadGroup.uncaughtException:690
Since you are using a Toolbar in your layout, you should use Theme.AppCompat.NoActionBar as your parent theme.
Otherwise you can use somenthing like:
<style name="MyTheme" parent="Theme.AppCompat">
...
</style>
<style name="MyTheme.NoActionBar">
<!-- Both of these are needed -->
<item name="windowActionBar">false</item>
<item name="windowNoTitle">true</item>
</style>
You need to use an AppCompat theme for the activity. One like this, Theme.AppCompat.Light.NoActionBar
This comment helped me when copying code from into a a new project:
don't forget to add android:theme="#style/AppTheme.NoActionBar" to
your activity declaration in AndroidManifest.xml. I knew this
needed to be there but forgot to add it and I couldn't figure out why
my app was crashing at setupActionBar() in my Activity - This fixed
it. – DangerPaws
It should be a standalone answer :-)

ListView Returning Null After Being Intitalized

I have searched SO and it seems like the solutions to other problems like mine aren't doing it for me.
I am getting a NullPointerException on my setAdapter(). Here is the code:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_select_file);
String currentDir = getApplicationContext().getFilesDir().getAbsolutePath();
File file[] = GetFiles(currentDir);
ArrayList<String> files = getFileNames(file);
final ArrayAdapter arrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, files);
listView = (ListView)findViewById(android.R.id.list);
listView.setAdapter(arrayAdapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent myActivity = new Intent(SelectFile.this, MyActivity.class);
myActivity.putExtra("filename", String.valueOf(listView.getItemAtPosition(position)));
startActivity(myActivity);
finish();
}
});
}
And the 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:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
tools:context="edu.niu.cs.jacob.journal.SelectFile"
android:id="#+id/relativeLay">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Select A File"
android:id="#+id/textView"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"/>
<ListView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/list"
android:layout_centerHorizontal="true"
android:layout_below="#android:id/list"/>
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ListView.setAdapter(android.widget.ListAdapter)' on a null object reference
at edu.niu.cs.jacob.journal.SelectFile.onCreate(SelectFile.java:44)
at android.app.Activity.performCreate(Activity.java:6221)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1119)
at
android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2614)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2728)
            at android.app.ActivityThread.access$900(ActivityThread.java:172)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1421)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:145)
            at android.app.ActivityThread.main(ActivityThread.java:5837)
            at java.lang.reflect.Method.invoke(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:372)
I have narrowed it down to the fact that the ListView is still null when it is initialized with findViewById. I have checked to make sure it is referring to the correct element in the correct XML file. What else could be causing this issue?
This is used for ListActivity: android.R.id.list.
Change:
listView = (ListView)findViewById(android.R.id.list);
To:
listView = (ListView)findViewById(R.id.list);
Please see this similar question: Your content must have a ListView whose id attribute is 'android.R.id.list'
This is because you are not using your own R. Change the findViewById to
listView = (ListView)findViewById(R.id.list);

Categories

Resources