Android App Crashing at setSupportActionBar - java

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 :-)

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.

Application crashing in Android:Runtime exception

I started with Android like 2 days ago and please forgive me if I have made a naive error.I am making the interface in Java instead of XML and the application crashes every time I launch it on the emulator.Here is the stack trace for the same:
03-01 21:08:46.941 7640-7640/com.example.prashant.wisdom E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.prashant.wisdom, PID: 7640
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.prashant.wisdom/com.example.prashant.wisdom.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.design.widget.FloatingActionButton.setOnClickListener(android.view.View$OnClickListener)' 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.design.widget.FloatingActionButton.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
at com.example.prashant.wisdom.MainActivity.onCreate(MainActivity.java:65)
at android.app.Activity.performCreate(Activity.java:6237)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1107)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2369)
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) 
03-01 21:08:49.797 7640-7640/? I/Process: Sending signal. PID: 7640 SIG: 9
Here is MainActivity.java:
package com.example.prashant.wisdom;
import android.graphics.Color;
import android.os.Bundle;
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.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.RelativeLayout;
import android.widget.Button;
import android.widget.EditText;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
RelativeLayout layout=new RelativeLayout(this); //layout
Button button=new Button(this); //button
button.setText("SignIn");
//giving ids to layout and button
button.setId(1);
layout.setId(2);
//rules for button positioning
RelativeLayout.LayoutParams buttonDetails=new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.WRAP_CONTENT,
RelativeLayout.LayoutParams.WRAP_CONTENT
); //the above snippet is to be written for every widget in the activity.
// For example,we'll write one for EditText also.
buttonDetails.addRule(RelativeLayout.CENTER_HORIZONTAL);
buttonDetails.addRule(RelativeLayout.CENTER_VERTICAL);
EditText username=new EditText(this); //username input
username.setId(3);
RelativeLayout.LayoutParams usernameDetails=new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.WRAP_CONTENT,
RelativeLayout.LayoutParams.WRAP_CONTENT
); //rules for the EditText details.
//now we've to place the EditText above the button that is already positioned in the center.
//the following snippet does that.
usernameDetails.addRule(RelativeLayout.ABOVE,button.getId());
usernameDetails.addRule(RelativeLayout.CENTER_HORIZONTAL); //Rule for positioing in the center of the screen
usernameDetails.setMargins(0,0,0,50); //padding on all the sides.We're adding padding just to the bottom
//hence the rest are zero, but the bottom one is 50 pixels.
layout.addView(username); //EditText now positioned on the layout.
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
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();
}
});
setContentView(layout); //placement of layout itself
layout.addView(button, buttonDetails); //placement of buttons on the layout
}
#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);
}
}
And here is content_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:context="com.example.prashant.wisdom.MainActivity"
tools:showIn="#layout/activity_main">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
</RelativeLayout>
You dont have a FAB defined in your xml so
findViewById(R.id.fab);
returns null and you get a simple NullpointerException accessing it
You have to call setContentView before you can find views in your layout (findViewById).
Also it seems like none of your xml files is actually used in code, so nothing defined in any xml will be accessible.

NullPointerException onCreate() Android Studio

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.

Show fragment when click ActionBar menu return null

I want to show/hide fragment when i click the action bar menu item. But my app give me error when i click. Fragment coming on first run. When I want to hide fragment App give null error.
How can i solve this problem ?
Thanks in now.
Logcat
01-26 03:48:40.942 2295-2295/test.sy.myapplication E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.NullPointerException
at android.app.BackStackRecord.run(BackStackRecord.java:661)
at android.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1435)
at android.app.FragmentManagerImpl$1.run(FragmentManager.java:441)
at android.os.Handler.handleCallback(Handler.java:730)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5103)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
at dalvik.system.NativeStart.main(Native Method)
LayerList.Java
package test.sy.myapplication;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class LayerList extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View mView = inflater.inflate(R.layout.layerlist,container,false);
return mView;
}
}
MainActivity.Java
package test.sy.myapplication;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
public class MainActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#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.
switch (item.getItemId()) {
case R.id.action_settings:
return true;
case R.id.showsth:
FragmentManager fm = getFragmentManager();
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.setCustomAnimations(android.R.animator.fade_in,
android.R.animator.fade_out);
ft.show(fm.findFragmentById(R.id.fragment));
ft.commit();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
ft.show(fm.findFragmentById(R.id.fragment));
this line causes the problem
fm.findFragmentById(R.id.fragment) returns null.
With this line you are trying to find a fragment in layout/activity_main which is previously added to R.id.fragment.
If you didn't add or replace fragment before, it is obvious to return null AMK
I fix this issue.
This situation caused by adding fragment without any framelayout.
Once add framelayout to main activity. And give it id;
<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=".MainActivity">
<FrameLayout
android:layout_width="200dp"
android:layout_height="450dp"
android:layout_centerVertical="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="false"
android:id="#+id/frameLayout"></FrameLayout>
Second;
Create fragment with its activty. In this example our fragment name may be FragmentTest.java and our Fragments activity may be fragment_activity.xml.
And adding fragment to main activiy;
In Oncreate method you should add this line;
FragmentTest Mfragmenttest = new FragmentTest();
FragmentManager fm = getSupportFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
//R.id.frameLayout is our frame layouts id.
ft.add(R.id.frameLayout, Mfragmenttest , "Hello Fragment");
ft.commit

Categories

Resources