I'm studying Android development. I have a problem in LogCat, it seems like it is unable to start settings activity:
05-06 09:40:37.323: E/AndroidRuntime(945): FATAL EXCEPTION: main
05-06 09:40:37.323: E/AndroidRuntime(945): Process: com.androiddevbook.onyourbike_chapter4, PID: 945
05-06 09:40:37.323: E/AndroidRuntime(945): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.androiddevbook.onyourbike_chapter4/com.androiddevbook.onyourbike_chapter5.activities.SettingsActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.app.ActionBar.setDisplayHomeAsUpEnabled(boolean)' on a null object reference
05-06 09:40:37.323: E/AndroidRuntime(945): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2298)
05-06 09:40:37.323: E/AndroidRuntime(945): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360)
05-06 09:40:37.323: E/AndroidRuntime(945): at android.app.ActivityThread.access$800(ActivityThread.java:144)
05-06 09:40:37.323: E/AndroidRuntime(945): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278)
05-06 09:40:37.323: E/AndroidRuntime(945): at android.os.Handler.dispatchMessage(Handler.java:102)
05-06 09:40:37.323: E/AndroidRuntime(945): at android.os.Looper.loop(Looper.java:135)
05-06 09:40:37.323: E/AndroidRuntime(945): at android.app.ActivityThread.main(ActivityThread.java:5221)
05-06 09:40:37.323: E/AndroidRuntime(945): at java.lang.reflect.Method.invoke(Native Method)
05-06 09:40:37.323: E/AndroidRuntime(945): at java.lang.reflect.Method.invoke(Method.java:372)
05-06 09:40:37.323: E/AndroidRuntime(945): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
05-06 09:40:37.323: E/AndroidRuntime(945): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
05-06 09:40:37.323: E/AndroidRuntime(945): Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.app.ActionBar.setDisplayHomeAsUpEnabled(boolean)' on a null object reference
05-06 09:40:37.323: E/AndroidRuntime(945): at com.androiddevbook.onyourbike_chapter5.activities.SettingsActivity.setupActionBar(SettingsActivity.java:48)
05-06 09:40:37.323: E/AndroidRuntime(945): at com.androiddevbook.onyourbike_chapter5.activities.SettingsActivity.onCreate(SettingsActivity.java:40)
05-06 09:40:37.323: E/AndroidRuntime(945): at android.app.Activity.performCreate(Activity.java:5933)
05-06 09:40:37.323: E/AndroidRuntime(945): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1105)
05-06 09:40:37.323: E/AndroidRuntime(945): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2251)
05-06 09:40:37.323: E/AndroidRuntime(945): ... 10 more
Here is class where make intent with function clickedSettings for calling SettingsActivity.class Activity ( in runtime when is clicked Settings on the actionBar on top of the screen) :
package com.androiddevbook.onyourbike_chapter5.activities;
import com.androiddevbook.onyourbike_chapter4.BuildConfig;
import com.androiddevbook.onyourbike_chapter4.R;
import com.androiddevbook.onyourbike_chapter5.model.TimerState;
import android.support.v7.app.ActionBarActivity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.StrictMode;
import android.os.Vibrator;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class TimerActivity extends ActionBarActivity {
private static String CLASS_NAME;
protected TextView counter;
protected Button start;
protected Button stop;
protected Handler handler;
protected UpdateTimer updateTimer;
private static long UPDATE_EVERY = 200;
protected Vibrator vibrate;
protected long lastSeconds;
private TimerState timer;
public TimerActivity(){
CLASS_NAME = getClass().getName();
timer = new TimerState();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_timer);
counter = (TextView) findViewById(R.id.timer);
start = (Button) findViewById(R.id.start_button);
stop = (Button) findViewById(R.id.stop_button);
Log.d(CLASS_NAME, "Setting text.");
if (BuildConfig.DEBUG){
StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder().detectAll().penaltyLog().build());
StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder().detectAll().penaltyLog().penaltyDeath().build());
}
timer.reset();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
Log.d(CLASS_NAME, "Showing menu.");
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
Log.d(CLASS_NAME, "SETTINGS PRESSED.");
System.out.println("Settings pressed.");
clickedSettings(null);
return true;
}
return super.onOptionsItemSelected(item);
}
public void clickedStart(View view){
Log.d(CLASS_NAME, "Clicked start button.");
timer.start();
enableButtons();
handler = new Handler();
updateTimer = new UpdateTimer();
handler.postDelayed(updateTimer, UPDATE_EVERY);
}
public void clickedStop(View view){
Log.d(CLASS_NAME, "Clicked stop button.");
timer.stop();
enableButtons();
handler.removeCallbacks(updateTimer);
updateTimer = null;
handler = null;
}
public void enableButtons(){
Log.d(CLASS_NAME, "Set buttons enabled/disabled.");
start.setEnabled(!timer.isRunning());
stop.setEnabled(timer.isRunning());
}
public class UpdateTimer implements Runnable {
public void run(){
Log.d(CLASS_NAME, "run");
setTimeDisplay();
if ( handler != null){
handler.postDelayed(this, UPDATE_EVERY);
}
if ( timer.isRunning() ){
vibrateCheck();
}
}
}
public void onStart(){
super.onStart();
Log.d(CLASS_NAME, "onStart");
if ( timer.isRunning() ){
handler = new Handler();
updateTimer = new UpdateTimer();
handler.postDelayed(updateTimer, UPDATE_EVERY);
}
vibrate = (Vibrator) getSystemService(VIBRATOR_SERVICE);
if (vibrate == null){
Log.w(CLASS_NAME, "No vibrate service exists.");
}
}
public void onPause(){
super.onPause();
Log.d(CLASS_NAME, "onPause");
}
public void onResume(){
super.onResume();
Log.d(CLASS_NAME, "onResume");
}
public void onStop(){
super.onStop();
Log.d(CLASS_NAME, "onSop");
if ( timer.isRunning() ){
handler.removeCallbacks(updateTimer);
handler = null;
updateTimer = null;
}
}
public void onDestroy(){
super.onDestroy();
Log.d(CLASS_NAME, "onDestroy");
}
public void onRestart(){
super.onRestart();
Log.d(CLASS_NAME, "onRestart");
}
protected void vibrateCheck(){
long diff = timer.elapsedTime();
long seconds = diff / 1000;
long minutes = seconds / 60;
seconds = seconds % 60;
minutes = minutes % 60;
Log.d(CLASS_NAME, "vibrateCheck");
if ( vibrate != null && seconds == 0 && seconds != lastSeconds){
long[] once = { 0, 100 };
long[] twice= { 0, 100, 400, 100};
long[] thrice = { 0, 100, 400, 100, 400, 100 };
// every hour
if ( minutes == 0){
Log.d(CLASS_NAME, "Vibrate 3 times");
vibrate.vibrate(thrice, -1);
}
// every 15 minutes
else if ( minutes % 15 == 0 ){
Log.d(CLASS_NAME, "Vibrate 2 times");
vibrate.vibrate(twice, -1);
}
// every 1 minute
else if ( minutes == 1 ){
Log.d(CLASS_NAME, "Vibrate 1 time");
vibrate.vibrate(once, -1);
}
}
lastSeconds = seconds;
}
public void clickedSettings(View view){
Log.d(CLASS_NAME, "clickedSettings.");
Intent settingsIntent = new Intent(this, SettingsActivity.class);
startActivity(settingsIntent);
}
public void setTimeDisplay(){
Log.d(CLASS_NAME, "setTimeDisplay");
counter.setText(timer.display());
}
}
And here is SettingsActivity class, where keep options for vibrate:
package com.androiddevbook.onyourbike_chapter5.activities;
import com.androiddevbook.onyourbike.chapter5.helpers.Toaster;
import com.androiddevbook.onyourbike_chapter4.R;
import com.androiddevbook.onyourbike_chapter5.OnYourBike;
import com.androiddevbook.onyourbike_chapter5.model.Settings;
import android.support.v7.app.ActionBarActivity;
import android.annotation.TargetApi;
import android.app.ActionBar;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.CheckBox;
public class SettingsActivity extends ActionBarActivity {
private CheckBox vibrate;
private String CLASS_NAME = "dada";
public SettingsActivity(){
Log.d(CLASS_NAME, "SettingsActivity.class....");
CLASS_NAME = getClass().getName();
}
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
private void setupActionBar() {
if ( Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB){
ActionBar actionBar = getActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings);
vibrate = (CheckBox)
findViewById(R.id.vibrate_checkbox);
Settings settings = ((OnYourBike)getApplication()).getSettings();
vibrate.setChecked(settings.isVibrateOn(this));
setupActionBar();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.settings, 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();
if (id == R.id.home) {
goHome();
return true;
}
return super.onOptionsItemSelected(item);
}
private void goHome() {
Log.d(CLASS_NAME, "gotoHome");
Intent timer =
new Intent(this, TimerActivity.class);
timer.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(timer);
}
public void onStop(){
super.onStop();
Settings settings = ((OnYourBike)getApplication()).getSettings();
settings.setVibrate(this, vibrate.isChecked());
}
public void vibrateChanged(View view){
Toaster toast = new Toaster(getApplicationContext());
if(vibrate.isChecked())
toast.make(R.string.vibrate_on);
else
toast.make(R.string.vibrate_off);
}
public void goBack(View view){
finish();
}
}
And finnaly, spec about my virtual telephone:
CPU/ABI: ARM (armeabi-v7a)
Target: Android 5.0.1 ( API level 21)
As you Extends ActionBarActivity so you need to get ActionBar using
ActionBar actionBar = getSupportActionBar();
According to the error log:
05-06 09:40:37.323: E/AndroidRuntime(945): Process: com.androiddevbook.onyourbike_chapter4, PID: 945
05-06 09:40:37.323: E/AndroidRuntime(945): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.androiddevbook.onyourbike_chapter4/com.androiddevbook.onyourbike_chapter5.activities.SettingsActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.app.ActionBar.setDisplayHomeAsUpEnabled(boolean)' on a null object reference
ActionBar actionBar = getActionBar(); line returns a null object.
Reasons:
ActionBarActivity subclasses FragmentActivity which is a support component, change code to ActionBar actionBar = getSupportActionBar();
You might be using a theme like ...Light.NoActionBar, so this due to this also there is no ActionBar present for activities, change theme to a theme that support ActionBar.
Another thing to note, this isn't the reason of this issue but, is that ActionBarActivity is deprecated, use AppCompatActivity from now on.
Your error log says it all:
05-06 09:40:37.323: E/AndroidRuntime(945): Process: com.androiddevbook.onyourbike_chapter4, PID: 945
05-06 09:40:37.323: E/AndroidRuntime(945): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.androiddevbook.onyourbike_chapter4/com.androiddevbook.onyourbike_chapter5.activities.SettingsActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.app.ActionBar.setDisplayHomeAsUpEnabled(boolean)' on a null object reference
You are calling a method on a null object:
actionBar.setDisplayHomeAsUpEnabled(true);
So make sure you do a null check or you might need to use getSupportActionBar
change your setupActionBar method like this:
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
private void setupActionBar() {
if ( Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB){
ActionBar actionBar = getSupportActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
}
}
Related
I'm just trying this library out to see if it fits my needs and so far I have not been able to get it to work. Here is the code
package com.example.user.bottomnavigationbar;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.BottomNavigationView;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.view.MenuItem;
import com.github.mikephil.charting.charts.PieChart;
import com.github.mikephil.charting.data.PieData;
import com.github.mikephil.charting.data.PieDataSet;
import com.github.mikephil.charting.data.PieEntry;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
PieChart pc;
private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener
= new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.navigation_home:
return true;
// case R.id.navigation_overview:
// Intent intentOverview = new Intent(MainActivity.this, activity_test.class);
// intentOverview.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
// MainActivity.this.finish();
// startActivity(intentOverview);
// return true;
case R.id.navigation_expenses:
return true;
case R.id.navigation_reminder:
return true;
case R.id.navigation_income:
return true;
case R.id.navigation_login:
Intent intentLogin = new Intent(MainActivity.this, LoginActivity.class);
intentLogin.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
MainActivity.this.finish();
startActivity(intentLogin);
return true;
}
return false;
}
};
#Override
protected void onCreate(Bundle savedInstanceState)
{
pc = findViewById(R.id.chart);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
BottomNavigationView navigation = findViewById(R.id.navigation);
navigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener);
ArrayList <PieEntry> pieData = new ArrayList<>();
pieData.add(new PieEntry(10));
pieData.add(new PieEntry(20));
pieData.add(new PieEntry(30));
PieDataSet dataSet = new PieDataSet(pieData, "Survey Results");
PieData data = new PieData(dataSet);
pc.setData(data);
}
public void onBackPressed()
{
new AlertDialog.Builder(this)
.setIcon(android.R.drawable.ic_dialog_alert)
.setTitle("Closing Activity")
.setMessage("Are you sure you want to close this activity?")
.setPositiveButton("Yes", new DialogInterface.OnClickListener()
{
#Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
})
.setNegativeButton("No", null)
.show();
}
}
And here is the error I get
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.user.bottomnavigationbar, PID: 4172
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.user.bottomnavigationbar/com.example.user.bottomnavigationbar.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void com.github.mikephil.charting.charts.PieChart.setData(com.github.mikephil.charting.data.ChartData)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2325)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387)
at android.app.ActivityThread.access$800(ActivityThread.java:151)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5254)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void com.github.mikephil.charting.charts.PieChart.setData(com.github.mikephil.charting.data.ChartData)' on a null object reference
at com.example.user.bottomnavigationbar.MainActivity.onCreate(MainActivity.java:78)
at android.app.Activity.performCreate(Activity.java:5990)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1106)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2278)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387)
at android.app.ActivityThread.access$800(ActivityThread.java:151)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5254)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
I've searched for a bit and all I've found was that for others, they did not initialize the object hence it throws this error. Now someone did mention that it is possible to create the chart in code and then add it to the activity as the documentation's Getting Started page suggests but I have been unable to get it working. So what gives?
P.S Left in the code for navigation as I'm not sure if it might be the cause of the issue
You are first finding the view and then providing the content view to your activity replace with this code
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
pc = findViewById(R.id.chart);
BottomNavigationView navigation = findViewById(R.id.navigation);
navigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener);
ArrayList <PieEntry> pieData = new ArrayList<>();
pieData.add(new PieEntry(10));
pieData.add(new PieEntry(20));
pieData.add(new PieEntry(30));
PieDataSet dataSet = new PieDataSet(pieData, "Survey Results");
PieData data = new PieData(dataSet);
pc.setData(data);
}
This question already has answers here:
This Activity already has an action bar supplied by the window decor
(25 answers)
Closed 6 years ago.
while I test my app, I get the follow error in the Android-Studio-Consol:
10-09 20:44:56.685 21573-21573/com.example.android.buyhatke E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.android.buyhatke, PID: 21573
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.android.buyhatke/com.example.android.buyhatke.HomeActivity}: java.lang.IllegalStateException: This Activity already has an action bar supplied by the window decor. Do not request Window.FEATURE_SUPPORT_ACTION_BAR and set windowActionBar to false in your theme to use a Toolbar instead.
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2416)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
at android.app.ActivityThread.-wrap11(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Caused by: java.lang.IllegalStateException: This Activity already has an action bar supplied by the window decor. Do not request Window.FEATURE_SUPPORT_ACTION_BAR and set windowActionBar to false in your theme to use a Toolbar instead.
at android.support.v7.app.AppCompatDelegateImplV7.setSupportActionBar(AppCompatDelegateImplV7.java:198)
at android.support.v7.app.AppCompatActivity.setSupportActionBar(AppCompatActivity.java:130)
at com.example.android.buyhatke.HomeActivity.onCreate(HomeActivity.java:36)
at android.app.Activity.performCreate(Activity.java:6237)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1107)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2369)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
at android.app.ActivityThread.-wrap11(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
10-09 20:49:57.180 26089-26089/com.example.android.buyhatke W/System: ClassLoader referenced unknown path: /data/app/com.example.android.buyhatke-3/lib/x86
10-09 20:49:58.795 26089-26089/com.example.android.buyhatke W/System: ClassLoader referenced unknown path: /data/app/com.example.android.buyhatke-3/lib/x86
10-09 20:49:58.905 26089-26089/com.example.android.buyhatke W/art: Before Android 4.1, method android.graphics.PorterDuffColorFilter android.support.graphics.drawable.VectorDrawableCompat.updateTintFilter(android.graphics.PorterDuffColorFilter, android.content.res.ColorStateList, android.graphics.PorterDuff$Mode) would have incorrectly overridden the package-private method in android.graphics.drawable.Drawable
10-09 20:49:59.023 26089-26089/com.example.android.buyhatke D/AndroidRuntime: Shutting down VM
10-09 20:49:59.023 26089-26089/com.example.android.buyhatke E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.android.buyhatke, PID: 26089
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.android.buyhatke/com.example.android.buyhatke.HomeActivity}: java.lang.IllegalStateException: This Activity already has an action bar supplied by the window decor. Do not request Window.FEATURE_SUPPORT_ACTION_BAR and set windowActionBar to false in your theme to use a Toolbar instead.
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2416)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
at android.app.ActivityThread.-wrap11(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Caused by: java.lang.IllegalStateException: This Activity already has an action bar supplied by the window decor. Do not request Window.FEATURE_SUPPORT_ACTION_BAR and set windowActionBar to false in your theme to use a Toolbar instead.
at android.support.v7.app.AppCompatDelegateImplV7.setSupportActionBar(AppCompatDelegateImplV7.java:198)
at android.support.v7.app.AppCompatActivity.setSupportActionBar(AppCompatActivity.java:130)
at com.example.android.buyhatke.HomeActivity.onCreate(HomeActivity.java:36)
at android.app.Activity.performCreate(Activity.java:6237)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1107)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2369)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
at android.app.ActivityThread.-wrap11(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
My codes are
MainActivity.java
package com.example.android.buyhatke;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import com.facebook.CallbackManager;
import com.facebook.FacebookCallback;
import com.facebook.FacebookException;
import com.facebook.FacebookSdk;
import com.facebook.GraphRequest;
import com.facebook.GraphResponse;
import com.facebook.appevents.AppEventsLogger;
import com.facebook.login.LoginResult;
import com.facebook.login.widget.LoginButton;
import org.json.JSONObject;
public class MainActivity extends AppCompatActivity {
CallbackManager callbackManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//
facebookSDKInitialize();
LoginButton loginButton = (LoginButton) findViewById(R.id.login_button);
loginButton.setReadPermissions("email");
getLoginDetails(loginButton);
}
/*
Initialize the facebook sdk.
And then callback manager will handle the login responses.<br />
*/
protected void facebookSDKInitialize() {
FacebookSdk.sdkInitialize(getApplicationContext());
callbackManager = CallbackManager.Factory.create();
}
/*
Register a callback function with LoginButton to respond to the login result.
On successful login,login result has new access token and recently granted permissions.
*/
protected void getLoginDetails(LoginButton login_button){
// Callback registration<br />
login_button.registerCallback(callbackManager, new FacebookCallback <LoginResult> (){
#Override
public void onSuccess(LoginResult login_result) {
getUserInfo(login_result);
}
#Override
public void onCancel() {
// code for cancellation
}
#Override
public void onError(FacebookException error) {
// code for error handling.
}
});
}
/*To get the facebook user's own profile information via creating a new request.
When the request is completed, a callback is called to handle the success condition. */
protected void getUserInfo(LoginResult login_result){
GraphRequest data_request = GraphRequest.newMeRequest(
login_result.getAccessToken(),
new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted( JSONObject json_object, GraphResponse response) {
Intent intent = new Intent(MainActivity.this,HomeActivity.class);
intent.putExtra("jsondata",json_object.toString());
startActivity(intent);
}
});
Bundle permission_param = new Bundle();
permission_param.putString("fields", "id,name,email,picture.width(120).height(120)");
data_request.setParameters(permission_param);
data_request.executeAsync();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
callbackManager.onActivityResult(requestCode, resultCode, data);
Log.e("data",data.toString());
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
// getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
return super.onOptionsItemSelected(item);
}
#Override
protected void onResume() {
super.onResume();
// Logs 'install' and 'app activate' App Events.
AppEventsLogger.activateApp(this);
}
#Override
protected void onPause() {
super.onPause();
// Logs 'app deactivate' App Event.
AppEventsLogger.deactivateApp(this);
}
}
HomeActivity.java
package com.example.android.buyhatke;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.NavigationView;
import android.support.design.widget.Snackbar;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.squareup.picasso.Picasso;
import org.json.JSONObject;
public class HomeActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {
JSONObject response, profile_pic_data, profile_pic_url;
TextView user_name, user_email;
ImageView user_picture;
NavigationView navigation_view;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setTitle("Home Page"); // may produce null pointer exception
Intent intent = getIntent();
String jsondata = intent.getStringExtra("jsondata");
setNavigationHeader(); // call setNavigationHeader Method.
setUserProfile(jsondata); // call setUserProfile Method
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this,drawer,toolbar,R.string.openDrawer, R.string.closeDrawer);
try {
drawer.setDrawerListener(toggle);
}catch(NullPointerException e)
{
Context context = getApplicationContext();
CharSequence text = "Error";
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
}
toggle.syncState();
navigation_view.setNavigationItemSelectedListener(this);
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
/*
Set Navigation header by using Layout Inflater.<br />
*/
public void setNavigationHeader(){
navigation_view = (NavigationView) findViewById(R.id.nav_view);
View header = LayoutInflater.from(this).inflate(R.layout.nav_header_home, null);
navigation_view.addHeaderView(header);
user_name = (TextView) header.findViewById(R.id.username);
user_picture = (ImageView) header.findViewById(R.id.profile_pic);
user_email = (TextView) header.findViewById(R.id.email);
}
/*
Set User Profile Information in Navigation Bar.<br />
*/
public void setUserProfile(String jsondata){
try {
response = new JSONObject(jsondata);
user_email.setText(response.get("email").toString());
user_name.setText(response.get("name").toString());
profile_pic_data = new JSONObject(response.get("picture").toString());
profile_pic_url = new JSONObject(profile_pic_data.getString("data"));
Picasso.with(this).load(profile_pic_url.getString("url"))
.into(user_picture);
} catch (Exception e){
e.printStackTrace();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.<br />
// getMenuInflater().inflate(R.menu.home, menu);<br />
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {/** check if error*/
return true;
}
return super.onOptionsItemSelected(item);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item){
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id ==R.id.inbox) {
// Handle the camera action
} else if (id ==R.id.starred) {
}
else if (id ==R.id.sent_mail) {
}
else if (id ==R.id.drafts) {
}
else if (id ==R.id.allmail ) {
}
else if (id ==R.id.trash ) {
}
else if (id ==R.id.spam ) {
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
}
can anyone help?
In your styles.xml file, change your theme parent to NoActionBar if you are using Toolbar.
<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
I'm making an app that by now should save and then get the value of a numeric Edit Text. When i put to load data from string.xml it went fine, but when i switched to SharedPreferences it didn't even start. Any help finding the problem would be appreciated. BTW .java is below and i'm sure layout .xml is fine.
package programmingandroidapps.brightnesscustomizationapp;
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.EditText;
import android.widget.TextView;
import android.widget.Button;
import android.util.Log;
import android.content.SharedPreferences;
import android.content.Context;
public class MainActivity extends AppCompatActivity {
//Declarations
String brightnessValue;
int choice, brightnessValueInt;
final EditText mEditText1=(EditText)findViewById(R.id.editText1), mEditText2=(EditText)findViewById(R.id.editText2), mEditText3=(EditText)findViewById(R.id.editText3), mEditText4=(EditText)findViewById(R.id.editText4), mEditText5=(EditText)findViewById(R.id.editText5);
Button mButton1=(Button)findViewById(R.id.button1), mButton2=(Button)findViewById(R.id.button2), mButton3=(Button)findViewById(R.id.button3), mButton4=(Button)findViewById(R.id.button4), mButton5=(Button)findViewById(R.id.button5);
SharedPreferences storedBrightness1 = this.getSharedPreferences("brightv1", Context.MODE_PRIVATE), storedBrightness2 = this.getSharedPreferences("brightv2", Context.MODE_PRIVATE), storedBrightness3 = this.getSharedPreferences("brightv3", Context.MODE_PRIVATE), storedBrightness4 = this.getSharedPreferences("brightv4", Context.MODE_PRIVATE), storedBrightness5 = this.getSharedPreferences("brightv5", Context.MODE_PRIVATE);
SharedPreferences.Editor mEditor;
//
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Get saved brightness values from string.xml and set them to ediText1-5
brightnessValueInt = storedBrightness1.getInt("brightv1", 0);
brightnessIntToString();
printToEditText(1);
brightnessValueInt = storedBrightness2.getInt("brightv2", 0);
brightnessIntToString();
printToEditText(2);
brightnessValueInt = storedBrightness3.getInt("brightv3", 0);
brightnessIntToString();
printToEditText(3);
brightnessValueInt = storedBrightness4.getInt("brightv4", 0);
brightnessIntToString();
printToEditText(4);
brightnessValueInt = storedBrightness5.getInt("brightv5", 0);
brightnessIntToString();
printToEditText(5);
//
// On Click Button Listeners
mButton1.setOnClickListener(
new View.OnClickListener()
{
public void onClick(View view)
{
//Validate >=0 and <=100, paint #222222 if is valid, paint red if not
Log.v(brightnessValue, mEditText1.getText().toString());
mEditor = storedBrightness1.edit();
mEditor.putInt("brightv1", brightnessValueInt);
}
});
//
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public void printToEditText(int choice)
{
if(choice==1)
{
mEditText1.setText(brightnessValue, TextView.BufferType.EDITABLE);
}
else if(choice==2)
{
mEditText2.setText(brightnessValue, TextView.BufferType.EDITABLE);
}
else if(choice==3)
{
mEditText3.setText(brightnessValue, TextView.BufferType.EDITABLE);
}
else if(choice==4)
{
mEditText4.setText(brightnessValue, TextView.BufferType.EDITABLE);
}
else
{
mEditText5.setText(brightnessValue, TextView.BufferType.EDITABLE);
}
}
public void brightnessIntToString()
{
brightnessValue=brightnessValueInt+"";
}
}
I believe this is the applications crash log. I'm new to Android so if it is not just say it, no need to get angry :P
05-01 13:24:53.061 1624-1624/programmingandroidapps.brightnesscustomizationapp D/dalvikvm: Not late-enabling CheckJNI (already on)
05-01 13:24:56.451 1624-1624/programmingandroidapps.brightnesscustomizationapp D/AndroidRuntime: Shutting down VM
05-01 13:24:56.451 1624-1624/programmingandroidapps.brightnesscustomizationapp W/dalvikvm: threadid=1: thread exiting with uncaught exception (group=0xb3d11b20)
05-01 13:24:56.471 1624-1624/programmingandroidapps.brightnesscustomizationapp E/AndroidRuntime:
FATAL EXCEPTION: main
Process: programmingandroidapps.brightnesscustomizationapp, PID: 1624
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{programmingandroidapps.brightnesscustomizationapp/programmingandroidapps.brightnesscustomizationapp.MainActivity}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2110)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2233)
at android.app.ActivityThread.access$800(ActivityThread.java:135)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5001)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at android.app.Activity.findViewById(Activity.java:1884)
at programmingandroidapps.brightnesscustomizationapp.MainActivity.<init>(MainActivity.java:21)
at java.lang.Class.newInstanceImpl(Native Method)
at java.lang.Class.newInstance(Class.java:1208)
at android.app.Instrumentation.newActivity(Instrumentation.java:1061)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2101)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2233)
at android.app.ActivityThread.access$800(ActivityThread.java:135)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5001)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
at dalvik.system.NativeStart.main(Native Method)
The problem is that you are calling findViewById and getSharedPreferences before layout has been applied and the activity (this) was initialized. You should put those method calls in onCreate after setContentView(R.layout.activity_main);.
Dejan is right about moving part of the code into the onCreate lifecycle method, specifically, your code should change to something like this:
package programmingandroidapps.brightnesscustomizationapp;
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.EditText;
import android.widget.TextView;
import android.widget.Button;
import android.util.Log;
import android.content.SharedPreferences;
import android.content.Context;
public class MainActivity extends AppCompatActivity {
//Declarations
String brightnessValue;
int choice, brightnessValueInt;
private EditText mEditText1, mEditText2, mEditText3, mEditText4, mEditText5;
private Button mButton1,mButton2, mButton3, mButton4, mButton5;
private SharedPreferences storedBrightness1, storedBrightness2, storedBrightness3,storedBrightness4,storedBrightness5;
private SharedPreferences.Editor mEditor;
//
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mButton1 =(Button)findViewById(R.id.button1);
mButton2=(Button)findViewById(R.id.button2);
mButton3=(Button)findViewById(R.id.button3);
mButton4=(Button)findViewById(R.id.button4);
mButton5=(Button)findViewById(R.id.button5);
mEditText1 =(EditText)findViewById(R.id.editText1);
mEditText2=(EditText)findViewById(R.id.editText2);
mEditText3=(EditText)findViewById(R.id.editText3);
mEditText4=(EditText)findViewById(R.id.editText4);
mEditText5=(EditText)findViewById(R.id.editText5);
//instead of doing this, I'd rather use "named" SharedPreferences - call it "brightness" and will carry the five values
//something like SharedPreferences brightnessPreferences = this.getSharedPreferences("brightness", Context.MODE_PRIVATE);
//I ma just adding this here because that's the way you have it
storedBrightness1 = this.getSharedPreferences("brightv1", Context.MODE_PRIVATE),
storedBrightness2 = this.getSharedPreferences("brightv2", Context.MODE_PRIVATE),
storedBrightness3 = this.getSharedPreferences("brightv3", Context.MODE_PRIVATE),
storedBrightness4 = this.getSharedPreferences("brightv4", Context.MODE_PRIVATE),
storedBrightness5 = this.getSharedPreferences("brightv5", Context.MODE_PRIVATE);
//Get saved brightness values from string.xml and set them to ediText1-5
brightnessValueInt = storedBrightness1.getInt("brightv1", 0);
brightnessIntToString();
printToEditText(1);
brightnessValueInt = storedBrightness2.getInt("brightv2", 0);
brightnessIntToString();
printToEditText(2);
brightnessValueInt = storedBrightness3.getInt("brightv3", 0);
brightnessIntToString();
printToEditText(3);
brightnessValueInt = storedBrightness4.getInt("brightv4", 0);
brightnessIntToString();
printToEditText(4);
brightnessValueInt = storedBrightness5.getInt("brightv5", 0);
brightnessIntToString();
printToEditText(5);
//
// On Click Button Listeners
mButton1.setOnClickListener(
new View.OnClickListener()
{
public void onClick(View view)
{
//Validate >=0 and <=100, paint #222222 if is valid, paint red if not
Log.v(brightnessValue, mEditText1.getText().toString());
mEditor = storedBrightness1.edit();
mEditor.putInt("brightv1", brightnessValueInt);
}
});
//
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public void printToEditText(int choice)
{
if(choice==1)
{
mEditText1.setText(brightnessValue, TextView.BufferType.EDITABLE);
}
else if(choice==2)
{
mEditText2.setText(brightnessValue, TextView.BufferType.EDITABLE);
}
else if(choice==3)
{
mEditText3.setText(brightnessValue, TextView.BufferType.EDITABLE);
}
else if(choice==4)
{
mEditText4.setText(brightnessValue, TextView.BufferType.EDITABLE);
}
else
{
mEditText5.setText(brightnessValue, TextView.BufferType.EDITABLE);
}
}
public void brightnessIntToString()
{
brightnessValue=brightnessValueInt+"";
}
}
package viewbrosers.mehdi.home.mytestappviewbrowser;
import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
import java.util.Random;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button getAnswer = (Button) findViewById(R.id.getAnswerButton);
getAnswer.setOnClickListener(getAnswerListener);
}
private View.OnClickListener getAnswerListener = new View.OnClickListener() {
#Override
public void onClick(View v) {
Random randomnum = new Random();
int numToast = randomnum.nextInt(19);
numToast++;
CharSequence text = "";
switch (numToast) {
case 1:
text = getString(R.string.answer1);
break;
case 2:
text = getString(R.string.answer2);
break;
case 3:
text = getString(R.string.answer3);
break;
case 4:
text = getString(R.string.answer4);
break;
case 5:
text = getString(R.string.answer5);
break;
case 6:
text = getString(R.string.answer6);
break;
case 7:
text = getString(R.string.answer7);
break;
}
Context context = getApplicationContext();
int duration = Toast.LENGTH_LONG;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
}
};
#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);
}
}
My error is:
Unfortunately Application has stopped and 06-05
11:31:44.131 13711-13711/? I/art﹕ Not late-enabling -Xcheck:jni
(already on) 06-05 11:31:44.208 13711-13711/? D/AndroidRuntime﹕
Shutting down VM 06-05 11:31:44.208 13711-13711/? E/AndroidRuntime﹕
FATAL EXCEPTION: main
Process: viewbrosers.mehdi.home.mytestappviewbrowser, PID: 13711
java.lang.RuntimeException: Unable to start activity ComponentInfo{viewbrosers.mehdi.home.mytestappviewbrowser/viewbrosers.mehdi.home.mytestappviewbrowser.MainActivity}:
java.lang.NullPointerException: Attempt to invoke virtual method
'boolean java.lang.String.equals(java.lang.Object)' on a null object
reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2325)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2390)
at android.app.ActivityThread.access$800(ActivityThread.java:151)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5257)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'boolean java.lang.String.equals(java.lang.Object)' on
a null object reference
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:715)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:806)
at android.view.LayoutInflater.inflate(LayoutInflater.java:504)
at android.view.LayoutInflater.inflate(LayoutInflater.java:414)
at android.view.LayoutInflater.inflate(LayoutInflater.java:365)
at com.android.internal.policy.impl.PhoneWindow.setContentView(PhoneWindow.java:378)
at android.app.Activity.setContentView(Activity.java:2145)
at viewbrosers.mehdi.home.mytestappviewbrowser.MainActivity.onCreate(MainActivity.java:23)
at android.app.Activity.performCreate(Activity.java:5990)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1106)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2278)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2390)
at android.app.ActivityThread.access$800(ActivityThread.java:151)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5257)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698) 06-05
11:31:44.218 13711-13718/? I/art﹕ Debugger is no longer active 06-05
11:32:28.690 13711-13718/viewbrosers.mehdi.home.mytestappviewbrowser
W/art﹕ Suspending all threads took: 12.748ms
Move the creation and initialization of your text variable outside of the onClick() method. Try the following code.
public class MainActivity extends Activity {
CharSequence text;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
text = "";
Button getAnswer = (Button) findViewById(R.id.getAnswerButton);
getAnswer.setOnClickListener(getAnswerListener);
}
private View.OnClickListener getAnswerListener = new View.OnClickListener() {
#Override
public void onClick(View v) {
Random randomnum = new Random();
int numToast = randomnum.nextInt(19);
numToast++;
switch (numToast) {
case 1:
text = getString(R.string.answer1);
break;
case 2:
text = getString(R.string.answer2);
break;
case 3:
text = getString(R.string.answer3);
break;
case 4:
text = getString(R.string.answer4);
break;
case 5:
text = getString(R.string.answer5);
break;
case 6:
text = getString(R.string.answer6);
break;
case 7:
text = getString(R.string.answer7);
break;
}
Context context = getApplicationContext();
int duration = Toast.LENGTH_LONG;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
}
};
#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);
}
}
You are somewhere using equals function on string which is null.
Look at exception: 'boolean java.lang.String.equals(java.lang.Object)' on a null object
reference
Try it, may be like this.
public class MainActivity extends Activity implements OnClickListener
{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button getAnswer = (Button) findViewById(R.id.getAnswerButton);
getAnswer.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch (v.getId())
{
case R.id.getAnswerButton:
//Your code
break;
}
}
}
There is one button I set in Scene2.java.I want to use the button to get in other activities Scene3.java,GameOver.java Everything worked fine until its about to open the new activity,every time the app crashed there. I want to know if there're any mistake I made in the connection,which I mean the newIntent and getIntent inScene2.java GameOver.javaand Scene3.java
Scene2.java
package com.group5.littlered;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
public class Scene2 extends Activity {
MediaPlayer bird;
MediaPlayer bgm;
int position = 0;
String[] conversation;
TextView frame;
ImageView conframe;
final String[] ListStr = { "Wake up and ask her", "Peek her secretly" };
int plot = 0;
#Override
public void onBackPressed() {
}
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
// Remove title bar
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
// Remove notification bar
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_scene2);
Intent intent1 = getIntent();
conversation = getResources().getStringArray(R.array.scene2);
frame = (TextView) findViewById(R.id.textView1);
Button next = (Button) findViewById(R.id.wtf);
next.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (position < 2) {
String sentence = conversation[position];
frame.setText(sentence + "");
position++;
} else {
if (plot < 1) {
AlertDialog choice = new AlertDialog.Builder(
Scene2.this).create();
choice.setTitle("Pick a choice");
choice.setMessage(" ");
choice.setButton("Get up and ask her what happened",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int which) {
// TODO Auto-generated method stub
plot = 1;
}
});
choice.setButton2("Peek her secretly",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int which) {
// TODO Auto-generated method stub
plot = 2;
position = 4;
}
});
choice.show();
} else {
if (plot < 2) {
if (position < 4) {
String sentence = conversation[position];
frame.setText(sentence + "");
position++;
} else {
Intent intent2 = new Intent(Scene2.this,
GameOver.class);
startActivity(intent2);
finish();
}
} else {
if (position < 6) {
String sentence = conversation[position];
frame.setText(sentence + "");
position++;
} else {
Intent intent3 = new Intent(Scene2.this,
Scene3.class);
startActivity(intent3);
finish();
}
}
}
}
}
});
// BGM
bgm = MediaPlayer.create(Scene2.this, R.raw.voyager);
bgm.setLooping(true);
bgm.start();
// bird
bird = MediaPlayer.create(Scene2.this, R.raw.bird);
bird.setLooping(false);
bird.start();
}
}
Scene3.java
package com.group5.littlered;
import android.app.Activity;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
public class Scene3 extends Activity {
int position = 0;
String[] conversation;
TextView frame;
ImageView conframe;
#Override
public void onBackPressed() {
}
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
// Remove title bar
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
// Remove notification bar
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_scene3);
Intent intent3 = getIntent();
conversation = getResources().getStringArray(R.array.scene1);
frame = (TextView) findViewById(R.id.textView1);
Button next = (Button) findViewById(R.id.wtf);
next.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (position < 6) {
String sentence = conversation[position];
frame.setText(sentence + "");
position++;
} else {
{
}
}
}
});
}
}
Again sorry for my poor ENGLISH, plz tell me what I need to post more to help you understand my problem.
my logcat
04-30 09:37:39.497: E/AndroidRuntime(4862): FATAL EXCEPTION: main
04-30 09:37:39.497: E/AndroidRuntime(4862): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.group5.littlered/com.group5.littlered.Scene3}: java.lang.NullPointerException
04-30 09:37:39.497: E/AndroidRuntime(4862): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2211)
04-30 09:37:39.497: E/AndroidRuntime(4862): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2261)
04-30 09:37:39.497: E/AndroidRuntime(4862): at android.app.ActivityThread.access$600(ActivityThread.java:141)
04-30 09:37:39.497: E/AndroidRuntime(4862): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1256)
04-30 09:37:39.497: E/AndroidRuntime(4862): at android.os.Handler.dispatchMessage(Handler.java:99)
04-30 09:37:39.497: E/AndroidRuntime(4862): at android.os.Looper.loop(Looper.java:137)
04-30 09:37:39.497: E/AndroidRuntime(4862): at android.app.ActivityThread.main(ActivityThread.java:5103)
04-30 09:37:39.497: E/AndroidRuntime(4862): at java.lang.reflect.Method.invokeNative(Native Method)
04-30 09:37:39.497: E/AndroidRuntime(4862): at java.lang.reflect.Method.invoke(Method.java:525)
04-30 09:37:39.497: E/AndroidRuntime(4862): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
04-30 09:37:39.497: E/AndroidRuntime(4862): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
04-30 09:37:39.497: E/AndroidRuntime(4862): at dalvik.system.NativeStart.main(Native Method)
04-30 09:37:39.497: E/AndroidRuntime(4862): Caused by: java.lang.NullPointerException
04-30 09:37:39.497: E/AndroidRuntime(4862): at com.group5.littlered.Scene3.onCreate(Scene3.java:45)
04-30 09:37:39.497: E/AndroidRuntime(4862): at android.app.Activity.performCreate(Activity.java:5133)
04-30 09:37:39.497: E/AndroidRuntime(4862): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
04-30 09:37:39.497: E/AndroidRuntime(4862): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2175)
04-30 09:37:39.497: E/AndroidRuntime(4862): ... 11 more
The line that is crashing is the line 45 of Scene3:
Button next = (Button) findViewById(R.id.wtf);
next.setOnClickListener(new View.OnClickListener() { // <-- THIS ONE
...
});
The cause is a NullPointerException. This means that the identifier "wtf" exists in R (this wouldn't compile otherwise) but is not found in the layer activity_scene3, as we wave the following statement line 38 of Scene3.onCreate():
setContentView(R.layout.activity_scene3); // and later on findViewById() returns `null`
You have to revisit this layout to ensure that the Button you are willing to access to actually exists, with the ID wtf.
Generally speaking, this is the danger in using a same ID in different layouts. This is prone to hide errors that would easily be found otherwise as this would just not compile.
Check your manifest file and add Scene3.java in it
<activity
android:name=".Scene3" >
</activity>
Always post question with exception, second this is may be you have not mention your other activity in manifest file like:
<activity
android:name=".Scene3">
</activity>
<activity
android:name=".GameOver">
</activity>