Android: My app crashes on startup [duplicate] - java

This question already has answers here:
Android 1.6: "android.view.WindowManager$BadTokenException: Unable to add window -- token null is not for an application"
(16 answers)
Closed 5 years ago.
Whenever I launch my activity it crashes. I don't know what the problem is. My code, xml resources and Android manifest looks fine. If anyone could
help me that would be appreciated!
The issue is caused by a android.view.WindowManager$BadTokenException, which is mentioned in the LogCat
Java Code
package com.example.hp.machine;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
public class Machine extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.machine);
Button click = (Button) findViewById(R.id.click);
click.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AlertDialog.Builder builder = new AlertDialog.Builder(Machine.this);
builder.setTitle("Warning")
.setIcon(R.drawable.bomb)
.setMessage("Do you want to Die ?")
.setCancelable(false) ;
AlertDialog alert = builder.create();
alert.show();
}
});
}
}
XML
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/machine"
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.hp.machine.Machine"
android:background="#drawable/splash_screen"
>
<Button
android:layout_height="wrap_content"
android:layout_width="130dp"
android:text="click"
android:layout_marginTop="200dp"
android:id="#+id/click"
android:textColor="#android:color/white"
android:textStyle="bold"
android:fontFamily="serif"
android:background="#android:color/background_dark"
/>
</RelativeLayout>
Manifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.hp.machine">
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".Machine">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
LogCat
Caused by: android.view.WindowManager$BadTokenException: Unable to add window -- token null is not for an application
at android.view.ViewRootImpl.setView(ViewRootImpl.java:789)
at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:298)
at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:91)
at android.app.Dialog.show(Dialog.java:325)
at com.example.hp.machine.Machine.onCreate(Machine.java:46)
at android.app.Activity.performCreate(Activity.java:6609)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1134)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3113)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3275) 
at android.app.ActivityThread.access$1000(ActivityThread.java:218) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1744) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:145) 
at android.app.ActivityThread.main(ActivityThread.java:7007) 
at java.lang.reflect.Method.invoke(Native Method) 
at java.lang.reflect.Method.invoke(Method.java:372) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1404)  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1199) 
07-19 17:13:23.830 28841-28841/com.example.hp.machine I/Process: Sending signal. PID: 28841 SIG: 9

You can not write AlertDialog in onCreate() method.
Replace it at onResume() method.

Change the getBaseContext() to Machine.this
package com.example.hp.machine;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
public class Machine extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.machine);
Button click = (Button) findViewById(R.id.click);
AlertDialog.Builder builder = new AlertDialog.Builder(Machine.this);
builder.setTitle("Warning")
.setIcon(R.drawable.bomb)
.setMessage("Do you want to Die ?")
.setCancelable(false) ;
AlertDialog alert = builder.create();
alert.show();
}
}

I assume the space in AppCompatActivity (the extend part) is an SO import issue.
You use getBaseContext, when you should reference the context to the current object:
AlertDialog.Builder builder = new AlertDialog.Builder(Machine.this
/*Inside nested classes, this refers to that class. This is just good practice to do even
if you aren't inside a nested class/thread*/);
When showing dialogs, you need to do it:
On the UI thread
With the application context
Using outside the UI thread ends up with leaked window.
Just saw now, you run on a different thread.
Inside the onClick method, you add this:
runOnUiThread(new Runnable() {
#Override
public void run() {
//Add your dialog code here
}
});
and add the dialog code inside.

One thing I do not understand how come onClick get called while activity is being created.
onClick should be called on clicking event.

Related

How to fix WebView app giving "App Keeps Stopping" error after installing?

I have a web view app that works perfectly fine on most android phones, but while testing, some said that the app even won't open for the first time after installation.
It keeps on showing the error as below :
"Keeps Stopping"
And in some mobile devices, it says "Runtime Exception" and crashes without even opening.
This was a debug APK, so in an attempt of trying to fix it, I even generated a signed APK. Still no luck.
Here is my whole Code:
Activity Main.XML
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<WebView
android:layout_width="match_parent"
android:id="#+id/webviewid"
android:layout_height="match_parent"
android:overScrollMode="never"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent">
</WebView>
</RelativeLayout>
AndroidManifest.Xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.xxxxxxxxxxxxx;">
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" ></uses-permission>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" ></uses-permission>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"></uses-permission>
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_roundffd"
android:supportsRtl="true"
android:theme="#style/Theme_xxxxxx"
android:configChanges="keyboard|keyboardHidden|orientation|screenLayout|uiMode|screenSize|smallestScreenSize">
<activity
android:name=".MainActivity"
android:windowSoftInputMode="adjustResize"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Mainactivity.java
package com.xxxxxxxxxxxxx;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import android.content.DialogInterface;
import android.graphics.Bitmap;
import android.accessibilityservice.AccessibilityService;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;
import android.os.Handler;
import android.webkit.GeolocationPermissions;
import android.webkit.WebChromeClient;
import android.content.Context;
import android.net.ConnectivityManager;
public class MainActivity extends AppCompatActivity {
private WebView webView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
webView = findViewById(R.id.webviewid);
webView.setWebViewClient(new WebViewClient());
webView.loadUrl("https://www.some.com/");
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
webView.getSettings().setDomStorageEnabled(true);
webView.getSettings().setGeolocationEnabled(true);
webView.setWebChromeClient(new WebChromeClient() {
public void onGeolocationPermissionsShowPrompt(String origin, GeolocationPermissions.Callback callback) {
callback.invoke(origin, true, false);
}
});
}
// On double back press stuff starts --------------------------------------------------
private boolean doubleBackToExitPressedOnce = false;
#Override
protected void onResume() {
super.onResume();
// .... other stuff in my onResume ....
this.doubleBackToExitPressedOnce = false;
}
#Override
public void onBackPressed() {
if (doubleBackToExitPressedOnce) {
super.onBackPressed();
return;
}
if(webView.canGoBack()){
webView.goBack();
}
}
}
Please note that the app works completely fine, It installs and opens with no issues, but when it comes to some phones, I am getting this "Keeps Stopping" error.
As per some blogs, I even tried uninstalling updates from the Android Web View setting, yet still no use.
Any help or suggestion is greatly appreciated.
can you remove the 'smallestscreensize' in android:configChanges in manifest file and let us know.

"Button button1 = (Button)findViewById(R.id.button_1) " goes run in Android [duplicate]

This question already has answers here:
What does a "Cannot find symbol" or "Cannot resolve symbol" error mean?
(18 answers)
Closed 10 months ago.
I'm a beginner in Android , so please pardon my ignorance.
As I was learning Android programming,I followed the book and the codes are as follows:
FirstActivity.java
package com.example.activitytest;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;
public class FirstActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.first_layout);
Button button1 = (Button)findViewById(R.id.button_1);
button1.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
Toast.makeText(FirstActivity.this, "You clicked Button 1", Toast.LENGTH_SHORT).show();
}
});
}
}
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.activitytest">
<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.Activitytest">
<activity
android:name=".FirstActivity"
android:label="This is FirstActivity"
android:exported="true">
<intent-filter>
<action android:name = "android.intent.action.MAIN"/>
<category android:name = "android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
</application>
</manifest>
first_layout.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:id="#+id/button_1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/button_1"
tools:ignore="MissingConstraints"
tools:layout_editor_absoluteX="0dp"
tools:layout_editor_absoluteY="1dp" />
</androidx.constraintlayout.widget.ConstraintLayout>
And android studio reports that:
error: cannot find symbol
Button button1 = (Button)findViewById(R.id.button_1);
^
symbol: class Button
location: class FirstActivity
and then I search stackoverflow to find the method to debug.
I once tried this method:
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
Button buttonClick = (Button)rootView.findViewById(R.id.button);
buttonClick.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
onButtonClick((Button) view);
}
});
But it still does not work.As I am just a beginner, I can't find a way to debug.
Can someone help me? Thank you for that.
As I can see in your code that in xml you have assigned the id to the button which is
android:id="#+id/button_1"
but you are trying to access the wrong id here
Button buttonClick = (Button)rootView.findViewById(R.id.button);
and if you are in activity there is no need of rootView you can simply access the button with findViewById(R.id.button_1)
Also it is missing in your first_layout.xml
tools:context=".FirstActivity"
add this to the constraintLayout in xml
also add import
import android.widget.Button;
And I will suggest you to use viewBinding it will help you a lot in this case
add this line
import android.widget.Button;
FirstActivity.java
package com.example.activitytest;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;
import android.widget.Button;
public class FirstActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.first_layout);
Button button1 = (Button)findViewById(R.id.button_1);
button1.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
Toast.makeText(FirstActivity.this, "You clicked Button 1", Toast.LENGTH_SHORT).show();
}
});
}
}

Button does nothing

I am trying to make a button that goes from activity 2 to activity 3.
I already made a button that goes from activity 1 to 2 and that worked perfectly. When I press the button in the app it does nothing. This is my code so far.
This is Main2Activity.java
import android.app.Activity;
import android.content.Intent;
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.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
public class Main2Activity extends Activity {
Button button;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
button = (Button) findViewById(R.id.btnRemote);
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent myIntent = new Intent(Main2Activity.this, Main3Activity.class);
startActivity(myIntent);
}
});
}
}
And this is my activity_main2.xml
<android.support.constraint.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"
tools:context="uk.co.ndevr.evewebapp20.Main2Activity">
<Button
android:id="#+id/btnRemote"
style="#style/Widget.AppCompat.Button.Colored"
android:layout_width="164dp"
android:layout_height="45dp"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:layout_marginBottom="8dp"
android:layout_marginEnd="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:backgroundTint="#color/colorPrimary"
android:text="TV Remote"
android:textStyle="bold"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.082"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.013" />
</android.support.constraint.ConstraintLayout>
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="uk.co.ndevr.evewebapp20">
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<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">
<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" />
<activity
android:name=".Main3Activity"
android:label="#string/title_activity_main3"
android:theme="#style/AppTheme"></activity>
</application>
</manifest>
Main3Activity.java
import android.app.Activity;
import android.content.Intent;
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.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
public class Main3Activity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main3);
}
}
You are never actually switching to MainActivity2 in the first Activity.
Calling setContentView() only changes the layout file inflated for the current Activity. This means, you have never called Activity2 so the onCreate() of your 2nd Activity is never called and the OnClickListener for that button is never registered.
In your onClick() of your first Activity, change from calling setContentView() (you almost never want to do this more than once in an Activity) to using an Intent as you are doing in the second Activity.
The issse is that, as you've said in the comment, you used
public void onClickLogin(View view) {
setContentView(R.layout.activity_main2);
}
to go from activity 1 to activity 2. That simply changed the layout on activity 1 with the one from activity 2. In other words, you're still in activity 1 (that looks like activity 2), while the onClickListener for btnRemote is only defined in activity 2.

Appbar/Toolbar not working

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.

startActivity() causing crash in Android

So I just started learning to develop Android apps, and I have a programming background (Python mainly), so I somewhat know what I'm doing. I'm having a problem with using startActivity(). I've commented code to figure out exactly where the error gets thrown, and it happens right as startActivity() is encountered. The error I get is from the emulator and it is just a popup window that says, "Unfortunately, Test has stopped." (Test is my program name) after I click my button. My code is this
package com.test.test;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
public class TestActivity extends Activity {
public final static String EXTRA_MESSAGE = "com.test.test.MESSAGE";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
public class DisplayMessageActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
}
}
public void sendMessage(View view) {
setContentView(R.layout.main);
Intent intent = new Intent(this, DisplayMessageActivity.class);
EditText editText = (EditText) findViewById(R.id.textBox1);
String message = editText.getText().toString();
intent.putExtra(EXTRA_MESSAGE, message);
startActivity(intent);
}
}
Now I know that won't do anything yet, but why is it crashing?
My XML:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="horizontal" >
<EditText android:id="#+id/textBox1"
android:layout_weight="1"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:hint="#string/textBox1Hint" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/button1"
android:onClick="sendMessage" />
</LinearLayout>
My manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.test.test"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk android:minSdkVersion="15" />
<application
android:icon="#drawable/ic_launcher"
android:label="#string/app_name" >
<activity
android:name=".TestActivity"
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=".DisplayMessageActivity" >
</activity>
</application>
</manifest>
I saw that a lot of other people were having problems with this because they had not declared their activities in the manifest, but I think I have done so properly. Any help would be so greatly appreciated.
One possible problem is that
EditText editText = (EditText) findViewById(R.id.textBox1);
returns null because you dont set anywhere the layout for your activity (with setContentView)
If your editetext is included in view (passed to sendMessage), you can find it with
EditText editText = (EditText) view.findViewById(R.id.textBox1);
I think problem is you are on DisplayMessageActivity and starting the same activity.
What you need to do is start test activity and call DisplayMessageActivity from intent.
Use separate files for TestActivity and DisplayMessageActivity classes. In your given code you are not specifying a layout for your DisplayMessageActivity activity using setContentView.
the problem is this,
you declare in the manifest that the main class is TestActivity:
<activity
android:name=".TestActivity"
android:label="#string/app_name" >
but you wanted to start DisplayMessageActivity,
so, change this to the following:
public class TestActivity extends Activity {
#Override
I can't understand what you are actually trying to achieve by starting the same activity again. Try this,
public class DisplayMessageActivity extends Activity {
private String message ;
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setLayout(R.layout.<name of the xml file> ); // change the name if it is not in layout folder
EditText editText = (EditText) findViewById(R.id.textBox1);
String message = editText.getText().toString();
Button submitBtn = (Button) findViewById(R.id.button1);
submitBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Toast toast = Toast.makeText(DisplayMessageActivity.this,
message,
Toast.LENGTH_SHORT);
toast.show();
}});
}
}
The above code simply displays the String, This is just a sample code... Hope that helps!!!
EDIT
To run this code you must also add id tag to your Button Tag inside XML file having value button1..
Actullay you have created the Activity inside activity. Which is not much pref-able but if want to stick with that then you have to change the android:name=".DisplayMessageActivity" to

Categories

Resources