java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.lab02pc19 - android

I know there are many equal to the problems but none of the many who have read is equal to mine or has worked for me for help , so it is going to require your help.
I'm working on an application with a NavigationDrawer , I need to make an image work for me on and off the bluetooth cell .
I made another code separately with an " empty activity" and if I worked, but in the navigariondrawe that is where I need it to work , but it does not work , I 've tried many things , but I hope you can help me .
FATAL EXCEPTION: main
Process: com.example.lab02pc19.myapplication2, PID: 5146
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.lab02pc19.myapplication2/com.example.lab02pc19.myapplication2.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ImageView.setImageResource(int)' 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.-wrap11(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1354)
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.widget.ImageView.setImageResource(int)' on a null object reference
at com.example.lab02pc19.myapplication2.MainActivity.setImagenBluetooth(MainActivity.java:69)
at com.example.lab02pc19.myapplication2.MainActivity.onCreate(MainActivity.java:36)
at android.app.Activity.performCreate(Activity.java:6245)
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.-wrap11(ActivityThread.java) 
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) 
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.lab02pc19.myapplication2">
<uses-permission android:name="android.permission.BLUETOOTH"/>
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity
android:name=".MainActivity"
android:label="#string/app_name"
android:theme="#style/AppTheme.NoActionBar">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
package com.example.lab02pc19.myapplication2;
import android.bluetooth.BluetoothAdapter;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.View;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ImageView;
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener, FragmentBlue.OnFragmentInteractionListener {
ImageView miimagen;
BluetoothAdapter adaptador_bluetooth;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
miimagen= (ImageView)findViewById(R.id.ivw);
adaptador_bluetooth= BluetoothAdapter.getDefaultAdapter();
if(adaptador_bluetooth==null)
{
miimagen.setVisibility(View.GONE);
}
else
{
setImagenBluetooth(adaptador_bluetooth.isEnabled());
}
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 = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
}
public void clickImagen(View view)
{
switch (view.getId())
{
case R.id.ivw:
setEstadoBluetooth();
break;
}
}
public void miimagen()
{
setEstadoBluetooth();
}
public void setImagenBluetooth(boolean valor)
{
if(valor)miimagen.setImageResource(R.drawable.ic_action_bluetooth);
}
public void setEstadoBluetooth()
{
if(adaptador_bluetooth.isEnabled())
{
setImagenBluetooth(false);
adaptador_bluetooth.disable();
}
else
{
setImagenBluetooth(true);
adaptador_bluetooth.enable();
}
}
#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) {
int id = item.getItemId();
boolean FragmenTransaction= false;
Fragment fragment = null;
if (id == R.id.nav_camera) {
fragment = new FragmentBlue();
FragmenTransaction= true;
} else if (id == R.id.nav_gallery) {
} 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) {
}
if(FragmenTransaction)
{
getSupportFragmentManager().beginTransaction().replace(R.id.content_main,fragment).commit();
item.setChecked(true);
getSupportActionBar().setTitle(item.getTitle());
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
#Override
public void onFragmentInteraction(Uri uri) {
}
}
<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.example.lab02pc19.myapplication2.FragmentBlue">
<!-- TODO: Update blank fragment layout -->
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/ivw"
android:layout_gravity="left|top"
android:background="#drawable/ic_action_bluetooth"
android:clickable="true"
android:onClick="clickImagen"
android:contentDescription="#string/imagen" />
</FrameLayout>

As I think (it is not enough info), you want to create a fragment in the activity and make some actions with ImageView further. But you didn't create the fragment and try to find ImageView by id in other layout - thus, the image view didn't exist here, next you try to call function of the null object and finally have a NPE and crash. You need to read tutorial about fragment in Android: https://developer.android.com/training/basics/fragments/index.html

You are trying to access the image view of the fragment in your activity class which is not possible that's why giving null point exception. What you can do it that you can setImage in the image view in you fragment java class in onActivityCreated override method after setting the contentView.
If you want to set the image from the activity only then you can create the public method in the fragment and call the method from the activity.

Related

Android Navigation View click listener not working [duplicate]

This question already has answers here:
NavigationView OnNavigationItemSelectedListener not being called
(3 answers)
Closed 4 years ago.
I created the Activity with the Wizard.
I deleted what I am not interested in, for example, the floating action button.
Created my custom items in the activity_main_drawer.xml
The wizard created the onNavigationItemSelected function (see code below) and I added my code so it quits the activity and goes back to the Login Screen.
So I don't know why, I see nothing interesting in the logcat so this is a logical problem. I am a newbie and Navigation View scares me a lot... Let me know if I missed anything you need.
package com.skrefi.googleplaycopy;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.view.View;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;
import com.google.firebase.auth.FirebaseAuth;
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
private FirebaseAuth firebaseAuth;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
firebaseAuth = FirebaseAuth.getInstance();
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.addDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
}
//Don't know what this is
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
//Don't know what this is either
#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;
}
//In case I need it for the admin activity >> the 3 dots pop down thingy <<
#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.
MakeToast("SOMETHING");
switch (item.getItemId()){
case R.id.action_settings:
MakeToast("Settings button clicked");
return true;
}
return super.onOptionsItemSelected(item);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
switch(item.getItemId()){
case R.id.item_signout:
firebaseAuth.getInstance().signOut();
MakeToast("Signed out!");
finish();
startActivity(new Intent(MainActivity.this, LoginActivity.class));
break;
}
//DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
//drawer.closeDrawer(GravityCompat.START);
return true;
}
public void MakeToast(String text) {
Toast.makeText(this, text, Toast.LENGTH_LONG).show();
}
}
Edit:
So it may be confusing if I set the visibility to gone and I get use the layout I want right in this layout file because I get the screen without the toolbar, this is what I want. AND I want to keep that as well for the admin part, to check later in if the user is me, and if so, I get a new item in the drawer called Admin Activity which simply set the thingy visibility to visible so i get the admin screen.
Here is what you (#) asked for:
<?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_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true">
<!--This is for a potential admin screen-->
<include
android:id="#+id/include_toolbar_with_threedots_settings"
layout="#layout/app_bar_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:visibility="gone" />
<android.support.design.widget.NavigationView
android:id="#+id/nav_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
android:fitsSystemWindows="true"
app:headerLayout="#layout/nav_header_main"
app:menu="#menu/activity_main_drawer" />
<android.support.constraint.ConstraintLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="This is for test"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</android.support.constraint.ConstraintLayout>
</android.support.v4.widget.DrawerLayout>
You're calling finish() before actually starting your activity while you should call it after starting your login activity. The following code will start Login activity and close the Main activity.
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
switch(item.getItemId()){
case R.id.item_signout:
firebaseAuth.getInstance().signOut();
MakeToast("Signed out!");
startActivity(new Intent(MainActivity.this, LoginActivity.class));
finish();
break;
}
//DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
//drawer.closeDrawer(GravityCompat.START);
return true;
}

error implement Tabs using compileSdkVersion 23

I have been flowing this tutorial by android,
https://developer.android.com/training/implementing-navigation/lateral.html
and i cannot add tabs to the action bar,
i get an error saying
Attempt to invoke virtual method 'void android.app.ActionBar.setNavigationMode(int)' on a null object reference
I read somewhere the tabs are not supported anymore,
I have resolved to using the Title Strip instead in the same tutorial wich works, great, but i prefer the tabs,
what am i making wrong ?
here is my fragment activity,
package apps.radwin.wintouch.activities.alignmentActivities;
import android.app.ActionBar;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.NavigationView;
import android.support.design.widget.Snackbar;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.GravityCompat;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import apps.radwin.wintouch.R;
import apps.radwin.wintouch.adapters.aligmentAdapters.SwipeAdapterProjectSelection;
public class projectSelectionMainFragment extends FragmentActivity
implements NavigationView.OnNavigationItemSelectedListener {
ViewPager mainViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.project_selection_main_fragment);
Toolbar toolbar = (Toolbar) findViewById(R.id.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();
}
});
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 = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
/////////////////////////////////////////
//////// Start Of Implementation ////////
/////////////////////////////////////////
mainViewPager = (ViewPager) findViewById(R.id.projectSelectionMainViewPager); // the main view pager
SwipeAdapterProjectSelection swipeAdapter = new SwipeAdapterProjectSelection(getSupportFragmentManager()); // calls the adapter and initlizes it
mainViewPager.setAdapter(swipeAdapter); // sets the adapter
///////////////////////////////////////////
/////start of action bar implementation////
///////////////////////////////////////////
final ActionBar actionBar = getActionBar();
// Specify that tabs should be displayed in the action bar.
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
// Create a tab listener that is called when the user changes tabs.
ActionBar.TabListener tabListener = new ActionBar.TabListener() {
#Override
public void onTabSelected(ActionBar.Tab tab, FragmentTransaction ft) {
}
public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction ft) {
// hide the given tab
}
public void onTabReselected(ActionBar.Tab tab, FragmentTransaction ft) {
// probably ignore this event
}
};
// Add 3 tabs, specifying the tab's text and TabListener
for (int i = 0; i < 3; i++) {
actionBar.addTab(
actionBar.newTab()
.setText("Tab " + (i + 1))
.setTabListener(tabListener));
}
}
#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.project_selection_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) {
// Handle the camera action
} else if (id == R.id.nav_gallery) {
} 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;
}
}
error log:
Process: apps.radwin.wintouch, PID: 32161
java.lang.RuntimeException: Unable to start activity ComponentInfo{apps.radwin.wintouch/apps.radwin.wintouch.activities.alignmentActivities.projectSelectionMainFragment}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.app.ActionBar.setNavigationMode(int)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3253)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3349)
at android.app.ActivityThread.access$1100(ActivityThread.java:221)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1794)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:158)
at android.app.ActivityThread.main(ActivityThread.java:7224)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.app.ActionBar.setNavigationMode(int)' on a null object reference
at apps.radwin.wintouch.activities.alignmentActivities.projectSelectionMainFragment.onCreate(projectSelectionMainFragment.java:74)
at android.app.Activity.performCreate(Activity.java:6876)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1135)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3206)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3349) 
at android.app.ActivityThread.access$1100(ActivityThread.java:221) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1794) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:158) 
at android.app.ActivityThread.main(ActivityThread.java:7224) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120) 
build gradle:
apply plugin: 'com.android.application'
android {
compileSdkVersion 23
buildToolsVersion "23.0.3"
defaultConfig {
applicationId "apps.radwin.wintouch"
minSdkVersion 19
targetSdkVersion 23
versionCode 21
versionName "1.0"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
repositories {
jcenter()
}
dependencies {
compile fileTree(include: ['*.jar'], dir: 'libs')
testCompile 'junit:junit:4.12'
compile files('libs/core.jar')
provided 'org.glassfish:javax.annotation:10.0-b28'
compile 'com.android.support:appcompat-v7:23.4.0'
compile 'com.android.support:design:23.4.0'
compile 'com.google.android.gms:play-services-appindexing:8.4.0'
compile 'com.github.ybq:Android-SpinKit:1.0.4'
compile 'com.squareup.retrofit2:retrofit:2.0.1'
compile 'com.squareup.retrofit2:converter-gson:2.0.1'
compile 'com.michaelpardo:activeandroid:3.1.0-SNAPSHOT'
compile 'com.rengwuxian.materialedittext:library:2.1.4'
compile 'com.github.fenjuly:ArrowDownloadButton:9e15b85e8a'
compile 'com.oguzdev:CircularFloatingActionMenu:1.0.2'
compile 'com.yayandroid:LocationManager:1.1.1'
compile 'com.google.android.gms:play-services-location:7.5.0'
compile 'com.github.quentin7b:android-location-tracker:3.2'
compile 'com.github.lzyzsd:circleprogress:1.1.0#aar'
compile 'com.android.support:support-v4:23.4.0'
compile 'com.astuetz:pagerslidingtabstrip:1.0.1'
}
After
final ActionBar actionBar = getActionBar();
set
setSupportActionBar(actionBar);
EDIT: yea i miss
setSupportActionBar(toolbar);
after u initialize toolbar
First set Toolbar as action bar
setSupportActionBar(toolbar);
Instead of
final ActionBar actionBar = getActionBar();
Please use
final ActionBar actionBar = getSupportActionBar();
Also make sure intheme/style that you have mentioned
windowActionBar as true or in activity
getWindow().requestFeature(Window.FEATURE_ACTION_BAR);
You should extend AppCompatActivity instead of extending FragmentActivity because AppCompatActivity inherits from FragmentActivity and you need to set your Toolbar as your ActionBar. also make sure your base themes parent is AppCompat.Light.NoActionBar something like this
<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
and include
setSupportActionBar(toolbar);
after
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
and get reference with getSupportActionBar(); not getActionBar();
Answered, by removing the old Action bar Implementation and inserting the new
Tabllayout implementation as stated by android,
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabsLayoutWorkorderSelection);
tabLayout.setupWithViewPager(mainViewPager);
as it is implemented in the new tabbed activity you can do when you open a new Activity in Android.
in that case the Class can extends AppCompatActivity instead of FragmentActivity.

NullPointerException When starting new Activity in Navigation Drawer

I am using a template navigation drawer that was provided by android studio. I am very new to android development so i'm wondering if i'm missing something simple here. I want to start a new activity by clicking on an item in my navigation menu I followed several tutorials on how to do this but i keep getting this error in my logcat:
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.bsmyth.sidemenu/com.example.bsmyth.sidemenu.second_activity}: java.lang.NullPointerException
Here is the code I tried to start a new activity:
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_camera) {
// Handle the camera action
}
else if (id == R.id.nav_gallery) {
Intent intent = new Intent(MainActivity.this, second_activity.class);
startActivity(intent);
}
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;
}
}
I referred to my second activity in my manifest file like this:
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity
android:name=".MainActivity"
android:label="#string/app_name"
android:theme="#style/AppTheme.NoActionBar">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".second_activity">
<intent-filter>
<action android:name="com.example.bsmyth.sidemenu.second_activity" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
</application>
Here is the drawer layout:
<group android:checkableBehavior="single">
<item
android:id="#+id/nav_camera"
android:icon="#drawable/ic_menu_camera"
android:title="Adfeed"
android:checked="true"/>
<item
android:id="#+id/nav_gallery"
android:icon="#drawable/ic_menu_gallery"
android:title="Post" />
<item
android:id="#+id/nav_slideshow"
android:icon="#drawable/ic_menu_slideshow"
android:title="Notification" />
<item
android:id="#+id/nav_manage"
android:icon="#drawable/ic_menu_send"
android:title="Messages" />
</group>
Here is the second activity:
package com.example.bsmyth.sidemenu;
import android.app.ActionBar;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.view.View;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
public class second_activity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.second_activity);
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 = (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) {
// Handle the camera action
} else if (id == R.id.nav_gallery) {
} 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;
}
}
Here is second_activity layout:
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:android="http://schemas.android.com/apk/res/android">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Your in the second activity"
android:textSize="20sp"/>
</android.support.v4.widget.DrawerLayout>
And here are the error messages in logcat:
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.bsmyth.sidemenu/com.example.bsmyth.sidemenu.second_activity}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2059)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2084)
at android.app.ActivityThread.access$600(ActivityThread.java:130)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1195)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4745)
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:786)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at com.example.bsmyth.sidemenu.second_activity.onCreate(second_activity.java:30)
at android.app.Activity.performCreate(Activity.java:5008)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1079)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2023)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2084) 
at android.app.ActivityThread.access$600(ActivityThread.java:130) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1195) 
at android.os.Handler.dispatchMessage(Handler.java:99) 
at android.os.Looper.loop(Looper.java:137) 
at android.app.ActivityThread.main(ActivityThread.java:4745) 
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:786) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553) 
at dalvik.system.NativeStart.main(Native Method) 
Your second activity layout has only a DrawerLayout and one TextView it does not have the views that you are calling in onCreate method.
Try running it again after removing this views from your onCreate:
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
add this:
android:id="#+id/drawer_layout"
to your DrawerLayout.
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/drawer_layout"
>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Your in the second activity"
android:textSize="20sp"/>
</android.support.v4.widget.DrawerLayout>
Use a little common sense on these, you are using findViewById for drawer_layout, toolbar as well as nav_view and other extras too.
But there is nothing in second_activity layout except one TextView even that is without any id. Then how can these codes work ?
Create these elements like shown in new android project in android studio then follow the same pattern and see how the next layout is included there.
Your will get multiple NullPointerException in your code. You only copied the code of MainActivity.java to second_activity.java but not in the layout file from activity_main to second_activity.
You can create your second activity in project explorer and selecting the activity you want from the template. It is the easiest way and also very good way. After that you can simply call the second activity from first activity like you are doing now
You are doing many things wrong in second activity code....
In layout XML..you don't give any id for drawer layout which you are using (drawer_layout).
So Add this...
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/drawer_layout">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Your in the second activity"
android:textSize="20sp"/>
</android.support.v4.widget.DrawerLayout>
Also create this view toolbar and nav_view in this XML file like you have create Textview in second_activity XML .
And create Drawer object only once with same drwaer id(drawer_layout).
Like...
//declare this globally(means out of any method)
DrawerLayout drawer;
and then initialize this in onCreate method...
drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
and at last remove this line DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); from onBackPressed() and onNavigationItemSelected method.
Hope this will help you...

issue with replacing Fragment views in Navigation drawer

I am using the android Navigation drawer template and fragments to display different views.
as the normal there is a MainActivity, activity_main.xml and content_main.xml generated automatically.
I have created two java classes; MusicFragment and MainFragment and of course the layout files which I have content inside.
When I run the app the activity_main is the default layout launched which I have welcome content displaying, I am using the Navigation drawer to navigate to my MusicFragment and MainFragment, this code I using to replace the current view in the onNavigationItemSelected method is;
if (id == R.id.nav_camara) {
fm.beginTransaction().replace(R.id.content_frame, new MainFragment()).commit();
} else if (id == R.id.nav_gallery) {
fm.beginTransaction().replace(R.id.content_frame, new MusicFragment()).commit();
these both work fine with replacing each other although I have a big problem, when I select the nav drawer and hit the camera option it shows the fragment view but does not replace the content from activity_main it shows the fragment content on top of the content_main and doesn't replace it.
This is my MainActivity:
package com.justmikey.justmik;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v4.app.FragmentManager;
import android.support.v7.internal.widget.ButtonBarLayout;
import android.text.method.ScrollingMovementMethod;
import android.view.View;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Button;
import android.widget.TextView;
import JustMikey.Fragments.MainFragment;
import JustMikey.Fragments.MusicFragment;
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
//create a media player object called mp
MediaPlayer mp;
//declare my buttons play, pause and stop
Button play, pause,stop;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Set the textView scrollMain to scrollable
TextView tv = (TextView) findViewById(R.id.scrollMain);
tv.setMovementMethod(new ScrollingMovementMethod());
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 = (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) {
android.app.FragmentManager fm = getFragmentManager();
int id = item.getItemId();
if (id == R.id.nav_camara) {
fm.beginTransaction().replace(R.id.content_frame, new MainFragment()).commit();
} else if (id == R.id.nav_gallery) {
fm.beginTransaction().replace(R.id.content_frame, new MusicFragment()).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;
}
}
content_main.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"
xmlns:app="http://schemas.android.com/apk/res-auto" 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"
app:layout_behavior="#string/appbar_scrolling_view_behavior" tools:showIn="#layout/app_bar_main"
tools:context=".MainActivity"
android:background="#dbe4eb">
<FrameLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="#+id/content_frame">
<ImageView
android:layout_width="355dp"
android:layout_height="wrap_content"
android:src="#drawable/jmmain"
android:id="#+id/imageView2"
android:layout_gravity="center_horizontal|top"
android:layout_alignRight="#+id/content_frame"
android:layout_alignEnd="#+id/content_frame" />
<TextView
android:layout_width="fill_parent"
android:layout_height="274dp"
android:text="hello hello hello hello hello hello hello hello"
android:id="#+id/scrollMain"
android:layout_gravity="center_horizontal|bottom"
android:layout_alignBottom="#+id/scrollView"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginBottom="28dp"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:background="#ffffff"
android:padding="10dp"
/>
<ScrollView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="#+id/scrollView"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_gravity="center">
</ScrollView>
</FrameLayout>
</RelativeLayout>
FragmentTransactions only handle Fragments. They will not replace/remove anything not in a Fragment. Since those Views contained in the content_frame FrameLayout are only needed at startup, we can simply remove them upon the first FragmentTransaction.
To do this, we'll create a member boolean flag, isStartup, initialized to true. In the onNavigationItemSelected() method, we'll check the flag, and if it's true, remove the Views and change it to false.
Declare and initialize the boolean outside of any method:
private boolean isStartup = true;
Then do the check and removal in the onNavigationItemSelected() method.
public boolean onNavigationItemSelected(MenuItem item) {
android.app.FragmentManager fm = getFragmentManager();
int id = item.getItemId();
if(isStartup) {
((FrameLayout) findViewById(R.id.content_frame)).removeAllViews();
isStartup = false;
}
if (id == R.id.nav_camara) {
...
}
I had the same problem.
I could not solve my problem with the said solutions. But i found two solutions to solve it!
1- You can present the content of the main page into an other view group. and hide it in onNavigationItemSelected, in the right place:
content_main.xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#dbe4eb"
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=".MainActivity"
tools:showIn="#layout/app_bar_main">
<FrameLayout
android:id="#+id/content_frame"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<LinearLayout
android:id="#+id/my_linearLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<ImageView
android:id="#+id/imageView2"
android:layout_width="355dp"
android:layout_height="wrap_content"
android:layout_alignEnd="#+id/content_frame"
android:layout_alignRight="#+id/content_frame"
android:layout_gravity="center_horizontal|top"
android:src="#drawable/jmmain" />
<TextView
android:id="#+id/scrollMain"
android:layout_width="fill_parent"
android:layout_height="274dp"
android:layout_alignBottom="#+id/scrollView"
android:layout_alignParentEnd="true"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_alignParentStart="true"
android:layout_gravity="center_horizontal|bottom"
android:layout_marginBottom="28dp"
android:background="#ffffff"
android:padding="10dp"
android:text="hello hello hello hello hello hello hello hello" />
<ScrollView
android:id="#+id/scrollView"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_gravity="center"></ScrollView>
</LinearLayout>
</RelativeLayout>
onNavigationItemSelected method in MainActivity.java:
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.main) {
findViewById(R.id.my_linearLayout).setVisibility(View.VISIBLE);
fragmentManager.popBackStack("fragment", POP_BACK_STACK_INCLUSIVE);
} else if (id == R.id.one) {
findViewById(R.id.my_linearLayout).setVisibility(View.GONE);
fragmentManager.beginTransaction().replace(R.id.content_frame, new OneFragment()).addToBackStack("fragment").commit();
} else if (id == R.id.tow) {
findViewById(R.id.my_linearLayout).setVisibility(View.GONE);
fragmentManager.beginTransaction().replace(R.id.content_frame, new SecondFragment()).addToBackStack("fragment").commit();
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
2- The second way is to consider a fragment for the contents of the main page as well. and then in the onNavigationItemSelected method, we treat it Like the rest of the fragments:
onNavigationItemSelected method in MainActivity.java:
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.main) {
fragmentManager.beginTransaction().replace(R.id.content_frame, new HomeFragment()).addToBackStack("fragment").commit();
} else if (id == R.id.one) {
fragmentManager.beginTransaction().replace(R.id.content_frame, new OneFragment()).addToBackStack("fragment").commit();
} else if (id == R.id.tow) {
fragmentManager.beginTransaction().replace(R.id.content_frame, new SecondFragment()).addToBackStack("fragment").commit();
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
note: To display the contents of the main page when opening the program enter the following code in onCreate() in MainActivity:
fragmentManager.beginTransaction().replace(R.id.content_frame, new HomeFragment()).addToBackStack("fragment").commit();

Android Studio: Adding Action Bar Item with "onClick" encounters "FATAL EXCEPTION"

So I'm starting to work on my first Android App and I've already hit a wall. I want to start off with a "Create" button at the action menu at the top that has the ability to create new contacts. But then I hit some sort of error I can't understand and it's been hindering my process.
The error started when I added the "onClick" line tot he action item and since then, stopped running on my emulator.
Thank you.
MainActivity.java
package com.xephos.detra;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
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.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public void create(View v){
TextView tv = (TextView) findViewById(R.id.test);
tv.setText("Working!");
}
}
This might help: the menu_main.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=".MainActivity">
<item android:id="#+id/action_settings" android:title="#string/action_settings"
android:orderInCategory="100" app:showAsAction="never" />
<item
android:id="#+id/add"
android:title="Add New Contact"
app:showAsAction ="always"
android:icon="#drawable/ic_add_white_48dp"
android:onClick="create"/>
</menu>
And finally, the error:
20653-20653/com.xephos.detra E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.xephos.detra, PID: 20653
android.view.InflateException: Couldn't resolve menu item onClick handler create in class com.xephos.detra.MainActivity
at android.support.v7.internal.view.SupportMenuInflater$InflatedOnMenuItemClickListener.<init>(SupportMenuInflater.java:242)
at android.support.v7.internal.view.SupportMenuInflater$MenuState.setItem(SupportMenuInflater.java:443)
at android.support.v7.internal.view.SupportMenuInflater$MenuState.addItem(SupportMenuInflater.java:479)
at android.support.v7.internal.view.SupportMenuInflater.parseMenu(SupportMenuInflater.java:196)
at android.support.v7.internal.view.SupportMenuInflater.inflate(SupportMenuInflater.java:118)
at com.xephos.detra.MainActivity.onCreateOptionsMenu(MainActivity.java:22)
at android.app.Activity.onCreatePanelMenu(Activity.java:2823)
at android.support.v4.app.FragmentActivity.onCreatePanelMenu(FragmentActivity.java:277)
at android.support.v7.internal.view.WindowCallbackWrapper.onCreatePanelMenu(WindowCallbackWrapper.java:84)
at android.support.v7.app.AppCompatDelegateImplBase$AppCompatWindowCallbackBase.onCreatePanelMenu(AppCompatDelegateImplBase.java:275)
at android.support.v7.app.AppCompatDelegateImplV7.preparePanel(AppCompatDelegateImplV7.java:1117)
at android.support.v7.app.AppCompatDelegateImplV7.doInvalidatePanelMenu(AppCompatDelegateImplV7.java:1399)
at android.support.v7.app.AppCompatDelegateImplV7.access$100(AppCompatDelegateImplV7.java:89)
at android.support.v7.app.AppCompatDelegateImplV7$1.run(AppCompatDelegateImplV7.java:126)
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:5257)
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.NoSuchMethodException: create [interface android.view.MenuItem]
at java.lang.Class.getMethod(Class.java:664)
at java.lang.Class.getMethod(Class.java:643)
at android.support.v7.internal.view.SupportMenuInflater$InflatedOnMenuItemClickListener.<init>(SupportMenuInflater.java:240) ...
            
You create method needs to take a MenuItem as the argument, not a View.
public void create(MenuItem item){
TextView tv = (TextView) findViewById(R.id.test);
tv.setText("Working!");
}
Alternatively, remove the android:onClick attribute of your menu item and handle the click in onOptionsItemSelected() by checking the id of the item:
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.add:
// your code here
return true;
case R.id.action_settings:
// copied from auto-generated stub
return true;
}
return super.onOptionsItemSelected(item);
}
Either will work, my preference is the second approach.
You'd be better off doing it programmatically. Get rid of the 'android:OnClick' line in the XML, then after you set the text of 'tv' put in this:
tv.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Process click here
});
This should do the trick!

Categories

Resources