During one of the launches of the application, log issued such a stack of errors:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.nikitafront.schooldiary, PID: 29751
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.nikitafront.schooldiary/com.nikitafront.schooldiary.MainActivity}: java.lang.IllegalStateException: Activity com.nikitafront.schooldiary.MainActivity#4801345 does not have a NavController set on 2131296534
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3754)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3912)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:85)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2319)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:239)
at android.app.ActivityThread.main(ActivityThread.java:8205)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:626)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1016)
Caused by: java.lang.IllegalStateException: Activity com.nikitafront.schooldiary.MainActivity#4801345 does not have a NavController set on 2131296534
at androidx.navigation.Navigation.findNavController(Navigation.java:61)
at com.nikitafront.schooldiary.MainActivity.onCreate(MainActivity.java:53)
at android.app.Activity.performCreate(Activity.java:8119)
at android.app.Activity.performCreate(Activity.java:8103)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1359)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3727)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3912)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:85)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2319)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:239)
at android.app.ActivityThread.main(ActivityThread.java:8205)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:626)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1016)
Before this I was only experimenting with app themes, but after I returned everything to its original state nothing has changed
P.S. I tried solve the problem by clearing the cache and restart IDE, but this way doesn`t worked too.
MainActivity.java code
package com.nikitafront.schooldiary;
import android.content.res.Configuration;
import android.graphics.Canvas;
import android.graphics.ColorFilter;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.widget.CheckBox;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.Spinner;
import com.google.android.material.bottomnavigation.BottomNavigationView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
import androidx.navigation.NavController;
import androidx.navigation.Navigation;
import androidx.navigation.fragment.NavHostFragment;
import androidx.navigation.ui.AppBarConfiguration;
import androidx.navigation.ui.NavigationUI;
import com.nikitafront.schooldiary.databinding.ActivityMainBinding;
public class MainActivity extends AppCompatActivity {
private ActivityMainBinding binding;
private CheckBox checkBoxAuto;
private Spinner dropDownList;
private LinearLayout byHandLesson;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
binding = ActivityMainBinding.inflate(getLayoutInflater());
setContentView(binding.getRoot());
BottomNavigationView navView = findViewById(R.id.nav_view);
// Passing each menu ID as a set of Ids because each
// menu should be considered as top level destinations.
AppBarConfiguration appBarConfiguration = new AppBarConfiguration.Builder(
R.id.nav_write, R.id.nav_do, R.id.nav_account)
.build();
NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment_activity_main);
NavigationUI.setupActionBarWithNavController(this, navController, appBarConfiguration);
NavigationUI.setupWithNavController(binding.navView, navController);
checkBoxAuto = (CheckBox) findViewById(R.id.checkBoxAuto);
dropDownList = (Spinner) findViewById(R.id.dropDownListLesson);
byHandLesson = (LinearLayout) findViewById(R.id.byHandLesson);
}
#Override
protected void onStart() {
super.onStart();
checkBoxAuto.setOnClickListener(this::selectFillLesson);
int currentNightMode = getApplicationContext().getResources().getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_MASK;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP && currentNightMode == Configuration.UI_MODE_NIGHT_YES) {
getWindow().setNavigationBarColor(ContextCompat.getColor(this, R.color.my_black));
}
}
public void selectFillLesson(View view) {
if (checkBoxAuto.isChecked()) {
byHandLesson.setAlpha((float) 0.7);
} else {
byHandLesson.setAlpha((float) 1);
}
dropDownList.setEnabled(!(checkBoxAuto.isChecked()));
}
public void selectCheckBox(View view) {
checkBoxAuto.setChecked(!checkBoxAuto.isChecked());
selectFillLesson(checkBoxAuto);
}
public void addHomework(View view) {
}
}
main_activity.xml code
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent">
<com.google.android.material.bottomnavigation.BottomNavigationView
android:id="#+id/nav_view"
android:layout_width="0dp"
android:layout_height="wrap_content"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:menu="#menu/bottom_nav_menu" />
<androidx.fragment.app.FragmentContainerView
android:id="#+id/nav_host_fragment_activity_main"
android:name="androidx.navigation.fragment.NavHostFragment"
class="androidx.navigation.fragment.NavHostFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:defaultNavHost="true"
app:layout_constraintBottom_toTopOf="#id/nav_view"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:navGraph="#navigation/mobile_navigation" />
</androidx.constraintlayout.widget.ConstraintLayout>
Manifest.xml code
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.nikitafront.schooldiary">
<application
android:allowBackup="true"
android:icon="#drawable/homework_icon"
android:label="#string/app_name"
android:roundIcon="#drawable/homework_icon"
android:supportsRtl="true"
android:theme="#style/Theme.SchoolDiary">
<activity
android:name=".MainActivity"
android:label="#string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
As it was described in the reference:
When creating the NavHostFragment using FragmentContainerView or if
manually adding the NavHostFragment to your activity via a
FragmentTransaction, attempting to retrieve the NavController in
onCreate() of an Activity via Navigation.findNavController(Activity,
#IdRes int) will fail. You should retrieve the NavController directly
from the NavHostFragment instead.
Looks like you should use
NavHostFragment navHostFragment =
(NavHostFragment) supportFragmentManager.findFragmentById(R.id.nav_host_fragment);
NavController navController = navHostFragment.getNavController();
instead of
NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment_activity_main);
Navigating to a destination is done using a NavController, an
object that manages app navigation within a NavHost. Each
NavHost has its own corresponding NavController.
Write your code like below:
Kotlin
val bottomNavigationView = findViewById<BottomNavigationView>(R.id.nav_view)
val navHostFragment = supportFragmentManager.findFragmentById(R.id.nav_host_fragment_activity_main) as NavHostFragment
bottomNavigationView.setupWithNavController(navHostFragment.navController)
Java
BottomNavigationView bottomNavigationView = findViewById<BottomNavigationView>(R.id.nav_view);
NavHostFragment navHostFragment = (NavHostFragment) supportFragmentManager.findFragmentById(R.id.nav_host_fragment_activity_main);
bottomNavigationView.setupWithNavController(navHostFragment.navController);
Related
I have a simple toy app that works on one mainActivity. It has a bottom navigation bar with separate nested graphs. For instance, the navigation graph "notification" has an additional destination to settings. If I move to "notification" >>> "settings" >>>> to "home"/"dashboard" nested navigation and get back to "notification", it will show the most recent state of nested graph, which is "settings".
How to make the bottom navigation to get to the startDestination, which is "notification", after I double click "notification" menu item? For instance, the first time I click "notification" it retrieves "settings", if I click the same "notification" item in the bottom navigation, it will get me to the startDestination "notification".
activity_main.xml
package com.example.myvagtest;
import android.os.Bundle;
import com.google.android.material.bottomnavigation.BottomNavigationView;
import androidx.appcompat.app.AppCompatActivity;
import androidx.navigation.NavController;
import androidx.navigation.Navigation;
import androidx.navigation.ui.AppBarConfiguration;
import androidx.navigation.ui.NavigationUI;
import com.example.myvagtest.databinding.ActivityMainBinding;
import java.util.HashSet;
import java.util.Set;
public class MainActivity extends AppCompatActivity {
private ActivityMainBinding binding;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
binding = ActivityMainBinding.inflate(getLayoutInflater());
setContentView(binding.getRoot());
BottomNavigationView navView = findViewById(R.id.nav_view);
// Passing each menu ID as a set of Ids because each
// menu should be considered as top level destinations.
AppBarConfiguration appBarConfiguration = new AppBarConfiguration.Builder(
R.id.navigation_nested3,R.id.navigation_nested2,R.id.navigation_nested1).build();
NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment_activity_main);
NavigationUI.setupActionBarWithNavController(this, navController, appBarConfiguration);
NavigationUI.setupWithNavController(navView, navController);
}
}
menu.xml
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:id="#+id/navigation_nested1"
android:icon="#drawable/ic_home_black_24dp"
android:title="#string/title_home" />
<item
android:id="#+id/navigation_nested2"
android:menuCategory="secondary"
android:icon="#drawable/ic_dashboard_black_24dp"
android:title="#string/title_dashboard" />
<item
android:id="#+id/navigation_nested3"
android:menuCategory="secondary"
android:icon="#drawable/ic_notifications_black_24dp"
android:title="#string/title_notifications" />
</menu>
navigation.xml
<?xml version="1.0" encoding="utf-8"?>
<navigation 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/mobile_navigation"
app:startDestination="#+id/navigation_nested1">
<navigation
android:id="#+id/navigation_nested1"
app:startDestination="#id/navigation_home">
<fragment
android:id="#+id/navigation_home"
android:name="com.example.myvagtest.ui.home.HomeFragment"
android:label="#string/title_home"
tools:layout="#layout/fragment_home" />
</navigation>
<navigation
android:id="#+id/navigation_nested2"
app:startDestination="#id/navigation_dashboard">
<fragment
android:id="#+id/navigation_dashboard"
android:name="com.example.myvagtest.ui.dashboard.DashboardFragment"
android:label="#string/title_dashboard"
tools:layout="#layout/fragment_dashboard" />
</navigation>
<navigation
android:id="#+id/navigation_nested3"
app:startDestination="#id/navigation_notifications"
>
<fragment
android:id="#+id/navigation_settings"
android:name="com.example.myvagtest.ui.SettingsFragment"
android:label="settings"
tools:layout="#layout/fragment_settings">
<action
android:id="#+id/action_navigation_settings_to_navigation_notifications"
app:destination="#id/navigation_notifications" />
</fragment>
<fragment
android:id="#+id/navigation_notifications"
android:name="com.example.myvagtest.ui.notifications.NotificationsFragment"
android:label="#string/title_notifications"
tools:layout="#layout/fragment_notifications">
<action
android:id="#+id/action_navigation_notifications_to_navigation_settings"
app:destination="#id/navigation_settings" />
<action
android:id="#+id/action_navigation_notifications_pop"
app:popUpTo="#id/navigation_notifications"
app:popUpToInclusive="true" />
</fragment>
<action
android:id="#+id/action_navigation_nested3_self"
app:destination="#id/navigation_notifications"
app:launchSingleTop="true"
app:popUpTo="#id/navigation_notifications"
app:popUpToInclusive="true"/>
</navigation>
</navigation>
Update:
public void bottomNavigationReselection() {
navView.setOnItemReselectedListener(new NavigationBarView.OnItemReselectedListener() {
#Override
public void onNavigationItemReselected(#NonNull MenuItem item) {
int id = item.getItemId();
if (id == R.id.home_navigation) {
navController.navigate(R.id.action_global_home_navigation);
} else if (id == R.id.explore_navigation){
navController.navigate(R.id.action_global_navigation_explore);
} else if (id == R.id.library_navigation){
navController.navigate(R.id.action_global_navigation_library);
} else if (id == R.id.profile_navigation) {
navController.navigate(R.id.action_global_navigation_profile);
}
}
});
}
is enough to refresh main destinations.
As soon as I am launching my application , the splash screen appears but after 4 seconds the app crashes , I don't know what is the problem . I have already tried and tested other solutions but nothing worked for me. If any of you could tell me the solution then it would be of great help.
Splash.java
package com.example.myapplication;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.view.WindowManager;
import androidx.annotation.RequiresApi;
import com.example.myapplication.MainActivity;
import com.example.myapplication.R;
public class Splash extends MainActivity {
public static int splashTimeout=2000;
#RequiresApi(api = Build.VERSION_CODES.P)
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);
new android.os.Handler().postDelayed(new Runnable() {
#Override
public void run() {
Intent intent=new Intent(Splash.this,MainActivity.class);
startActivity(intent);
finish();
}
} ,splashTimeout );
}
}
activity_splash.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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="#drawable/java_bg2"
tools:context=".Splash">
<ImageView
android:id="#+id/imageView2"
android:layout_width="203dp"
android:layout_height="172dp"
android:layout_marginTop="136dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.497"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
android:background="#drawable/java_bg1"
app:srcCompat="#drawable/java_logo" />
<TextView
android:id="#+id/textView3"
android:layout_width="376dp"
android:layout_height="77dp"
android:fontFamily="#font/courgette"
android:gravity="center_horizontal|center_vertical"
android:outlineAmbientShadowColor="#color/black"
android:shadowColor="#color/black"
android:text="#string/software_sucks_because_users_demand_it_to"
android:textAllCaps="true"
android:textColor="#FFFFFF"
android:textSize="24sp"
android:textStyle="bold|italic"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.457"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/imageView2"
app:layout_constraintVertical_bias="0.84" />
</androidx.constraintlayout.widget.ConstraintLayout>
MainActivity.java
package com.example.myapplication;
import android.content.Intent;
import android.os.Bundle;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.android.material.snackbar.Snackbar;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Handler;
import android.view.View;
import androidx.navigation.NavController;
import androidx.navigation.Navigation;
import androidx.navigation.ui.AppBarConfiguration;
import androidx.navigation.ui.NavigationUI;
import com.example.myapplication.databinding.ActivityMainBinding;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
private AppBarConfiguration appBarConfiguration;
private ActivityMainBinding binding;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
binding = ActivityMainBinding.inflate(getLayoutInflater());
setContentView(binding.getRoot());
setSupportActionBar(binding.toolbar);
NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment_content_main);
appBarConfiguration = new AppBarConfiguration.Builder(navController.getGraph()).build();
NavigationUI.setupActionBarWithNavController(this, navController, appBarConfiguration);
binding.fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(MainActivity.this, "Thoda Wait Kar Na Bhai", Toast.LENGTH_SHORT).show();
}
});
}
private void activity3() {
System.out.println("Activity3");
}
private void activity2() {
System.out.println("Activity2");
}
#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);
}
#Override
public boolean onSupportNavigateUp() {
NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment_content_main);
return NavigationUI.navigateUp(navController, appBarConfiguration)
|| super.onSupportNavigateUp();
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<com.google.android.material.appbar.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/Theme.MyApplication.AppBarOverlay">
<androidx.appcompat.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:popupTheme="#style/Theme.MyApplication.PopupOverlay" />
</com.google.android.material.appbar.AppBarLayout>
<ImageView
android:id="#+id/imageView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scaleType = "centerCrop"
app:layout_anchor="#+id/include"
app:layout_anchorGravity="center"
app:srcCompat="#drawable/background" />
<include
android:id="#+id/include"
layout="#layout/content_main"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<com.google.android.material.floatingactionbutton.FloatingActionButton
android:id="#+id/fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|end"
android:layout_margin="#dimen/fab_margin"
app:srcCompat="#android:drawable/ic_dialog_email" />
</androidx.coordinatorlayout.widget.CoordinatorLayout>
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.myapplication">
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/Theme.MyApplication">
<activity android:name=".decToHex"/>
<activity android:name=".MainActivity" />
<activity android:name=".decToOct" />
<activity android:name=".decToBin" />
<activity android:name=".binToHex" />
<activity android:name=".binToOct" />
<activity android:name=".binToDec" />
<activity
android:name=".Splash"
android:label="#string/app_name"
android:theme="#style/Theme.MyApplication.NoActionBar">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<meta-data
android:name="preloaded_fonts"
android:resource="#array/preloaded_fonts" />
</application>
</manifest>
Logcat
2021-06-28 17:41:29.470 6195-6195/com.example.myapplication I/zygote: Not late-enabling -Xcheck:jni (already on)
2021-06-28 17:41:29.493 6195-6195/com.example.myapplication W/zygote: Unexpected CPU variant for X86 using defaults: x86
2021-06-28 17:41:30.696 6195-6273/com.example.myapplication D/OpenGLRenderer: HWUI GL Pipeline
2021-06-28 17:41:30.758 6195-6273/com.example.myapplication I/OpenGLRenderer: Initialized EGL, version 1.4
2021-06-28 17:41:30.758 6195-6273/com.example.myapplication D/OpenGLRenderer: Swap behavior 1
2021-06-28 17:41:30.758 6195-6273/com.example.myapplication W/OpenGLRenderer: Failed to choose config with EGL_SWAP_BEHAVIOR_PRESERVED, retrying without...
2021-06-28 17:41:30.759 6195-6273/com.example.myapplication D/OpenGLRenderer: Swap behavior 0
2021-06-28 17:41:30.789 6195-6273/com.example.myapplication D/EGL_emulation: eglCreateContext: 0xac8b1e60: maj 2 min 0 rcv 2
2021-06-28 17:41:30.802 6195-6273/com.example.myapplication D/EGL_emulation: eglMakeCurrent: 0xac8b1e60: ver 2 0 (tinfo 0xac88b280)
2021-06-28 17:41:30.858 6195-6273/com.example.myapplication D/EGL_emulation: eglMakeCurrent: 0xac8b1e60: ver 2 0 (tinfo 0xac88b280)
2021-06-28 17:41:32.770 6195-6204/com.example.myapplication I/zygote: Do partial code cache collection, code=29KB, data=30KB
2021-06-28 17:41:32.772 6195-6204/com.example.myapplication I/zygote: After code cache collection, code=29KB, data=30KB
2021-06-28 17:41:32.772 6195-6204/com.example.myapplication I/zygote: Increasing code cache capacity to 128KB
2021-06-28 17:41:32.806 6195-6195/com.example.myapplication D/AndroidRuntime: Shutting down VM
2021-06-28 17:41:32.808 6195-6195/com.example.myapplication E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.myapplication, PID: 6195
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.myapplication/com.example.myapplication.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:2817)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2892)
at android.app.ActivityThread.-wrap11(Unknown Source:0)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1593)
at android.os.Handler.dispatchMessage(Handler.java:105)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6541)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)
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 androidx.appcompat.app.AppCompatDelegateImpl.setSupportActionBar(AppCompatDelegateImpl.java:575)
at androidx.appcompat.app.AppCompatActivity.setSupportActionBar(AppCompatActivity.java:183)
at com.example.myapplication.MainActivity.onCreate(MainActivity.java:45)
at android.app.Activity.performCreate(Activity.java:6975)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1213)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2770)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2892)
at android.app.ActivityThread.-wrap11(Unknown Source:0)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1593)
at android.os.Handler.dispatchMessage(Handler.java:105)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6541)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)
You are trying to set action bar with activity twice. remove below line from code or if you do not want to remove below line disable default action bar from activity using theme.
setSupportActionBar(binding.toolbar);
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.
Your logs has your solution.
Add this line
<item name="windowActionBar">false</item>
to your theme declaration inside of your app/src/main/res/values/styles.xml.
Also, if you're using AppCompatActivity support library of version 22.1 or greater, add this line:
<item name="windowNoTitle">true</item>
Your theme declaration may look like this after all these additions:
<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
<!-- Customize your theme here. -->
<item name="colorPrimary">#color/colorPrimary</item>
<item name="colorPrimaryDark">#color/colorPrimaryDark</item>
<item name="colorAccent">#color/colorAccent</item>
<item name="windowActionBar">false</item>
<item name="windowNoTitle">true</item>
</style>
This is my main activity i want to navigate to an activity on my navigation drawer item click. I have checked the old way of achieving this i.e using switch statement and using onNavigationItemSelected method.
I know this is a question frequently asked, but after reading the many questions and solutions on stack overflow I am confused. I am confused with regards to Fragments and what is required to start an activity from clicking an item in the navigation drawer.
MainActivity.java
import android.os.Bundle;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.android.material.snackbar.Snackbar;
import android.view.View;
import androidx.navigation.NavController;
import androidx.navigation.Navigation;
import androidx.navigation.ui.AppBarConfiguration;
import androidx.navigation.ui.NavigationUI;
import com.google.android.material.navigation.NavigationView;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import android.view.Menu;
public class MainActivity extends AppCompatActivity {
private AppBarConfiguration mAppBarConfiguration;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
DrawerLayout drawer = findViewById(R.id.drawer_layout);
NavigationView navigationView = findViewById(R.id.nav_view);
// Passing each menu ID as a set of Ids because each
// menu should be considered as top level destinations.
mAppBarConfiguration = new AppBarConfiguration.Builder(
R.id.nav_home, R.id.nav_gallery, R.id.nav_slideshow,
R.id.nav_tools, R.id.nav_share, R.id.nav_send)
.setDrawerLayout(drawer)
.build();
NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
NavigationUI.setupActionBarWithNavController(this, navController, mAppBarConfiguration);
NavigationUI.setupWithNavController(navigationView, navController);
}
#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 onSupportNavigateUp() {
NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
return NavigationUI.navigateUp(navController, mAppBarConfiguration)
|| super.onSupportNavigateUp();
}
}
mobile_navigation.xml
<?xml version="1.0" encoding="utf-8"?>
<navigation 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/mobile_navigation"
app:startDestination="#+id/nav_home">
<fragment
android:id="#+id/nav_home"
android:name="com.vdosol.navigationdrawer.ui.home.HomeFragment"
android:label="#string/menu_home"
tools:layout="#layout/fragment_home" />
<fragment
android:id="#+id/nav_gallery"
android:name="com.vdosol.navigationdrawer.ui.gallery.GalleryFragment"
android:label="#string/menu_gallery"
tools:layout="#layout/fragment_gallery" />
<fragment
android:id="#+id/nav_slideshow"
android:name="com.vdosol.navigationdrawer.ui.slideshow.SlideshowFragment"
android:label="#string/menu_slideshow"
tools:layout="#layout/fragment_slideshow" />
<fragment
android:id="#+id/nav_tools"
android:name="com.vdosol.navigationdrawer.ui.tools.ToolsFragment"
android:label="#string/menu_tools"
tools:layout="#layout/fragment_tools" />
<fragment
android:id="#+id/nav_share"
android:name="com.vdosol.navigationdrawer.ui.share.ShareFragment"
android:label="#string/menu_share"
tools:layout="#layout/fragment_share" />
<fragment
android:id="#+id/nav_send"
android:name="com.vdosol.navigationdrawer.ui.send.SendFragment"
android:label="#string/menu_send"
tools:layout="#layout/fragment_send" />
</navigation>
you can do the following to navigate:
MenuItem logOutItem = navigationView.getMenu().findItem(R.id.nav_logout);
logOutItem.setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem item) {
//do your stuff
return true;
}
});
your AppBarConfiguration and Nav Controller should not contain above id ie "nav_logout" (in my case):
mAppBarConfiguration = new AppBarConfiguration.Builder(
R.id.navigation_home, R.id.navigation_dashboard, R.id.navigation_plan, R.id.navigation_history, R.id.navigation_about, R.id.navigation_feedback, R.id.navigation_notifications)
.setDrawerLayout(drawer)
.build();
your menu should only contain in your menu file....no need to add it to you AppBarConfiguration and your NavController....
hope this helps....happy coding
Implement the listener in your Activity:
public class HomeActivity extends AppCompatActivity implements
NavigationView.OnNavigationItemSelectedListener
setNavigationItemSelectedListener in onCreate of Activity
NavigationView mNavigationView = (NavigationView) findViewById(R.id.account_navigation_view);
if (mNavigationView != null) {
mNavigationView.setNavigationItemSelectedListener(this);
}
Override the method
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_account) {//DO your stuff }
...
}
I tried to follow some tutorials on how to set up a shared elements transition. Though when i try to set up a background the shared element kind of glitches the wrong way and then moves like it should.
Heres a link to a video of my problem: https://drive.google.com/file/d/14lTFGIpqnMwM2MEbLxwBe_gkI0GuyuMc/view?usp=sharing
When no background is set: https://drive.google.com/open?id=15Hpkj7y8nLLTXa5RF5FV00jlTTWMofjF
When i don't set a background in my xml layout, the animation works properly. Does anyone know, why this happens?
Activity 1 XML
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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="#color/colorPrimary"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:id="#+id/text1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:fontFamily="#font/nexa"
android:gravity="center"
android:padding="10dp"
android:text="Test"
android:textColor="#color/colorAccent"
android:textSize="30sp"
android:transitionName="transition"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
Activity 2 XML
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
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:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/colorPrimary">
<TextView
android:id="#+id/text2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"
android:padding="10dp"
android:text="Test"
android:fontFamily="#font/nexa"
android:textColor="#color/colorAccent"
android:textSize="30sp"
android:transitionName="transition"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.05" />
</androidx.constraintlayout.widget.ConstraintLayout>
Activity 1 Java
package com.stonks.sharedanimtest;
import androidx.appcompat.app.AppCompatActivity;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.core.app.ActivityCompat;
import android.app.ActivityOptions;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.WindowManager;
import android.widget.LinearLayout;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
private TextView textView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
getWindow().setEnterTransition(null);
textView = (TextView) findViewById(R.id.text1);
textView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(MainActivity.this, MainActivity2.class);
ActivityOptions options = ActivityOptions.makeSceneTransitionAnimation(MainActivity.this, textView, "transition");
startActivity(intent, options.toBundle());
}
});
}
}
Activity 2 Java
package com.stonks.sharedanimtest;
import android.app.Activity;
import android.app.ActivityOptions;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.WindowManager;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
public class MainActivity2 extends AppCompatActivity {
private TextView textView;
#Override
public void onBackPressed() {
textView = (TextView) findViewById(R.id.text2);
Intent intent = new Intent(MainActivity2.this, MainActivity.class);
ActivityOptions options = ActivityOptions.makeSceneTransitionAnimation(MainActivity2.this, textView, "transition");
startActivity(intent, options.toBundle());
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
getWindow().setEnterTransition(null);
}
}
Colors XML
<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="colorPrimary">#161618</color>
<color name="colorPrimaryLight">#202024</color>
<color name="colorAccent">#ffffff</color>
</resources>
Manifest XML
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.stonks.sharedanimtest">
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".MainActivity2"
android:screenOrientation="portrait" />
<activity android:name=".MainActivity"
android:screenOrientation="portrait">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
You can wrap your shared view (either text1 or text2) in FrameLayout - but still TextView should be the shared element. It should solve the issue.
I've made an app that allows user to login but everytime I try to run, my App is crashing constantly.
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.mertino11.ourapplication">
<uses-permission android:name="android.permission.INTERNET" />
<application
android:name=".FireApp"
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true">
<activity
android:name=".MainActivity"
android:theme="#style/AppTheme">
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
</application>
</manifest>
activity_account.xml (XML for user logged in succesfully)
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/activity_account"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.example.mertino11.ourapplication.AccountActivity">
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="textPersonName"
android:text="Account Page"
android:ems="10"
android:id="#+id/editText"
android:textSize="22sp"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true"
android:textStyle="normal|bold"
android:textAlignment="center" />
</RelativeLayout>
activity_main.xml (login page)
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:baselineAligned="false">
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textEmailAddress"
android:ems="10"
android:id="#+id/emailField"
android:hint="Email"
android:paddingTop="20dp" />
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textPassword"
android:ems="10"
android:id="#+id/passwordField"
android:hint="Password"
android:fontFamily="sans-serif"
android:paddingTop="20dp" />
<Button
android:text="Login"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/loginBtn"
android:paddingTop="20dp" />
</LinearLayout>
Java --> Class: AccountActivity (Page when the user logged in successfully)
package com.example.mertino11.ourapplication;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
public class AccountActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_account);
}
}
Java --> Class: FireApp (Firebase settings I think)
package com.example.mertino11.ourapplication;
import android.app.Application;
import com.firebase.client.Firebase;
/**
* Created by Mertino11 on 10-Dec-16.
*/
public class FireApp extends Application {
#Override
public void onCreate() {
super.onCreate();
Firebase.setAndroidContext(this);
}
}
Java --> Class: Main Activity (Back-end logging with account)
package com.example.mertino11.ourapplication;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
public class MainActivity extends AppCompatActivity {
private EditText mEmailField;
private EditText mPasswordField;
private Button mLoginBtn;
private FirebaseAuth mAuth;
private FirebaseAuth.AuthStateListener mAuthListener;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mAuth = FirebaseAuth.getInstance();
mEmailField = (EditText) findViewById(R.id.emailField);
mPasswordField = (EditText) findViewById(R.id.passwordField);
mLoginBtn = (Button) findViewById(R.id.loginBtn);
mAuthListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
if(firebaseAuth.getCurrentUser() != null) {
startActivity(new Intent(MainActivity.this, AccountActivity.class));
}
}
};
mLoginBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startSignIn();
}
});
}
#Override
protected void onStart() {
super.onStart();
mAuth.addAuthStateListener(mAuthListener);
}
private void startSignIn() {
String email = mEmailField.getText().toString();
String password = mPasswordField.getText().toString();
if(TextUtils.isEmpty(email) || TextUtils.isEmpty(password)) {
Toast.makeText(MainActivity.this, "Fields are empty!", Toast.LENGTH_LONG).show();
} else {
mAuth.signInWithEmailAndPassword(email, password).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if(!task.isSuccessful()){
Toast.makeText(MainActivity.this, "Sign In Problem!", Toast.LENGTH_LONG).show();
}
}
});
}
}
}
Error Message at Run:
--------- beginning of crash
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.mertino11.ourapplication, PID: 3060
android.content.ActivityNotFoundException: Unable to find explicit activity class {com.example.mertino11.ourapplication/com.example.mertino11.ourapplication.AccountActivity}; have you declared this activity in your AndroidManifest.xml?
at android.app.Instrumentation.checkStartActivityResult(Instrumentation.java:1805)
at android.app.Instrumentation.execStartActivity(Instrumentation.java:1523)
at android.app.Activity.startActivityForResult(Activity.java:4224)
at android.support.v4.app.BaseFragmentActivityJB.startActivityForResult(BaseFragmentActivityJB.java:48)
at android.support.v4.app.FragmentActivity.startActivityForResult(FragmentActivity.java:75)
at android.app.Activity.startActivityForResult(Activity.java:4183)
at android.support.v4.app.FragmentActivity.startActivityForResult(FragmentActivity.java:856)
at android.app.Activity.startActivity(Activity.java:4507)
at android.app.Activity.startActivity(Activity.java:4475)
at com.example.mertino11.ourapplication.MainActivity$1.onAuthStateChanged(MainActivity.java:48)
at com.google.firebase.auth.FirebaseAuth$1.run(Unknown Source)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6077)
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)
Application terminated.
Screenshot of the error:
http://i66.tinypic.com/51btrp.png
The scenario of the app:
Create account firebase Google (manually)
Opens app --> Sees login page
Logs in with accountdetails of Firebase
Goes to AccountActivity page
Note: I am a amateur/beginner with AndroidStudio.
The error is pretty self-explanatory.
You have missed adding the AccounActivity on your manifest...
<application
android:name=".FireApp"
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true">
<activity
android:name=".MainActivity"
android:theme="#style/AppTheme">
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
<activity
android:name=".AccountActivity"
android:theme="#style/AppTheme" />
</application>
Add AccountActivity in your AndroidManifest.xml
<activity
android:name=".AccountActivity">
<intent-filter>
...
</intent-filter>
</activity>
Always carefully read logcat:
android.content.ActivityNotFoundException: Unable to find explicit activity class {com.example.mertino11.ourapplication/com.example.mertino11.ourapplication.AccountActivity}; have you declared this activity in your AndroidManifest.xml?
I thank you all for giving me the solution. However (If it is possible) do you guys know why my App is running AccountActivity first instead of my Mainactivity? (it should run the mainactivity first)?
add .AccountActivity in manifest file as
<activity
android:name=".AccountActivity">
</activity>