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>
Related
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);
style.xml
<resources>
<!-- 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>
</style>
<style name="AppTheme.NoActionBar">
<item name="windowActionBar">false</item>
<item name="windowNoTitle">true</item>
</style>
<style name="AppTheme.AppBarOverlay" parent="ThemeOverlay.AppCompat.Dark.ActionBar" />
<style name="AppTheme.PopupOverlay" parent="ThemeOverlay.AppCompat.Light" />
</resources>
In my new activities my action bar wont show, im not sure why this is happening. It only appears on the first activity. And it does not appear in any other activities. Im new to android development so this may be anoob question. But its really bothering me. I have included my code for my project. thank you for reading!
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.karanvir.search.MainActivity">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<AutoCompleteTextView
android:id="#+id/autoCompleteTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:layout_marginTop="59dp"
android:text="AutoCompleteTextView" />
<Button
android:id="#+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/autoCompleteTextView"
android:layout_marginLeft="12dp"
android:layout_marginStart="12dp"
android:layout_marginTop="48dp"
android:layout_toEndOf="#+id/progressBar"
android:layout_toRightOf="#+id/progressBar"
android:onClick="jump"
android:text="Button" />
<ProgressBar
android:id="#+id/progressBar"
style="?android:attr/progressBarStyle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true" />
</RelativeLayout>
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/AppTheme.AppBarOverlay">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:popupTheme="#style/AppTheme.PopupOverlay" />
</android.support.design.widget.AppBarLayout>
</android.support.design.widget.CoordinatorLayout>
package com.karanvir.search;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import static com.karanvir.search.MainActivity.urlGlobal;
public class Main2Activity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
//finding webview
WebView webView=(WebView) findViewById(R.id.web1);
//whole bunch of settings you might want to do if you .
//do this because javascript is so wildely used that if you dont use this anywebsites you display wont be displayed properly
webView.getSettings().setJavaScriptEnabled(true);
//this is because on a number of phones if you dont do this it will jump to the devices default browser, and ddisplay the websview their instead.
webView.setWebViewClient(new WebViewClient());
webView.loadUrl("https://www.google.ca/?gws_rd=ssl#q="+urlGlobal);
//reminder ask permission
//you can load content using loaddata
//then add type of data
//then add character encoded were using
}
}
package com.karanvir.search;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import java.util.Random;
public class MainActivity extends AppCompatActivity {
Intent intentGoogle;
Random rn;
SharedPreferences urls;
AutoCompleteTextView searchBar;
public static String urlGlobal;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
searchBar=(AutoCompleteTextView) findViewById(R.id.autoCompleteTextView);
Button button=(Button) findViewById(R.id.button);
rn= new Random();
urls=this.getSharedPreferences("com.karanvir.search", Context.MODE_PRIVATE);
}
#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_settings4) {
Intent intentGoogle= new Intent(getApplicationContext(),Main2Activity.class);
startActivity(intentGoogle);
return true;
} else if(id ==R.id.action_settings2){
Intent intentGoogle= new Intent(getApplicationContext(),Yahoo.class);
startActivity(intentGoogle);
return true;
}else if (id==R.id.action_settings3){
Intent intentGoogle= new Intent(getApplicationContext(),MainActivity.class);
startActivity(intentGoogle);
return true;
}else if(id==R.id.action_settings1){
new AlertDialog.Builder(this)
.setIcon(android.R.drawable.alert_dark_frame)
.setTitle("About")
.setMessage("stuff");
return true;
}
return super.onOptionsItemSelected(item);
}
public void jump(View view){
//intnet changing target of our code
urlGlobal=searchBar.getText().toString();
Log.i("stuff",urlGlobal);
//public static String urlGlobal=
/* urls.edit().putString("url",searchBar.getText().toString()).apply();
String Stringurls=urls.getString("url","");*/
int pageJump = rn.nextInt(3)+1;
if (pageJump==1){
//google
Intent intentGoogle= new Intent(getApplicationContext(),Main2Activity.class);
startActivity(intentGoogle);
} else if (pageJump==2){
//YAHOO
Intent intentGoogle= new Intent(getApplicationContext(),Yahoo.class);
startActivity(intentGoogle);
} else if(pageJump==3){
//GOOGLE
Intent intentGoogle= new Intent(getApplicationContext(),Main2Activity.class);
startActivity(intentGoogle);
}
}
}
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.karanvir.search">
<uses-permission android:name="android.permission.INTERNET"/>
<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=".MainActivity"
android:label="#string/app_name"
android:theme="#style/AppTheme.NoActionBar">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".Main2Activity"
android:label="#string/title_activity_main2"
android:theme="#style/AppTheme.NoActionBar" />
<activity
android:name=".Yahoo"
android:label="#string/title_activity_yahoo"
android:theme="#style/AppTheme.NoActionBar"></activity>
</application>
</manifest>
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.karanvir.search.Main2Activity">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<WebView
android:id="#+id/web1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true" />
</RelativeLayout>
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/AppTheme.AppBarOverlay">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:popupTheme="#style/AppTheme.PopupOverlay" />
</android.support.design.widget.AppBarLayout>
</android.support.design.widget.CoordinatorLayout>
try above in style.xml
<resources>
<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
<!-- Customize your theme here. -->
<item name="colorPrimary">#color/colorPrimary</item>
<item name="colorPrimaryDark">#color/colorPrimaryDark</item>
<item name="colorAccent">#color/colorAccent</item>
</style>
and update your AndroidManifest file like above
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.karanvir.search">
<uses-permission android:name="android.permission.INTERNET"/>
<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=".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>
<activity
android:name=".Main2Activity"
android:label="#string/title_activity_main2"
/>
<activity
android:name=".Yahoo"
android:label="#string/title_activity_yahoo"
></activity>
</application>
Add this in your styles.xml
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
<!-- Customize your theme here. -->
<item name="colorPrimary">#color/grey_400</item>
<item name="colorPrimaryDark">#color/colorPrimaryDark</item>
<item name="colorAccent">#color/colorAccent</item>
</style>
And in your Manifest add this in every Activity
<activity
android:name=".YourActivity"
android:label="#string/title_activity_main2"
android:theme="#style/AppTheme" />
Try this with activity theme as AppTheme.NoActionBar, hope this help you.
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true">
<LinearLayout
android:id="#+id/activity_login"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
>
<android.support.design.widget.AppBarLayout
android:id="#+id/app_bar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:fitsSystemWindows="true"
android:theme="#style/AppTheme.AppBarOverlay">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
app:popupTheme="#style/AppTheme.PopupOverlay">
<TextView
style="#style/Base.TextAppearance.Widget.AppCompat.Toolbar.Title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:text="#string/login_title"
android:textColor="#color/colorPrimary"
/>
</android.support.v7.widget.Toolbar>
</android.support.design.widget.AppBarLayout>
</LinearLayout>
</android.support.design.widget.CoordinatorLayout>
When you are using Android Studio and add a new Activity try:
File -> New -> Activity -> Basic Activity
Then it has the ActionBar configurated by default.
I'm trying to enable the back button in this really simple activity (that is instantiated by another activity), but I always get the null pointer exception and therefore my app crashes when I launch the activity (without the back button in the action bar the activity works great).
I tried many different solution posted in the internet, but none worked...
I'm following this guide : Android Developer providing up navigation
Here the manifest file:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.android.projectcalculator">
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/Theme.AppCompat.Light.NoActionBar"
android:screenOrientation="portrait">
<!--attività principale-->
<activity
android:name=".MainActivity"
android:launchMode="singleInstance">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<!--attività infixToPostfix-->
<activity
android:name=".InfixToPostfixActivity"
android:launchMode="singleTask"
android:label="#string/infix_to_postfix"/>
<!--attività figlia di infixToPostfix-->
<activity
android:name=".ShowPostfixProcedureActivity"
android:launchMode="standard"
android:label="#string/postfix_procedure"
android:parentActivityName=".InfixToPostfixActivity" />
</application>
</manifest>
Here the java file of the activity (ShowPostfixProcedureActivity):
package com.example.android.projectcalculator;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.NavUtils;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.text.Html;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;
import java.util.Stack;
import static java.lang.Character.isDigit;
public class ShowPostfixProcedureActivity extends AppCompatActivity {
private static String equation;
private static int openBracket;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.show_infix_to_postfix_jurney);
Toolbar myToolbar = (Toolbar) findViewById(R.id.infix_to_postfix_toolbar_procedure);
setSupportActionBar(myToolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
TextView txview = (TextView)findViewById(R.id.postfix_jurney_text_wall);
Stack<String> s = new Stack<String>();
s = DataProcessor.ReturnProcess();
txview.setText(s.pop());
while (!s.empty())
{
if (s.peek().charAt(0) == '<')
{
txview.append(Html.fromHtml(s.pop()));
}
else
{
txview.append(s.pop());
}
}
//Log.d("SPPA/onCreate","text = "+DataProcessor.ReturnProcess());
}
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.action_bar_postfix_procedure, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item)
{
switch (item.getItemId()) {
// Respond to the action bar's Up/Home button
case android.R.id.home:
NavUtils.navigateUpFromSameTask(this);
return true;
}
return super.onOptionsItemSelected(item);
}
}
The XML file related to the layout (show_infix_to_postfix_jurney):
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<!--ActionBar in alto-->
<android.support.v7.widget.Toolbar
android:id="#+id/infix_to_postfix_toolbar_procedure"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="#42f480"
android:elevation="4dp"
android:theme="#style/ThemeOverlay.AppCompat.ActionBar"
app:popupTheme="#style/ThemeOverlay.AppCompat.Light"/>
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scrollbars="vertical">
<TextView
android:id="#+id/postfix_jurney_text_wall"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="10sp"
android:textSize="20sp"
android:gravity="center"
android:background="#f2f2f2"/>
</ScrollView>
</LinearLayout>
And finally the XML file related to the Navigation bar (action_bar_postfix_procedure):
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
</menu>
Here the error message:
10-29 17:14:43.841 18822-18822/com.example.android.projectcalculator E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.android.projectcalculator, PID: 18822
Theme: themes:{}
java.lang.NullPointerException: Attempt to invoke interface method 'android.view.MenuItem android.view.MenuItem.setEnabled(boolean)' on a null object reference
at com.example.android.projectcalculator.ShowPostfixProcedureActivity.onCreateOptionsMenu(ShowPostfixProcedureActivity.java:51)
at android.app.Activity.onCreatePanelMenu(Activity.java:2852)
at android.support.v4.app.FragmentActivity.onCreatePanelMenu(FragmentActivity.java:340)
at android.support.v7.view.WindowCallbackWrapper.onCreatePanelMenu(WindowCallbackWrapper.java:85)
at android.support.v7.app.AppCompatDelegateImplBase$AppCompatWindowCallbackBase.onCreatePanelMenu(AppCompatDelegateImplBase.java:258)
at android.support.v7.view.WindowCallbackWrapper.onCreatePanelMenu(WindowCallbackWrapper.java:85)
at android.support.v7.app.ToolbarActionBar.populateOptionsMenu(ToolbarActionBar.java:454)
at android.support.v7.app.ToolbarActionBar$1.run(ToolbarActionBar.java:61)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5461)
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)
I don't know what the line NavUtils.navigateUpFromSameTask(this); is supposed to do. If you want to close the activity on the press of the back button replace it with the method call onBackPressed()
#Override
public boolean onOptionsItemSelected(MenuItem item)
{
switch (item.getItemId()) {
// Respond to the action bar's Up/Home button
case android.R.id.home:
onBackPressed()
return true;
}
return super.onOptionsItemSelected(item);
}
I am making an android project by targetting api 13+. I need to have a appbar/toolbar instead of actionbar at the top of each activity I have in my app. I have tried searching over many blogs and SO itself but without any success.
I have created a base activity class and all my activities inherit from this class:
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.support.v7.widget.Toolbar;
public class BaseActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Toolbar tb = (Toolbar) findViewById(R.id.appToolbar);
setSupportActionBar(tb);
getSupportActionBar().setDisplayShowTitleEnabled(true);
getSupportActionBar().setTitle("oh yeah");
}
...
}
I have done the housekeeping stuff for the toolbar in this class and the following class is the activity which shows up when the app is launched:
import android.app.Activity;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.WindowManager;
public class SplashScreen extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// api level < 16 and > 16 have different
// ways of removing the status bar
if(Build.VERSION.SDK_INT < 16) {
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
} else {
View decorView = getWindow().getDecorView();
decorView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN);
}
setContentView(R.layout.activity_splash_screen);
// Create a new thread and delay for 3 sec
// to handle the start of the main screen.
Handler h = new Handler();
h.postDelayed(new Runnable() {
#Override
public void run() {
Intent i = new Intent().setClass(getApplicationContext(), MainScreen.class);
startActivity(i);
}
}, 3000);
}
And this is the activity which is launched after the splash screen:
import android.content.Intent;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageButton;
public class MainScreen extends BaseActivity {
private ImageButton btnLoyaltyForm;
private ImageButton btnFeedbackForm;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_screen);
btnLoyaltyForm = (ImageButton) findViewById(R.id.btnLoyaltyForm);
btnFeedbackForm = (ImageButton) findViewById(R.id.btnFeedbackForm);
btnLoyaltyForm.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent().setClass(getApplicationContext(), LoyaltyFormScreen.class);
startActivity(i);
}
});
btnFeedbackForm.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent().setClass(getApplicationContext(), FeedbackFormScreen.class);
startActivity(i);
}
});
}
}
Here is the XML for my appbar:
<android.support.v7.widget.Toolbar
android:id="#+id/app_bar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="#color/actionbar_background_color"
android:minHeight="?attr/actionBarSize"
xmlns:android="http://schemas.android.com/apk/res/android" />
Here is the XML for my MainScreen activity:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin" tools:context="com.tarz.MainScreen">
<LinearLayout
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true">
<include
android:id="#+id/appToolbar"
layout="#layout/app_bar" />
</LinearLayout>
<LinearLayout
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignParentRight="false"
android:layout_alignParentBottom="false"
android:layout_alignWithParentIfMissing="false"
android:gravity="center">
<ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/btnLoyaltyForm"
android:layout_gravity="center_horizontal"
android:src="#drawable/btn_form1" />
<ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/btnFeedbackForm"
android:layout_gravity="center"
android:src="#drawable/btn_form2" />
</LinearLayout>
</RelativeLayout>
Here is my app's manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.tarz" >
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".SplashScreen"
android:label="#string/title_activity_splash_screen" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".MainScreen"
android:label="#string/title_activity_main_screen" >
</activity>
<activity
android:name=".BaseActivity"
android:label="#string/title_activity_base" >
</activity>
</application>
</manifest>
Here is my colors.xml:
n="1.0" encoding="utf-8"?>
<resources>
<color name="actionbar_background_color">#2d3135</color>
<color name="actionbar_text_color">#ffffff</color>
<color name="app_background_color">#f7f6f0</color>
<color name="button_background_color">#2d3135</color>
<color name="button_text_color">#ffffff</color>
</resources>
Here is my styles.xml:
<resources xmlns:tools="http://schemas.android.com/tools" xmlns:android="http://schemas.android.com/apk/res/android">
<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
<!-- Customize your theme here. -->
<item name="android:background">#color/app_background_color</item>
<!--<item name="colorPrimaryDark">#color/colorPrimaryDark</item>-->
<!--<item name="colorAccent">#color/colorAccent</item>-->
</style>
<style name="ActionBarTheme" parent="ThemeOverlay.AppCompat.ActionBar">
<item name="android:background">#color/actionbar_background_color</item>
<item name="colorPrimary">#color/actionbar_background_color</item>
</style>
</resources>
When I run the app, the splash screen shows up then it crashes with the following error:
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.v7.app.ActionBar.setDisplayShowTitleEnabled(boolean)' on a null object reference
And
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.v7.app.ActionBar.setDisplayShowTitleEnabled(boolean)' on a null object reference
This is the log:
4059-4059/com.tarz E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.tarz, PID: 4059
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.tarz/com.tarz.MainScreen}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.v7.app.ActionBar.setDisplayShowTitleEnabled(boolean)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2416)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
at android.app.ActivityThread.-wrap11(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.v7.app.ActionBar.setDisplayShowTitleEnabled(boolean)' on a null object reference
at com.tarz.MainScreen.onCreate(MainScreen.java:28)
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)
How do I use the colors I have defined in my colors.xml so that my toolbar could have a different color, my app could have a different color and my toolbar's text could have a different color.
Also, menu on each activity would be different so the toolbar should adjust according to the activity, how could I do that also?
Please help, thanks. :)
EDIT 1:
After #Rod said to initialize toolbar after setting contentView, it cleared the NPE but then no toolbar is being shown:
This method is added at the top of the BaseActivity class:
public void initToolbar() {
Toolbar tb = (Toolbar) findViewById(R.id.appToolbar);
setSupportActionBar(tb);
getSupportActionBar().setDisplayShowTitleEnabled(true);
getSupportActionBar().setTitle("oh yeah");
}
and the onCreate now just have the super call. Also, the MainScreen class now have the initToolbar(); called after setContentView(); in onCreate(); method.
A couple of things I would point out:
You are not inflating a layout in your onCreate() in BaseActivity.
I think the official Toolbar tutorials are all using AppCompatActivity instead of ActionBarActivity.
You could define different Toolbar themes and apply them in different activities. More info here.
Each activity has it's own toolbar, so you don't have to worry about supporting different menus for each activity. You simply inflate the menu XML for the activity in onCreateOptionsMenu().
EDIT 1: Inflating the appropriate layout in the base activity:
public abstract class BaseActivity extends AppCompatActivity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(getLayoutResId());
final Toolbar toolbar = findViewById(<your toolbar id>);
// the rest of your logic
}
// This abstract method will provide a way for extending activities to give the id of their layout, so you can inflate it, before trying to set the toolbar
#LayoutRes
protected abstract getLayoutResId();
}
EDIT 2: Customising the toolbar
The Toolbar, like every other widget, can be customised using styles. To control the toolbar background colour, spacing, etc, you need to set a custom style to it. You can also change the toolbar title and subtitle appearance using the same mechanism. Here is a great link that shows all you need to know about creating and applying custom toolbar styles.
I am up to the "Start Another Activity" section of the Android tutorial and it simply won't work when I install and test it.
It compiles fine but running it breaks after I click the send button.
I am using the command line tools on Ubuntu 12.04 and installing to a real device, my Galaxy S5.
I am aware of logcat but haven't been able to get it working, it either shows no output at all, or gives a massive spam of output I can't keep up with. I would happily provide logcat information if I could manage to isolate my app's output and cut through everything else.
I have seen a lot of similar questions on this which leads me to believe the tutorial isn't very well written.
Here is "MyActivity.java"
package com.example.myfirstapp;
import android.app.Activity;
import android.os.Bundle;
import android.content.Intent;
import android.widget.EditText;
import android.view.View;
public class MyActivity extends Activity
{
public final static String EXTRA_MESSAGE = "com.mycompany.myfirstapp.MESSAGE";
/** Called when the activity is first created */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
/** Called when the user clicks the send button */
public void sendMessage(View view)
{
Intent intent = new Intent(this, DisplayMessageActivity.class);
EditText editText = (EditText) findViewById(R.id.edit_message);
String message = editText.getText().toString();
intent.putExtra(EXTRA_MESSAGE, message);
startActivity(intent);
}
}
Here is DisplayMessageActivity
package com.example.myfirstapp;
import android.app.Activity;
import android.os.Bundle;
import android.content.Intent;
import android.support.v7.app.*;
import android.view.*;
import android.widget.*;
import com.example.myfirstapp.R;
public class DisplayMessageActivity extends ActionBarActivity
{
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
//Get the message from intent
Intent intent = getIntent();
String message = intent.getStringExtra(MyActivity.EXTRA_MESSAGE);
//Create the text view
TextView textView = new TextView(this);
textView.setTextSize(40);
textView.setText(message);
//Set the text view as the activity layout
setContentView(textView);
}
}
Here is AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.myfirstapp"
android:versionCode="1"
android:versionName="1.0">
<application android:label="#string/app_name" android:icon="#drawable/ic_launcher">
<activity
android:name="MyActivity"
android:label="#string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name="com.example.myfirstapp.DisplayMessageActivity"
android:label="#string/title_activity_display_message"
android:parentActivityName="com.example.myfirstapp.MyActivity">
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value="com.example.myfirstapp.MyActivity"
/>
</activity>
</application>
</manifest>
EDIT: Here is Main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<EditText android:id="#+id/edit_message"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:hint="#string/edit_message"
/>
<Button
android:layout_weight="1"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:text="#string/button_send"
android:onClick="sendMessage"
/>
</LinearLayout>
There was some code that I changed and took out as it said to add code in, but then would later show a "this is what your code should look like" and it was missing some of the original code. I also changed the manifest package names in the activities because at the beginning it uses com.example.myfirstapp but later uses com.mycompany.myfirstapp
Any help or advice on why this seemingly simple tutorial doesn't work is greatly appreciated.
EDIT:
Logcat output - (after pressing the send button)
I/Timeline( 3812): Timeline: Activity_launch_request id:com.example.myfirstapp time:74636924
D/AndroidRuntime( 3812): Shutting down VM
E/AndroidRuntime( 3812): FATAL EXCEPTION: main
E/AndroidRuntime( 3812): Process: com.example.myfirstapp, PID: 3812
E/AndroidRuntime( 3812): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.myfirstapp/com.example.myfirstapp.DisplayMessageActivity}: java.lang.IllegalStateException: You need to use a Theme.AppCompat theme (or descendant) with this activity.
E/AndroidRuntime( 3812): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2658)
E/AndroidRuntime( 3812): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2725)
E/AndroidRuntime( 3812): at android.app.ActivityThread.access$900(ActivityThread.java:172)
E/AndroidRuntime( 3812): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1422)
E/AndroidRuntime( 3812): at android.os.Handler.dispatchMessage(Handler.java:102)
E/AndroidRuntime( 3812): at android.os.Looper.loop(Looper.java:145)
E/AndroidRuntime( 3812): at android.app.ActivityThread.main(ActivityThread.java:5834)
E/AndroidRuntime( 3812): at java.lang.reflect.Method.invoke(Native Method)
E/AndroidRuntime( 3812): at java.lang.reflect.Method.invoke(Method.java:372)
E/AndroidRuntime( 3812): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1388)
E/AndroidRuntime( 3812): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1183)
E/AndroidRuntime( 3812): Caused by: java.lang.IllegalStateException: You need to use a Theme.AppCompat theme (or descendant) with this activity.
E/AndroidRuntime( 3812): at android.support.v7.app.ActionBarActivityDelegate.onCreate(ActionBarActivityDelegate.java:151)
E/AndroidRuntime( 3812): at android.support.v7.app.ActionBarActivityDelegateBase.onCreate(ActionBarActivityDelegateBase.java:138)
E/AndroidRuntime( 3812): at android.support.v7.app.ActionBarActivity.onCreate(ActionBarActivity.java:123)
E/AndroidRuntime( 3812): at com.example.myfirstapp.DisplayMessageActivity.onCreate(DisplayMessageActivity.java:16)
E/AndroidRuntime( 3812): at android.app.Activity.performCreate(Activity.java:6221)
E/AndroidRuntime( 3812): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1119)
E/AndroidRuntime( 3812): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2611)
E/AndroidRuntime( 3812): ... 10 more
I/Process ( 3812): Sending signal. PID: 3812 SIG: 9
I/ActivityManager( 871): Process com.example.myfirstapp (pid 3812)(adj 13) has died(104,205)
Here's the working code :
MainActivity.class
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
public class MainActivity extends ActionBarActivity {
EditText et;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
et = (EditText) findViewById(R.id.editText1);
}
public void Go(View v)
{
Log.d("check", "Pressed");
String value = et.getText().toString();
Intent intent = new Intent(MainActivity.this, SecondActivity.class);
intent.putExtra("key", value);
startActivity(intent);
}
}
SecondActivity.class
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.widget.TextView;
public class SecondActivity extends ActionBarActivity {
TextView textv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.new_activity);
String txt = getIntent().getStringExtra("key");
Log.d("check", "got : " +txt);
textv = (TextView) findViewById(R.id.textView1);
textv.setText(txt);
}
}
res/layout/activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android: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.testproject.MainActivity" >
<EditText
android:id="#+id/editText1"
android:layout_width="wrap_content"
android:layout_height="40dp"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="67dp"
android:layout_marginTop="46dp"
android:ems="10" />
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:onClick="Go"
android:text="Button" />
</RelativeLayout>
res/layout/new_activity.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="74dp"
android:text="Large Text"
android:textAppearance="?android:attr/textAppearanceLarge" />
</RelativeLayout>
AndroidManifest.xml
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<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>
<activity android:name=".SecondActivity"></activity> // Registered the newly created activity
</application>
Output :
Logcat :
BY SEEING YOUR LOGCAT, I got there is a problem in your Theme.
You didn't declared AppTheme in AndroidManifest.xml file
android:theme="#style/AppTheme"
Try by This Sample Code I have made For You.
mainactivity.xml Code
<EditText
android:id="#+id/edtMessage"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:hint="message"
/>
<Button
android:id="#+id/btnSend"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Send"
/>
MainActivity.class
Button btnSend;
EditText edtMessage;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
edtMessage=(EditText)findViewById(R.id.edtMessage);
btnSend=(Button)findViewById(R.id.btnSend);
btnSend.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
String Message=edtMessage.getText().toString();
Intent intent=new Intent(getApplicationContext(),Second.class);
intent.putExtra("Message", Message);
startActivity(intent);
}
});
}
second.xml
<TextView
android:id="#+id/tviMessage"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#000000"
/>
Second.class
TextView tviMessage;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.second);
tviMessage=(TextView)findViewById(R.id.tviMessage);
Bundle extras = getIntent().getExtras();
String message = extras.getString("Message");
tviMessage.setText(message);
}
Manifesto.xml
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<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>
<activity
android:name=".Second"
android:label="#string/app_name" >
</activity>
By using logcat with this command:
adb logcat | grep `adb shell ps | grep com.example.myfirstapp | cut -c10-15`
I was able to find the error causing the app to crash. It came from missing the line:
android:theme="#style/Theme.AppCompat.Light"
In the Manifest.xml file. This is required by the Activity bar compatibility class. This part was completely overlooked in the tutorial, presumably because IDEs do this part automatically.
Thank you to everybody for their help and suggestions, it helped me keep looking and trying things until I finally found my solution.