I have created a drawer menu in android studio and changed items of drawer. I want to start another activity or view another layout on item click. but i get the following error and application is stopped.
03-24 21:38:28.202 2227-10289/? D/GassUtils: Found app info for package com.example.imran.myapp:1. Hash: 6b9333e031907d7a6a6c12cd9fdfa0d23bd13ee0f40c9617ddd005dc358321b0
03-24 21:38:28.202 2227-10289/? D/k: Found info for package com.example.imran.myapp in db.
03-24 21:38:38.722 1035-1167/? V/ApplicationPolicy: isApplicationStateBlocked userId 0 pkgname com.example.imran.myapp
03-24 21:38:38.782 9789-9789/? I/Timeline: Timeline: Activity_launch_request id:com.example.imran.myapp time:121627337
03-24 21:38:38.802 1035-1853/? W/ActivityManager: NORMAL SET : srcAppInfo.processName = com.example.imran.myapp, destAppInfo.processName = com.example.imran.myapp
03-24 21:38:38.802 1035-1853/? W/ActivityManager: startActivity called from finishing ActivityRecord{28b176ac u0 com.example.imran.myapp/.MainActivity t2394 f}; forcing Intent.FLAG_ACTIVITY_NEW_TASK for: Intent { cmp=com.example.imran.myapp/.Home (has extras) }
03-24 21:38:38.802 1035-1853/? V/ApplicationPolicy: isApplicationStateBlocked userId 0 pkgname com.example.imran.myapp
03-24 21:38:39.402 1035-1532/? I/WindowManager: Switching to real app window: Window{11c67d3b u0 com.example.imran.myapp/com.example.imran.myapp.Home}
03-24 21:38:39.622 1035-1069/? I/Timeline: Timeline: Activity_windows_visible id: ActivityRecord{dca1b0 u0 com.example.imran.myapp/.Home t2396} time:121628177
03-24 21:38:58.462 9789-9789/? E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.imran.myapp, PID: 9789
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.v4.widget.DrawerLayout.closeDrawer(int)' on a null object reference
at com.example.imran.myapp.Home.onNavigationItemSelected(Home.java:120)
at android.support.design.widget.NavigationView$1.onMenuItemSelected(NavigationView.java:146)
at android.support.v7.internal.view.menu.MenuBuilder.dispatchMenuItemSelected(MenuBuilder.java:811)
at android.support.v7.internal.view.menu.SubMenuBuilder.dispatchMenuItemSelected(SubMenuBuilder.java:84)
at android.support.v7.internal.view.menu.MenuItemImpl.invoke(MenuItemImpl.java:153)
at android.support.v7.internal.view.menu.MenuBuilder.performItemAction(MenuBuilder.java:958)
at android.support.design.internal.NavigationMenuPresenter.onItemClick(NavigationMenuPresenter.java:196)
at android.widget.AdapterView.performItemClick(AdapterView.java:334)
at android.widget.AbsListView.performItemClick(AbsListView.java:1536)
at android.widget.AbsListView$PerformClick.run(AbsListView.java:3683)
at android.widget.AbsListView$3.run(AbsListView.java:5604)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:145)
at android.app.ActivityThread.main(ActivityThread.java:6145)
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)
03-24 21:38:58.462 1035-1514/? V/ApplicationPolicy: isApplicationStateBlocked userId 0 pkgname com.example.imran.myapp
03-24 21:38:58.462 1035-1514/? W/ActivityManager: Force finishing activity com.example.imran.myapp/.Home
03-24 21:38:58.462 1035-1514/? V/ApplicationPolicy: isApplicationStateBlocked userId 0 pkgname com.example.imran.myapp
03-24 21:38:58.542 1035-1035/? D/CrashAnrDetector: processName: com.example.imran.myapp
03-24 21:38:58.542 1035-1035/? D/CrashAnrDetector: broadcastEvent : com.example.imran.myapp data_app_crash
03-24 21:38:58.992 1035-1062/? W/ActivityManager: Activity pause timeout for ActivityRecord{dca1b0 u0 com.example.imran.myapp/.Home t2396 f}
Java files:
Home.java
package com.example.imran.myapp;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
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.Button;
import android.widget.TextView;
public class Home extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
Button logout = (Button) findViewById(R.id.logout_button);
TextView text1 = (TextView) findViewById(R.id.result_sms);
final UserLocalStore loginuser = new UserLocalStore(getApplicationContext());
SharedPreferences mPrefs = getSharedPreferences("userDetails",0);
String str1=(mPrefs.getString("fullname","Default_Value"));
String email = loginuser.getLoggedInUser().email;
text1.setText("Welcome "+str1+"- Your email: "+email);
logout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
loginuser.clearUserData();
//startActivity(new Intent(getApplicationContext(), MainActivity.class));
finish();
startActivity(new Intent(getApplicationContext(), MainActivity.class));
//setContentView(R.layout.activity_main);
}
});
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.home, 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_photos) {
// Handle the camera action
//setContentView(R.layout.myaccount);
} else if (id == R.id.nav_myaccount) {
setContentView(R.layout.activity_myaccount2);
//
} else if (id == R.id.nav_logout) {
UserLocalStore loginuser = new UserLocalStore(this);
loginuser.clearUserData();
finish();
startActivity(new Intent(getApplicationContext(), MainActivity.class));
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
}
In the last part of home.java when i add setContentView(R.layout.activity_myaccount2);
then the app crashes.
The problem here is a Null Pointer Exception when calling drawer.closeDrawer(); and as you've stated this happens after setContentView(R.layout.activity_myaccount2); is called.
By using setContentView, you're replacing your whole layout with another one, and it seems in this case like you're replacing your layout that contains R.id.drawer_layout with another one that doesn't contain it. The null pointer exception then happens when you try to use findViewById and closeDrawer, when the layout containing the drawer isn't there anymore, it's been replaced with another using setContentView.
To fix this you may need to rethink how you are structuring your app and displaying different content. As a starting point, I'd suggest looking up examples using an Activity which contains your drawer and Fragments to show the different pieces of content. The Activity and drawer are always there, only the fragments change, like this tutorial.
Related
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 3 years ago.
Everything works fine in my app but when I press the back button (I mean exit app) the app is crashing. And I don't know why? I tried a couple of solutions but nothing works. It's a sounds/ringtones application.
I am a newbie at Android and I need some advice like "delete this" / "add this"
Here my code
package com.app.trying;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Environment;
import android.support.design.widget.NavigationView;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.MenuItem;
import android.widget.Toast;
import com.app.trying.tabs.Tab3;
import com.app.trying.tabs.Tab1;
import com.app.trying.tabs.Tab2;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdView;
import java.io.File;
public class MainActivity extends AppCompatActivity {
public MediaPlayer mp;
DrawerLayout mDrawerLayout;
NavigationView mNavigationView;
FragmentManager mFragmentManager;
FragmentTransaction mFragmentTransaction;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Banner Ad
AdView mAdView = (AdView) findViewById(R.id.adView);
AdRequest adRequest = new AdRequest.Builder().build();
mAdView.loadAd(adRequest);
toolbarTabs();
sidebar();
externalStorageAccess();
}
// Creates sidebar and sets onClickListeners
public void sidebar(){
mNavigationView = (NavigationView) findViewById(R.id.navigationView);
mNavigationView.setItemIconTintList(null);
mNavigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
mDrawerLayout.closeDrawers();
switch (menuItem.getItemId()){
case R.id.sounds:
FragmentTransaction xfragmentTransaction = mFragmentManager.beginTransaction();
xfragmentTransaction.replace(R.id.containerView,new TabFragment()).commit();
break;
case R.id.share:
Intent shareIntent = new Intent(Intent.ACTION_SEND);
shareIntent.setType("text/plain");
shareIntent.putExtra(Intent.EXTRA_SUBJECT, getText(R.string.app_name));
shareIntent.putExtra(Intent.EXTRA_TEXT, getText(R.string.share_text) + " " + getText(R.string.app_name) + "\n\n" + getText(R.string.playstore_link));
startActivity(Intent.createChooser(shareIntent, getText(R.string.share_via)));
break;
}
return false;
}
});
}
// Is listening which sound on Tab1 has been clicked
public void TabOneItemClicked(int position) {
cleanUpMediaPlayer();
mp=MediaPlayer.create(MainActivity.this, Tab1.soundfiles[position]);
mp.start();
}
// Is listening which sound on Tab2 has been clicked
public void TabTwoItemClicked(int position) {
cleanUpMediaPlayer();
mp=MediaPlayer.create(MainActivity.this, Tab2.soundfiles[position]);
mp.start();
}
// Is listening which sound on Tab3 has been clicked
public void TabThreeItemClicked ( int position){
cleanUpMediaPlayer();
mp=MediaPlayer.create(MainActivity.this, Tab3.soundfiles[position]);
mp.start();
}
// Cleans MediaPlayer
public void cleanUpMediaPlayer() {
if (mp != null) {
try {
mp.stop();
mp.release();
mp = null;
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(MainActivity.this, "Error", Toast.LENGTH_LONG).show();
}
}
}
// Access external storage
public void externalStorageAccess(){
final File FILES_PATH = new File(Environment.getExternalStorageDirectory(), "Android/data/"+ getText(R.string.package_name) +"/files");
if (Environment.MEDIA_MOUNTED.equals(
Environment.getExternalStorageState())) {
if (!FILES_PATH.mkdirs()) {
Log.w("error", "Could not create " + FILES_PATH);
}
} else {
Toast.makeText(MainActivity.this, "Error", Toast.LENGTH_LONG).show();
finish();
}
}
// Creates toolbar Tabs
public void toolbarTabs(){
mFragmentManager = getSupportFragmentManager();
mFragmentTransaction = mFragmentManager.beginTransaction();
mFragmentTransaction.replace(R.id.containerView, new TabFragment()).commit();
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawerLayout);
android.support.v7.widget.Toolbar toolbar = (android.support.v7.widget.Toolbar) findViewById(R.id.toolbar);
ActionBarDrawerToggle mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, toolbar, R.string.app_name,
R.string.app_name);
mDrawerLayout.setDrawerListener(mDrawerToggle);
mDrawerToggle.syncState();
}
#Override
protected void onPause() {
super.onPause();
stopMediaPlayer();
}
public void stopMediaPlayer()
{
mp.stop();
}
}
And this is my error logs.
2019-05-09 19:13:22.296 704-704/? E/cnss-daemon: Invalid mac address: 0x555555f110M
2019-05-09 19:13:32.682 704-704/? E/cnss-daemon: Stale or unreachable neighbors, ndm state: 4
2019-05-09 19:13:39.537 443-2253/? E/ANDR-PERF-MPCTL: Invalid profile no. 0, total profiles 0 only
2019-05-09 19:13:40.333 24095-24175/? E/libEGL: validate_display:99 error 3008 (EGL_BAD_DISPLAY)
2019-05-09 19:13:43.035 443-2253/? E/ANDR-PERF-MPCTL: Invalid profile no. 0, total profiles 0 only
2019-05-09 19:13:43.116 24095-24095/? E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.app.trying, PID: 24095
java.lang.RuntimeException: Unable to pause activity {com.app.trying/com.app.trying.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.media.MediaPlayer.stop()' on a null object reference
at android.app.ActivityThread.performPauseActivityIfNeeded(ActivityThread.java:3735)
at android.app.ActivityThread.performPauseActivity(ActivityThread.java:3701)
at android.app.ActivityThread.performPauseActivity(ActivityThread.java:3675)
at android.app.ActivityThread.handlePauseActivity(ActivityThread.java:3649)
at android.app.ActivityThread.-wrap16(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1487)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6111)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.media.MediaPlayer.stop()' on a null object reference
at com.app.trying.MainActivity.stopMediaPlayer(MainActivity.java:155)
at com.app.trying.MainActivity.onPause(MainActivity.java:150)
at android.app.Activity.performPause(Activity.java:6917)
at android.app.Instrumentation.callActivityOnPause(Instrumentation.java:1323)
at android.app.ActivityThread.performPauseActivityIfNeeded(ActivityThread.java:3724)
at android.app.ActivityThread.performPauseActivity(ActivityThread.java:3701)
at android.app.ActivityThread.performPauseActivity(ActivityThread.java:3675)
at android.app.ActivityThread.handlePauseActivity(ActivityThread.java:3649)
at android.app.ActivityThread.-wrap16(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1487)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6111)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
2019-05-09 19:13:43.736 2484-2484/? E/Launcher3: Meminfo, NativeHeapAllocatedSize18887424
2019-05-09 19:13:43.736 2484-2484/? E/Launcher3: Meminfo, NativeHeapSize35651584
2019-05-09 19:13:43.736 2484-2484/? E/Launcher3: Meminfo, getNativeHeapFreeSize16764160
2019-05-09 19:13:51.682 704-704/? E/cnss-daemon: Stale or unreachable neighbors, ndm state: 4
How should I resolve this error? Any help would be great. Thanks.
Your MediaPlayer instance is null as shown in the stacktrace, so:
public void stopMediaPlayer()
{
if (mp != null) {
mp.stop();
}
}
It can happen that your MediaPlayer instance is never initialization. So you have to handle it.
I'm new in android development and I'm trying to build a kind of book listing kind of app for a project in my class. The prof's favorite motto is "whatever you don't know google it". That's not bad when you semi-know what to do but since we are learning java along with android development that's not helpful since java can seem a bit alien.
Anyways basing my app in a contact app this is how my MainActivity looks
//MainActivity.java
package com.iekproject.siegfried.libraryapp;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
public class MainActivity extends AppCompatActivity
implements LibraryFragment.LibraryFragmentListener, DetailFragment.DetailFragmentListener,
AddEditFragment.AddEditFragmentListener {
//key for storing a book's Uri in a Bundle passed to a fragment
public static final String BOOK_URI = "book_uri";
private LibraryFragment libraryFragment; //displays library aka book list
//displays LibraryFragment when MainActivity first loads
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
//if layout contains fragmentContainer, the phone layout is in use. Create and display
//a LibraryFragment
if (savedInstanceState == null && findViewById(R.id.fragmentContainer) != null) {
//create LibraryFragment
libraryFragment = new LibraryFragment();
//add the fragment to the FrameLayout
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.add(R.id.fragmentContainer, libraryFragment);
transaction.commit(); //displays LibraryFragment
}
else {
libraryFragment =
(LibraryFragment) getSupportFragmentManager().
findFragmentById(R.id.DetailFragment);
}
}
public boolean isExternalStorageReadable() {
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state) ||
Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
return true;
}
return false;
}
//displays DetailFragment for selected book
#Override
public void onBookSelected(Uri bookUri) {
getSupportFragmentManager().popBackStack();
displayBook(bookUri, R.id.rightPaneContainer);
}
//displays AddEditFragment to add a new book. Possibly what I'll also have to change to make it
//scan/update the book list
#Override
public void onAddBook() {
displayAddEditFragment(R.id.rightPaneContainer, null);
}
//displays a book
private void displayBook(Uri bookUri, int viewID) {
DetailFragment detailFragment = new DetailFragment();
//specify book's Uri as an argument to the DetailFragment
Bundle arguments = new Bundle();
arguments.putParcelable(BOOK_URI, bookUri);
detailFragment.setArguments(arguments);
//use a FragmentTransaction to display the DetailFragment
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(viewID, detailFragment);
transaction.addToBackStack(null);
transaction.commit(); //causes DetailFragment to display
}
//displays fragment for adding new or editing existing book
private void displayAddEditFragment(int viewID, Uri bookUri) {
AddEditFragment addEditFragment = new AddEditFragment();
//if editing existing book, provide bookUri as an argument
if (bookUri != null) {
Bundle arguments = new Bundle();
arguments.putParcelable(BOOK_URI, bookUri);
addEditFragment.setArguments(arguments);
}
//use a FragmentTransaction to display the AddEditFragment
FragmentTransaction transaction =
getSupportFragmentManager().beginTransaction();
transaction.replace(viewID, addEditFragment);
transaction.addToBackStack(null);
transaction.commit(); //causes AddEditFragment to display
}
//return to book list when displayed book deleted
#Override
public void onBookDeleted() {
//removes top of back stack
getSupportFragmentManager().popBackStack();
libraryFragment.updateLibrary(); //refresh book list
}
//displays the AddEditFragment to edit an existing book. Maybe it can be used as Move or sth
/*#Override
public void onEditBook(Uri bookUri) {
displayAddEditFragment(R.id.rightPaneContainer, bookUri);
}*/
//update GUI after the new book or updated book saved
#Override
public void onAddEditCompleted(Uri bookUri) {
//removes top of back stack
getSupportFragmentManager().popBackStack();
libraryFragment.updateLibrary(); //refresh book list
if (findViewById(R.id.fragmentContainer) == null){ //tablet
//removes top of back stack
getSupportFragmentManager().popBackStack();
//on tablet, displays the book that was just added or edited
displayBook(bookUri, R.id.rightPaneContainer);
}
}
}
and this is the logcat
04-12 16:14:38.807 5796-5796/? I/art: Not late-enabling -Xcheck:jni (already on)
04-12 16:14:38.808 5796-5796/? W/art: Unexpected CPU variant for X86 using defaults: x86
04-12 16:14:38.926 5796-5796/com.iekproject.siegfried.libraryapp W/System: ClassLoader referenced unknown path: /data/app/com.iekproject.siegfried.libraryapp-1/lib/x86
04-12 16:14:38.945 5796-5796/com.iekproject.siegfried.libraryapp I/InstantRun: starting instant run server: is main process
04-12 16:14:38.991 5796-5796/com.iekproject.siegfried.libraryapp W/art: Before Android 4.1, method android.graphics.PorterDuffColorFilter android.support.graphics.drawable.VectorDrawableCompat.updateTintFilter(android.graphics.PorterDuffColorFilter, android.content.res.ColorStateList, android.graphics.PorterDuff$Mode) would have incorrectly overridden the package-private method in android.graphics.drawable.Drawable
04-12 16:14:39.119 5796-5796/com.iekproject.siegfried.libraryapp D/AndroidRuntime: Shutting down VM
04-12 16:14:39.119 5796-5796/com.iekproject.siegfried.libraryapp E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.iekproject.siegfried.libraryapp, PID: 5796
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.iekproject.siegfried.libraryapp/com.iekproject.siegfried.libraryapp.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:2665)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2726)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1477)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6119)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
Caused by: java.lang.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.AppCompatDelegateImplV9.setSupportActionBar(AppCompatDelegateImplV9.java:207)
at android.support.v7.app.AppCompatActivity.setSupportActionBar(AppCompatActivity.java:130)
at com.iekproject.siegfried.libraryapp.MainActivity.onCreate(MainActivity.java:30)
at android.app.Activity.performCreate(Activity.java:6679)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1118)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2618)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2726)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1477)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6119)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
any help is appreciated
You just need to set the content view after setting the toolbar. You can write like this :
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
setContentView(R.layout.activity_main);
The app is crashing because you are first setting the view and then setting the toolbar.
I have bug I don't know how to fix.
I need to add a Fragment, but it won't work.
Everything happens in void firstTime() and the error shows that it's on line setContentView(R.layout.activity_main);.
I really don't know how to fix this.
I tried a lot of things, but it just does not work.
Please, help me.
MainActivity class:
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
private MapFragment mapsFragment;
static MainActivity can;
static FloatingActionButton fab;
static FloatingActionButton show;
private String encoded_string;
private Bitmap bitmap;
private String picturePath;
View rootView;
/**
* ATTENTION: This was auto-generated to implement the App Indexing API.
* See https://g.co/AppIndexing/AndroidStudio for more information.
*/
private GoogleApiClient client;
private void initializeMapsFragment() {
FragmentTransaction mTransaction = getSupportFragmentManager().beginTransaction();
mapsFragment = new MapFragment();
SupportMapFragment supportMapFragment = mapsFragment;
mTransaction.add(R.id.map, supportMapFragment);
mTransaction.commitNow();
}
#RequiresApi(api = Build.VERSION_CODES.GINGERBREAD)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
can = this;
Log.d("--***** MAP ", "::Loading Map");
setContentView(R.layout.activity_main);
initializeMapsFragment();
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
fab = (FloatingActionButton) findViewById(R.id.fab);
show = (FloatingActionButton) findViewById(R.id.show);
show.hide();
fab.hide();
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
callPopup();
}
});
show.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
stats();
}
});
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
can, 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(can);
Button searchButton = (Button) findViewById(R.id.searchButton);
searchButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
EditText searchView = (EditText) findViewById(R.id.searchView1);
String text = searchView.getText().toString();
Geocoder geocoder = new Geocoder(getBaseContext());
List<Address> addresses = null;
try {
// Getting a maximum of 3 Address that matches the input
// text
addresses = geocoder.getFromLocationName(text, 3);
if (addresses != null && !addresses.equals(""))
search(addresses);
} catch (Exception e) {
}
}
});
client = new GoogleApiClient.Builder(can).addApi(AppIndex.API).build();
}
public void start(){
setContentView(R.layout.activity_main);
initializeMapsFragment();
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
fab = (FloatingActionButton) findViewById(R.id.fab);
show = (FloatingActionButton) findViewById(R.id.show);
show.hide();
fab.hide();
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
callPopup();
}
});
show.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
stats();
}
});
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
can, 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(can);
Button searchButton = (Button) findViewById(R.id.searchButton);
searchButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
EditText searchView = (EditText) findViewById(R.id.searchView1);
String text = searchView.getText().toString();
Geocoder geocoder = new Geocoder(getBaseContext());
List<Address> addresses = null;
try {
// Getting a maximum of 3 Address that matches the input
// text
addresses = geocoder.getFromLocationName(text, 3);
if (addresses != null && !addresses.equals(""))
search(addresses);
} catch (Exception e) {
}
}
});
client = new GoogleApiClient.Builder(can).addApi(AppIndex.API).build();
}
protected void search(List<Address> addresses) {
Address address = (Address) addresses.get(0);
LatLng latLng = new LatLng(address.getLatitude(), address.getLongitude());
MapFragment.mapView.moveCamera(CameraUpdateFactory.newLatLng(latLng));
MapFragment.mapView.animateCamera(CameraUpdateFactory.zoomTo(15));
}
#RequiresApi(api = Build.VERSION_CODES.GINGERBREAD)
#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);
}
#RequiresApi(api = Build.VERSION_CODES.HONEYCOMB)
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
FragmentManager fm = getFragmentManager();
android.support.v4.app.FragmentManager sFm = getSupportFragmentManager();
int id = item.getItemId();
if (id == R.id.nav_camera) {
if (!mapsFragment.isAdded())
sFm.beginTransaction().add(R.id.map, mapsFragment).commit();
else
sFm.beginTransaction().show(mapsFragment).commit();
} else if (id == R.id.nav_share) {
Intent sharingIntent = new Intent(Intent.ACTION_SEND);
sharingIntent.setType("text/plain");
String shareBody = "Check this app out --> link.kys";
sharingIntent.putExtra(Intent.EXTRA_SUBJECT, "Best Free Parking app");
sharingIntent.putExtra(Intent.EXTRA_TEXT, shareBody);
startActivity(Intent.createChooser(sharingIntent, "Share via"));
} else if (id == R.id.nav_send) {
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
public void firstTime() {
setContentView(R.layout.firsttime);
(findViewById(R.id.cancelBut))
.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
//View view = can.findViewById(android.R.id.content);
//Log.d("a", "" + ((ViewGroup)view).getChildCount() );
//((ViewGroup) view).removeView(view);
android.support.v4.app.FragmentManager sFm = getSupportFragmentManager();
sFm.beginTransaction().remove(mapsFragment).commitNow();
if(mapsFragment.isAdded()){
Log.d("--***** FRAGMENT ", "::Still On");
}
start();
}
});
}
public static void load(){
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(can);
if (!prefs.getBoolean("firstTime", false)) {
can.firstTime();
//SharedPreferences.Editor editor = prefs.edit();
//editor.putBoolean("firstTime", true);
//editor.commit();
}
}
private void stats() {
setContentView(R.layout.stats);
RatingBar ratingbar = (RatingBar) findViewById(R.id.ratingBar);
ratingbar.setRating((float) 2.0);
ratingbar.setOnRatingBarChangeListener(new RatingBar.OnRatingBarChangeListener() {
public void onRatingChanged(RatingBar ratingBar, float rating,
boolean fromUser) {
ratingBar.setRating((float) 2.0);
}
});
((Button) findViewById(R.id.cancBut)).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
setContentView(R.layout.content_main);
}
});
}
}
Xml file:
<?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:id="#+id/content_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:context="com.robertas.parking.bestfreeparking.MainActivity"
tools:showIn="#layout/app_bar_main">
<fragment
android:id="#+id/map"
android:name="com.google.android.gms.maps.SupportMapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.robertas.parking.test.MapsActivity"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_weight="0.68" />
<EditText
android:id="#+id/searchView1"
android:inputType="textPersonName"
android:layout_width="250dp"
android:layout_height="34dp"
android:layout_marginTop="14dp"
android:hint="Search Location"
android:ems="10"
android:textColor="#android:color/black"
android:background="#android:color/white"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true">
</EditText>
<Button
android:id="#+id/searchButton"
android:layout_width="wrap_content"
android:layout_height="25dp"
android:background="#drawable/places_ic_search"
android:layout_alignBottom="#+id/searchView1"
android:layout_alignRight="#+id/searchView1"
android:layout_alignEnd="#+id/searchView1"
android:layout_alignTop="#+id/searchView1"
android:layout_marginLeft="216dp"
android:layout_marginStart="216dp"
android:layout_alignLeft="#+id/searchView1"
android:layout_alignStart="#+id/searchView1" />
</RelativeLayout>
Error:
android.view.InflateException: Binary XML file line #12: Error inflating class fragment
Log:
03-10 20:21:45.036 31937-31937/com.robertas.parking.bestfreeparking D/AndroidRuntime: Shutting down VM
03-10 20:21:45.036 31937-31937/com.robertas.parking.bestfreeparking E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.robertas.parking.bestfreeparking, PID: 31937
android.view.InflateException: Binary XML file line #12: Error inflating class fragment
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:763)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:806)
at android.view.LayoutInflater.parseInclude(LayoutInflater.java:916)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:802)
at android.view.LayoutInflater.parseInclude(LayoutInflater.java:916)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:802)
at android.view.LayoutInflater.inflate(LayoutInflater.java:504)
at android.view.LayoutInflater.inflate(LayoutInflater.java:414)
at android.view.LayoutInflater.inflate(LayoutInflater.java:365)
at android.support.v7.app.AppCompatDelegateImplV9.setContentView(AppCompatDelegateImplV9.java:284)
at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:143)
at com.robertas.parking.bestfreeparking.MainActivity.start(MainActivity.java:161)
at com.robertas.parking.bestfreeparking.MainActivity$8.onClick(MainActivity.java:356)
at android.view.View.performClick(View.java:4780)
at android.view.View$PerformClick.run(View.java:19866)
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)
Caused by: java.lang.IllegalArgumentException: Binary XML file line #12: Duplicate id 0x7f0f00e8, tag null, or parent id 0x7f0f00e7 with another fragment for com.google.android.gms.maps.SupportMapFragment
at android.support.v4.app.FragmentManagerImpl.onCreateView(FragmentManager.java:2427)
at android.support.v4.app.FragmentController.onCreateView(FragmentController.java:120)
at android.support.v4.app.FragmentActivity.dispatchFragmentsOnCreateView(FragmentActivity.java:378)
at android.support.v4.app.BaseFragmentActivityHoneycomb.onCreateView(BaseFragmentActivityHoneycomb.java:33)
at android.support.v4.app.FragmentActivity.onCreateView(FragmentActivity.java:77)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:733)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:806)
at android.view.LayoutInflater.parseInclude(LayoutInflater.java:916)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:802)
at android.view.LayoutInflater.parseInclude(LayoutInflater.java:916)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:802)
at android.view.LayoutInflater.inflate(LayoutInflater.java:504)
at android.view.LayoutInflater.inflate(LayoutInflater.java:414)
at android.view.LayoutInflater.inflate(LayoutInflater.java:365)
at android.support.v7.app.AppCompatDelegateImplV9.setContentView(AppCompatDelegateImplV9.java:284)
at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:143)
at com.robertas.parking.bestfreeparking.MainActivity.start(MainActivity.java:161)
at com.robertas.parking.bestfreeparking.MainActivity$8.onClick(MainActivity.java:356)
at android.view.View.performClick(View.java:4780)
at android.view.View$PerformClick.run(View.java:19866)
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)
03-10 20:21:45.039 1499-1878/system_process W/ActivityManager: Force finishing activity 1 com.robertas.parking.bestfreeparking/.MainActivity
[ 03-10 20:21:45.046 1499: 1878 D/ ]
HostConnection::get() New Host Connection established 0x7ffc98084ec0, tid 1878
03-10 20:21:45.051 1123-1123/? E/EGL_emulation: tid 1123: eglCreateSyncKHR(1299): error 0x3004 (EGL_BAD_ATTRIBUTE)
03-10 20:21:45.152 1499-1558/system_process I/OpenGLRenderer: Initialized EGL, version 1.4
03-10 20:21:45.194 1499-1558/system_process W/EGL_emulation: eglSurfaceAttrib not implemented
03-10 20:21:45.194 1499-1558/system_process W/OpenGLRenderer: Failed to set EGL_SWAP_BEHAVIOR on surface 0x7ffca953fb40, error=EGL_SUCCESS
03-10 20:21:45.612 1499-1518/system_process W/ActivityManager: Activity pause timeout for ActivityRecord{38e88b4d u0 com.robertas.parking.bestfreeparking/.MainActivity t155 f}
03-10 20:21:45.645 1756-2040/com.google.android.googlequicksearchbox W/EGL_emulation: eglSurfaceAttrib not implemented
03-10 20:21:45.645 1756-2040/com.google.android.googlequicksearchbox W/OpenGLRenderer: Failed to set EGL_SWAP_BEHAVIOR on surface 0xe1c93620, error=EGL_SUCCESS
03-10 20:21:46.616 1622-1622/com.android.systemui W/ResourceType: No package identifier when getting value for resource number 0x00000000
03-10 20:21:46.616 1622-1622/com.android.systemui W/PackageManager: Failure retrieving resources for com.robertas.parking.bestfreeparking: Resource ID #0x0
03-10 20:21:46.832 1756-1756/com.google.android.googlequicksearchbox I/Choreographer: Skipped 69 frames! The application may be doing too much work on its main thread.
03-10 20:21:47.332 1756-2040/com.google.android.googlequicksearchbox W/OpenGLRenderer: Incorrectly called buildLayer on View: aep, destroying layer...
03-10 20:21:47.448 1499-1577/system_process W/AudioTrack: AUDIO_OUTPUT_FLAG_FAST denied by client
03-10 20:21:47.465 31937-31937/? I/Process: Sending signal. PID: 31937 SIG: 9
03-10 20:21:47.474 1499-14634/system_process I/WindowState: WIN DEATH: Window{394fad98 u0 com.robertas.parking.bestfreeparking/com.robertas.parking.bestfreeparking.MainActivity}
03-10 20:21:47.474 1499-1874/system_process I/ActivityManager: Process com.robertas.parking.bestfreeparking (pid 31937) has died
03-10 20:21:47.475 1499-1874/system_process W/ActivityManager: Scheduling restart of crashed service com.robertas.parking.bestfreeparking/com.android.tools.fd.runtime.InstantRunService in 1000ms
03-10 20:21:47.480 1123-1123/? W/SurfaceFlinger: couldn't log to binary event log: overflow.
03-10 20:21:47.521 1499-1558/system_process D/OpenGLRenderer: endAllStagingAnimators on 0x7ffc9dfec000 (RippleDrawable) with handle 0x7ffca9734500
03-10 20:21:47.525 1499-1753/system_process W/InputMethodManagerService: Got RemoteException sending setActive(false) notification to pid 31937 uid 10058
03-10 20:21:47.537 1956-32415/com.google.android.googlequicksearchbox:search I/HotwordRecognitionRnr: Starting hotword detection.
03-10 20:21:47.537 1956-32414/com.google.android.googlequicksearchbox:search I/MicrophoneInputStream: mic_starting gzi#c6aa4d0
03-10 20:21:47.568 1135-1912/? E/audio_hw_generic: Error opening input stream format 1, channel_mask 0010, sample_rate 16000
03-10 20:21:47.569 1135-32418/? I/AudioFlinger: AudioFlinger's thread 0xf59c4000 ready to run
03-10 20:21:47.581 2146-32417/com.google.android.gms W/IcingInternalCorpora: getNumBytesRead when not calculated.
03-10 20:21:47.584 1956-32414/com.google.android.googlequicksearchbox:search I/MicrophoneInputStream: mic_started gzi#c6aa4d0
03-10 20:21:47.602 1956-1956/com.google.android.googlequicksearchbox:search I/HotwordWorker: onReady
03-10 20:21:47.629 2146-2248/com.google.android.gms W/Settings: Setting adb_enabled has moved from android.provider.Settings.Secure to android.provider.Settings.Global.
03-10 20:21:47.629 2146-2248/com.google.android.gms I/Icing: Usage reports 1 indexed 1 rejected 0 imm upload true
03-10 20:21:47.634 2146-2248/com.google.android.gms W/Icing: App history upload skipped 1 0 0
03-10 20:21:48.101 1135-1535/? W/AudioFlinger: write blocked for 469 msecs, 16 delayed writes, thread 0xf58ac000
03-10 20:21:48.503 32429-32429/? I/art: Not late-enabling -Xcheck:jni (already on)
03-10 20:21:48.507 1499-1518/system_process I/ActivityManager: Start proc 32429:com.robertas.parking.bestfreeparking/u0a58 for service com.robertas.parking.bestfreeparking/com.android.tools.fd.runtime.InstantRunService
03-10 20:21:48.775 32429-32429/com.robertas.parking.bestfreeparking I/FirebaseInitProvider: FirebaseApp initialization unsuccessful
03-10 20:21:48.777 32429-32429/com.robertas.parking.bestfreeparking I/InstantRun: Starting Instant Run Server for com.robertas.parking.bestfreeparking
03-10 20:21:48.777 1499-14635/system_process W/ActivityManager: getRunningAppProcesses: caller 10058 does not hold REAL_GET_TASKS; limiting output
Everything happens in firstTime() void and error shows that it's on line setContentView(R.layout.activity_main);.
You can't do this.
start() and firstTime() are not the entrypoints to your activity/application.
onCreate() is and that is where you can only call setContentView(R.layout.activity_main).
Even so, static methods that "load" any Activity aren't going to work.
public static void load(){
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(can);
if (!prefs.getBoolean("firstTime", false)) {
can.firstTime(); // This doesn't work like this
}
}
Especially if you did MainActivity.load() somewhere else in your other classes.
Reading your error, see that start() -> setContentView() is causing the problem...
at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:143)
at com.robertas.parking.bestfreeparking.MainActivity.start(MainActivity.java:161)
at com.robertas.parking.bestfreeparking.MainActivity$8.onClick(MainActivity.java:356)
at android.view.View.performClick(View.java:4780)
And the real error message
Duplicate id 0x7f0f00e8, tag null, or parent id 0x7f0f00e7 with another fragment for com.google.android.gms.maps.SupportMapFragment
Meaning that the Fragment "#+id/maps" has already been added into the FragmentManger of the Activity class, so it has been duplicated.
Activities should ideally not call setContentView outside of onCreate.
Reason being = You call setContentView, therefore removing the MapFragment (and other Views) entirely from the root view, so 1) the FragmentManger cannot find anything previously added, 2) Any view you had used findViewById before (probably) no longer exists.
If you are wanting to "replace" the content of some Activity, then you should use Fragments + a FrameLayout + a FragmentTransaction.replace() method call.
Make sure you compile com.google.android.gms.maps in your build.gradle file. Add this to your dependencies if it's not there:
dependencies {
<other dependencies>
compile 'com.google.android.gms:play-services-maps:10.2.0'
}
And remember to import it in your java file:
import com.google.android.gms.maps.SupportMapFragment;
And on the tools:context, it should be .MainActivity
This question already has answers here:
This Activity already has an action bar supplied by the window decor
(25 answers)
Closed 6 years ago.
while I test my app, I get the follow error in the Android-Studio-Consol:
10-09 20:44:56.685 21573-21573/com.example.android.buyhatke E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.android.buyhatke, PID: 21573
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.android.buyhatke/com.example.android.buyhatke.HomeActivity}: 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: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.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:198)
at android.support.v7.app.AppCompatActivity.setSupportActionBar(AppCompatActivity.java:130)
at com.example.android.buyhatke.HomeActivity.onCreate(HomeActivity.java:36)
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)
10-09 20:49:57.180 26089-26089/com.example.android.buyhatke W/System: ClassLoader referenced unknown path: /data/app/com.example.android.buyhatke-3/lib/x86
10-09 20:49:58.795 26089-26089/com.example.android.buyhatke W/System: ClassLoader referenced unknown path: /data/app/com.example.android.buyhatke-3/lib/x86
10-09 20:49:58.905 26089-26089/com.example.android.buyhatke W/art: Before Android 4.1, method android.graphics.PorterDuffColorFilter android.support.graphics.drawable.VectorDrawableCompat.updateTintFilter(android.graphics.PorterDuffColorFilter, android.content.res.ColorStateList, android.graphics.PorterDuff$Mode) would have incorrectly overridden the package-private method in android.graphics.drawable.Drawable
10-09 20:49:59.023 26089-26089/com.example.android.buyhatke D/AndroidRuntime: Shutting down VM
10-09 20:49:59.023 26089-26089/com.example.android.buyhatke E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.android.buyhatke, PID: 26089
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.android.buyhatke/com.example.android.buyhatke.HomeActivity}: 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: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.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:198)
at android.support.v7.app.AppCompatActivity.setSupportActionBar(AppCompatActivity.java:130)
at com.example.android.buyhatke.HomeActivity.onCreate(HomeActivity.java:36)
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)
My codes are
MainActivity.java
package com.example.android.buyhatke;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import com.facebook.CallbackManager;
import com.facebook.FacebookCallback;
import com.facebook.FacebookException;
import com.facebook.FacebookSdk;
import com.facebook.GraphRequest;
import com.facebook.GraphResponse;
import com.facebook.appevents.AppEventsLogger;
import com.facebook.login.LoginResult;
import com.facebook.login.widget.LoginButton;
import org.json.JSONObject;
public class MainActivity extends AppCompatActivity {
CallbackManager callbackManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//
facebookSDKInitialize();
LoginButton loginButton = (LoginButton) findViewById(R.id.login_button);
loginButton.setReadPermissions("email");
getLoginDetails(loginButton);
}
/*
Initialize the facebook sdk.
And then callback manager will handle the login responses.<br />
*/
protected void facebookSDKInitialize() {
FacebookSdk.sdkInitialize(getApplicationContext());
callbackManager = CallbackManager.Factory.create();
}
/*
Register a callback function with LoginButton to respond to the login result.
On successful login,login result has new access token and recently granted permissions.
*/
protected void getLoginDetails(LoginButton login_button){
// Callback registration<br />
login_button.registerCallback(callbackManager, new FacebookCallback <LoginResult> (){
#Override
public void onSuccess(LoginResult login_result) {
getUserInfo(login_result);
}
#Override
public void onCancel() {
// code for cancellation
}
#Override
public void onError(FacebookException error) {
// code for error handling.
}
});
}
/*To get the facebook user's own profile information via creating a new request.
When the request is completed, a callback is called to handle the success condition. */
protected void getUserInfo(LoginResult login_result){
GraphRequest data_request = GraphRequest.newMeRequest(
login_result.getAccessToken(),
new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted( JSONObject json_object, GraphResponse response) {
Intent intent = new Intent(MainActivity.this,HomeActivity.class);
intent.putExtra("jsondata",json_object.toString());
startActivity(intent);
}
});
Bundle permission_param = new Bundle();
permission_param.putString("fields", "id,name,email,picture.width(120).height(120)");
data_request.setParameters(permission_param);
data_request.executeAsync();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
callbackManager.onActivityResult(requestCode, resultCode, data);
Log.e("data",data.toString());
}
#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.
return super.onOptionsItemSelected(item);
}
#Override
protected void onResume() {
super.onResume();
// Logs 'install' and 'app activate' App Events.
AppEventsLogger.activateApp(this);
}
#Override
protected void onPause() {
super.onPause();
// Logs 'app deactivate' App Event.
AppEventsLogger.deactivateApp(this);
}
}
HomeActivity.java
package com.example.android.buyhatke;
import android.content.Context;
import android.content.Intent;
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.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.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.squareup.picasso.Picasso;
import org.json.JSONObject;
public class HomeActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {
JSONObject response, profile_pic_data, profile_pic_url;
TextView user_name, user_email;
ImageView user_picture;
NavigationView navigation_view;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setTitle("Home Page"); // may produce null pointer exception
Intent intent = getIntent();
String jsondata = intent.getStringExtra("jsondata");
setNavigationHeader(); // call setNavigationHeader Method.
setUserProfile(jsondata); // call setUserProfile Method
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.openDrawer, R.string.closeDrawer);
try {
drawer.setDrawerListener(toggle);
}catch(NullPointerException e)
{
Context context = getApplicationContext();
CharSequence text = "Error";
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
}
toggle.syncState();
navigation_view.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();
}
}
/*
Set Navigation header by using Layout Inflater.<br />
*/
public void setNavigationHeader(){
navigation_view = (NavigationView) findViewById(R.id.nav_view);
View header = LayoutInflater.from(this).inflate(R.layout.nav_header_home, null);
navigation_view.addHeaderView(header);
user_name = (TextView) header.findViewById(R.id.username);
user_picture = (ImageView) header.findViewById(R.id.profile_pic);
user_email = (TextView) header.findViewById(R.id.email);
}
/*
Set User Profile Information in Navigation Bar.<br />
*/
public void setUserProfile(String jsondata){
try {
response = new JSONObject(jsondata);
user_email.setText(response.get("email").toString());
user_name.setText(response.get("name").toString());
profile_pic_data = new JSONObject(response.get("picture").toString());
profile_pic_url = new JSONObject(profile_pic_data.getString("data"));
Picasso.with(this).load(profile_pic_url.getString("url"))
.into(user_picture);
} catch (Exception e){
e.printStackTrace();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.<br />
// getMenuInflater().inflate(R.menu.home, menu);<br />
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) {/** check if error*/
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.inbox) {
// Handle the camera action
} else if (id ==R.id.starred) {
}
else if (id ==R.id.sent_mail) {
}
else if (id ==R.id.drafts) {
}
else if (id ==R.id.allmail ) {
}
else if (id ==R.id.trash ) {
}
else if (id ==R.id.spam ) {
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
}
can anyone help?
In your styles.xml file, change your theme parent to NoActionBar if you are using Toolbar.
<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
Trying to set up the Navigation Drawer of an app right now, and every time I try to run the app on my Android device, I get a NullPointerException. The error is caused by getActionBar.setDisplayHomeUpAsEnabled(true) and getActionBar.setHomeButtonEnabled(true)
Even if I remove these two lines of code, I still get an error.
How do I fix this quickly?
Code:
import android.app.Activity;
import android.app.Fragment;
import android.content.res.Configuration;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.support.v7.app.ActionBarDrawerToggle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
public class MainActivity extends Activity {
private String[] navDrawerTitles;
private DrawerLayout navDrawerLayout;
private ListView mDrawerList;
private ActionBarDrawerToggle mDrawerToggle;
private CharSequence mTitle;
Fragment fragment = new Fragment();
private Fragment blankFrag = new Fragment();
private final int POSITION = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
navDrawerTitles = getResources().getStringArray(R.array.nav_array);
navDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ListView) findViewById(R.id.left_drawer);
// Set the adapter for the list view
mDrawerList.setAdapter(new ArrayAdapter<String>(this,
R.layout.drawer_list_item, navDrawerTitles));
mDrawerList.setOnItemClickListener(new DrawerItemClickListener());
getActionBar().setDisplayHomeAsUpEnabled(true);
getActionBar().setHomeButtonEnabled(true);
navDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerToggle = new ActionBarDrawerToggle(this, /* host Activity */
navDrawerLayout, /* DrawerLayout object */
//R.drawable.ic_drawer, /* nav drawer icon to replace 'Up' caret */
R.string.drawer_open, /* "open drawer" description */
R.string.drawer_close /* "close drawer" description */
) {
/** Called when a drawer has settled in a completely closed state. */
public void onDrawerClosed(View view) {
// super.onDrawerClosed(view);
getActionBar().setTitle(R.string.app_name);
invalidateOptionsMenu();
}
/** Called when a drawer has settled in a completely open state. */
public void onDrawerOpened(View drawerView) {
// super.onDrawerOpened(drawerView);
getActionBar().setTitle(R.string.app_name);
invalidateOptionsMenu();
}
};
// Set the drawer toggle as the DrawerListener
navDrawerLayout.setDrawerListener(mDrawerToggle);
if (savedInstanceState == null) {
selectItem(0);
}
}
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu_main, menu);
return super.onCreateOptionsMenu(menu);
}
/* Called whenever we call invalidateOptionsMenu() */
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
// If the nav drawer is open, hide action items related to the content
// view
boolean drawerOpen = navDrawerLayout.isDrawerOpen(mDrawerList);
menu.findItem(R.id.action_settings).setVisible(!drawerOpen);
return super.onPrepareOptionsMenu(menu);
}
public boolean onOptionsItemSelected(MenuItem item) {
// Pass the event to ActionBarDrawerToggle, if it returns
// true, then it has handled the app icon touch event
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
return super.onOptionsItemSelected(item);
}
private class DrawerItemClickListener implements
ListView.OnItemClickListener {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
selectItem(position);
}
}
/** Swaps fragments in the main content view */
/**
* Starts an Activity when item is clicked
*/
private void selectItem(int position) {
// }
Bundle args = new Bundle();
args.putInt(StartingFragment.TEA_TYPE_POS, position);
fragment.setArguments(args);
// Highlight the selected item, update the title, and close the drawer
mDrawerList.setItemChecked(position, true);
// setTitle(navDrawerTitles[position]);
navDrawerLayout.closeDrawer(mDrawerList);
}
#Override
public void setTitle(CharSequence title) {
mTitle = title;
getActionBar().setTitle(mTitle);
}
/**
* When using the ActionBarDrawerToggle, you must call it during
* onPostCreate() and onConfigurationChanged()...
*/
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
mDrawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
mDrawerToggle.onConfigurationChanged(newConfig);
}
}
01-31 14:11:11.298: E/AndroidRuntime(20904): FATAL EXCEPTION: main
01-31 14:11:11.298: E/AndroidRuntime(20904): Process:
appathon.bu.com.appathon, PID: 20904 01-31 14:11:11.298:
E/AndroidRuntime(20904): java.lang.RuntimeException: Unable to start
activity
ComponentInfo{appathon.bu.com.appathon/appathon.bu.com.appathon.MainActivity}:
java.lang.NullPointerException 01-31 14:11:11.298:
E/AndroidRuntime(20904): at
android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2212)
01-31 14:11:11.298: E/AndroidRuntime(20904): at
android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2271)
01-31 14:11:11.298: E/AndroidRuntime(20904): at
android.app.ActivityThread.access$800(ActivityThread.java:144) 01-31
14:11:11.298: E/AndroidRuntime(20904): at
android.app.ActivityThread$H.handleMessage(ActivityThread.java:1205)
01-31 14:11:11.298: E/AndroidRuntime(20904): at
android.os.Handler.dispatchMessage(Handler.java:102) 01-31
14:11:11.298: E/AndroidRuntime(20904): at
android.os.Looper.loop(Looper.java:136) 01-31 14:11:11.298:
E/AndroidRuntime(20904): at
android.app.ActivityThread.main(ActivityThread.java:5146) 01-31
14:11:11.298: E/AndroidRuntime(20904): at
java.lang.reflect.Method.invokeNative(Native Method) 01-31
14:11:11.298: E/AndroidRuntime(20904): at
java.lang.reflect.Method.invoke(Method.java:515) 01-31 14:11:11.298:
E/AndroidRuntime(20904): at
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:796)
01-31 14:11:11.298: E/AndroidRuntime(20904): at
com.android.internal.os.ZygoteInit.main(ZygoteInit.java:612) 01-31
14:11:11.298: E/AndroidRuntime(20904): at
dalvik.system.NativeStart.main(Native Method) 01-31 14:11:11.298:
E/AndroidRuntime(20904): Caused by: java.lang.NullPointerException
01-31 14:11:11.298: E/AndroidRuntime(20904): at
appathon.bu.com.appathon.MainActivity.onCreate(MainActivity.java:45)
01-31 14:11:11.298: E/AndroidRuntime(20904): at
android.app.Activity.performCreate(Activity.java:5231) 01-31
14:11:11.298: E/AndroidRuntime(20904): at
android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
01-31 14:11:11.298: E/AndroidRuntime(20904): at
android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2169)
01-31 14:11:11.298: E/AndroidRuntime(20904): ... 11 more
First, if getActionBar() in an Activity is returning null, then you do not have a native action bar in your activity.
Second, android.support.v7.app.ActionBarDrawerToggle does not work with the native action bar. It works with the appcompat-v7 action bar backport. If you are going to use android.support.v7.app.ActionBarDrawerToggle, then you have to move your app over to use appcompat-v7:
Add appcompat-v7 as a dependency
Inherit from ActionBarActivity instead of Activity
Call getSupportActionBar() rather than getActionBar()
Use Theme.AppCompat (or something that inherits from it) as your activity's theme
I had the same error as you. My solution was to set theme with ThemeAppCompat, make your activity extend AppCompatActivity and use the method of getSupportActionBar instead of using the method of getActionBar. In short, you should make sure the actionBar of theme and the method which to get actionBar have the same support library.