App works on emulator but not real device - java

I just uploaded my app to google play and then installed it on my android phone which is running android 2.3.5. Anyways everything worked perfect on the emulator but crashes right on start up on the real device. Any ideas? here's the code.
public class StopWatch extends Activity implements OnClickListener {
//PROPERTIES USED THROUGHOUT CLASS
private Random rand = new Random();
private TextView stopWatchC;
private Button startButton,stopButton,resetButton;
private RelativeLayout mainLayout;
private Handler handle;
private Handler backHand = new Handler();
private boolean timerIsRunning;
private boolean previouslyStarted;
private long startTime;
private long endTime;
private long runTime;
private long UPDATE_EVERY = 200;
private int backgrounds[] = {
R.drawable.woman_1,
R.drawable.woman_2,
R.drawable.woman_3,
R.drawable.woman_4,
R.drawable.woman_5,
R.drawable.woman_6,
R.drawable.woman_7,
R.drawable.woman_8,
R.drawable.woman_9
};
//END PROPERTY DECLARATIONS
#SuppressLint("NewApi")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.stopwatch);
//Start our service
startService(new Intent(this,StopwatchService.class));
//SETUP BUTTON AND TEXTVIEWS
stopWatchC = (TextView) findViewById(R.id.counter);
startButton = (Button) findViewById(R.id.start_button);
stopButton = (Button) findViewById(R.id.stop_button);
resetButton = (Button) findViewById(R.id.reset);
mainLayout = (RelativeLayout) findViewById(R.id.main_layout);
//Handles listening for clicks on our start,stop and reset buttons
startButton.setOnClickListener(this);
stopButton.setOnClickListener(this);
resetButton.setOnClickListener(this);
//Calls run method for changing backgrounds
backHand.postDelayed(backgroundUpdate, 300);
}
/**
* Handles displaying the counter
*/
public void SWCounterDisplay()
{
String display;
long now;
long difference;
long secs;
long mins;
long hours;
if(timerIsRunning == true)
{
now = System.currentTimeMillis();
}else{
now = endTime;
}
if(previouslyStarted == true){
difference = runTime + (now - startTime);
}else{
difference = now-startTime;
}
//No negative numbers
if(difference < 0)
{
difference = 0;
}
secs = difference/1000;
mins = secs/60;
hours = mins/60;
secs = secs%60;
mins = mins%60;
display = String.format("%d", hours) + ":" +
String.format("%02d",mins) + ":" +
String.format("%02d", secs);
stopWatchC.setText(display);
}
/**
* Reset the timer
*/
public void resetTimer()
{
timerIsRunning = false;
previouslyStarted = false;
stopButton.setEnabled(false);
startButton.setEnabled(true);
runTime = 0;
SWCounterDisplay();
handle.removeCallbacks(timerUpdate);
handle = null;
}
/**
* Starts the stop watch
*/
public void startTimer()
{
timerIsRunning = true;
stopButton.setEnabled(timerIsRunning);
startButton.setEnabled(false);
if(!previouslyStarted){
previouslyStarted = true;
runTime = 0;
}
startTime = System.currentTimeMillis();
//Create new handler
handle = new Handler();
handle.postDelayed(timerUpdate, UPDATE_EVERY);
}
/**
* Stops the timer
*/
public void stopTimer()
{
timerIsRunning = false;
stopButton.setEnabled(timerIsRunning);
startButton.setEnabled(true);
endTime = System.currentTimeMillis();
runTime += endTime-startTime;
handle.removeCallbacks(timerUpdate);
handle = null;
}
/**
* Handles any onClick events
*/
#Override
public void onClick(View v) {
if(v == startButton)
{
startTimer();
}else if(v == stopButton)
{
stopTimer();
}else if(v == resetButton)
{
resetTimer();
}
}
/**
* Changes the background every 20 Seconds
*/
private Runnable backgroundUpdate = new Runnable(){
#Override
public void run() {
mainLayout.setBackgroundResource(backgrounds[rand.nextInt(backgrounds.length)]);
backHand.postDelayed(this, 60000);
}
};
/**
* Handles updating the timer
*/
private Runnable timerUpdate = new Runnable(){
#Override
public void run() {
SWCounterDisplay();
if(handle != null){
handle.postDelayed(this, UPDATE_EVERY);
}
}
};
/**
* Call run method if timer is still running
*/
public void onStart()
{
super.onStart();
if(timerIsRunning == true)
{
handle = new Handler();
handle.postDelayed(timerUpdate, UPDATE_EVERY);
}
}
/**
* Stop the timer if timer is still running
*/
public void onStop()
{
super.onStop();
if(timerIsRunning == true)
{
handle.removeCallbacks(timerUpdate);
handle = null;
}
}
/**
* Resume when the onResume method is called
*/
public void onResume()
{
super.onResume();
if(timerIsRunning == true){
stopButton.setEnabled(true);
startButton.setEnabled(false);
}else{
stopButton.setEnabled(false);
startButton.setEnabled(true);
}
SWCounterDisplay();
}
package com.webdeveloper93.stopwatch;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;
public class StopwatchService extends Service {
#Override
public IBinder onBind(Intent arg0) {
return null;
}
public int onStartCommand(Intent intent,int flags,int startId)
{
Log.d("StopwatchService:","SERVICE STARTED");
super.onStartCommand(intent, flags, startId);
return START_NOT_STICKY;
}
public void onDestroy()
{
Log.d("StopwatchService:","SERVICE DESTROYED");
super.onDestroy();
}
}
Thanks in advance
EDIT
I/ActivityManager( 132): No longer want com.google.android.gsf.login (pid 1140): hidden #16
D/WifiService( 132): ACTION_BATTERY_CHANGED pluggedType: 0
I/ActivityManager( 132): Starting: Intent { act=android.intent.action.MAIN cat=[android.intent.category.LAUNCHER] flg=0x10200000 cmp=com.webdeveloper93.stopwatch/.StopWatch } from pid 231
E/AndroidRuntime( 1186): FATAL EXCEPTION: main
E/AndroidRuntime( 1186): java.lang.NoSuchMethodError: android.os.StrictMode$VmPolicy$Builder.detectLeakedClosableObjects
E/AndroidRuntime( 1186): at com.webdeveloper93.stopwatch.StopWatch.onCreate(StopWatch.java:59)
E/AndroidRuntime( 1186): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
E/AndroidRuntime( 1186): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1611)
E/AndroidRuntime( 1186): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1663)
E/AndroidRuntime( 1186): at android.app.ActivityThread.access$1500(ActivityThread.java:117)
E/AndroidRuntime( 1186): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:931)
E/AndroidRuntime( 1186): at android.os.Handler.dispatchMessage(Handler.java:99)
E/AndroidRuntime( 1186): at android.os.Looper.loop(Looper.java:130)
E/AndroidRuntime( 1186): at android.app.ActivityThread.main(ActivityThread.java:3683)
E/AndroidRuntime( 1186): at java.lang.reflect.Method.invokeNative(Native Method)
E/AndroidRuntime( 1186): at java.lang.reflect.Method.invoke(Method.java:507)
E/AndroidRuntime( 1186): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:864)
E/AndroidRuntime( 1186): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:622)
E/AndroidRuntime( 1186): at dalvik.system.NativeStart.main(Native Method)
W/ActivityManager( 132): Force finishing activity com.webdeveloper93.stopwatch/.StopWatch
W/ActivityManager( 132): Activity pause timeout for HistoryRecord{408ff850 com.webdeveloper93.stopwatch/.StopWatch}
W/InputMethodManagerService( 132): Window already focused, ignoring focus gain of: com.android.internal.view.IInputMethodClient$Stub$Proxy#405ca178
I/ActivityManager( 132): Process com.webdeveloper93.stopwatch (pid 1186) has died.
W/ActivityManager( 132): Service crashed 2 times, stopping: ServiceRecord{4078c080 com.webdeveloper93.stopwatch/.StopwatchService}
W/ActivityManager( 132): Activity destroy timeout for HistoryRecord{408ff850 com.webdeveloper93.stopwatch/.StopWatch}
I/ActivityManager( 132): Starting: Intent { act=android.intent.action.MAIN cat=[android.intent.category.LAUNCHER] flg=0x10200000 cmp=org.jtb.alogcat/.LogActivity } from pid 231

It looks like you use a method which is not implemented in android <=2.3.5. If you remove #SuppressLint("NewApi"), you will see which one it is.
I think it works in your emulator because you use a higher sdk-version there.

Related

Unable to create and run app lock service

I have been trying to build a project named App Lock.
My problem is that whenever i try to run the project it shows a message Unfortunately App Lock has been stopped.
Log cat :-
01-15 10:29:58.322 31941-31941/? E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.pk.applock, PID: 31941
java.lang.RuntimeException: Unable to start service com.pk.applock.ApplockService#21d15610 with Intent { act=com.pk.applock.applock_service.start flg=0x4 cmp=com.pk.applock/.ApplockService (has extras) }: java.lang.NullPointerException
at android.app.ActivityThread.handleServiceArgs(ActivityThread.java:2886)
at android.app.ActivityThread.access$2100(ActivityThread.java:139)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1390)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:149)
at android.app.ActivityThread.main(ActivityThread.java:5257)
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:793)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:609)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at com.pk.applock.ApplockService.getTopTask(ApplockService.java:37)
at com.pk.applock.ApplockService.checkPackageChanged(ApplockService.java:86)
at com.pk.applock.ApplockService.onStartCommand(ApplockService.java:110)
at android.app.ActivityThread.handleServiceArgs(ActivityThread.java:2869)
at android.app.ActivityThread.access$2100(ActivityThread.java:139) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1390) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:149) 
at android.app.ActivityThread.main(ActivityThread.java:5257) 
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:793) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:609) 
at dalvik.system.NativeStart.main(Native Method) 
Here is the complete code of ApplockService.class
public class ApplockService
extends Service{
private Handler handler;
private static PendingIntent pendingIntent;
private String packageName;
private Map<String,Boolean> lockedPackages;
Intent intent;
private ActivityManager manager;
Context context;
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
private ActivityManager.RunningTaskInfo getTopTask()
{
return (ActivityManager.RunningTaskInfo)this.manager.getRunningTasks(1).get(0);
}
private boolean init()
{
handler=new Handler();
lockedPackages=new HashMap();
Iterator iterator=PrefUtils.getLocked((Context)this).iterator();
do {
if(!iterator.hasNext()) {
ApplockService.startAlarm((Context)this);
return true;
}
String string=(String)iterator.next();
lockedPackages.put(string,true);
}while (true);
}
private static void startAlarm(Context context)
{
AlarmManager alarmManager=(AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
PendingIntent repeated_intent=ApplockService.getRunIntent(context);
alarmManager.setRepeating(3, SystemClock.elapsedRealtime(),5,repeated_intent);
}
private static final PendingIntent getRunIntent(Context context)
{
if(pendingIntent==null)
{
Intent intent1=new Intent(context,ApplockService.class);
intent1.setAction("com.pk.applock.applock_service.start");
pendingIntent=PendingIntent.getService(context,1193135,intent1,0);
}
return pendingIntent;
}
public static final void start(Context context)
{
ApplockService.startAlarm(context);
}
public void showLocker(String packageName)
{
Intent intent=LockService.getLockIntent((Context)this,packageName);
intent.setAction(LockService.ACTION_COMPARE);
intent.putExtra(LockService.EXTRA_PACKAGENAME, packageName);
startService(intent);
}
public void checkPackageChanged()
{
String string=getTopTask().topActivity.getPackageName();
onAppOpen(string);
}
private void onAppOpen(String string)
{
if (lockedPackages.containsKey(string))
onLockedAppOpen(string);
}
private void onLockedAppOpen(String string)
{
if(this.lockedPackages.get(string).booleanValue())
{
showLocker(string);
}
}
#Override
public int onStartCommand(Intent intent,int n2,int n3)
{
if(intent==null||"com.pk.applock.applock_service.start".equals(intent.getAction()))
{
if(!init())
init();
checkPackageChanged();
return 2;
}
return 2;
}
}
Please help me!!!
I am new to android!
Thanks in advance.
Seem like manager object is not set yet in ApplockService class. You may put this code to init() function:
this.manager = (ActivityManager)getSystemService(Context.ACTIVITY_SERVICE);

Unable to start activity with intent

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);
}
}

android.view.WindowLeaked for tablet asynctask while trying to set portrait orientation

I have an activity that is displayed in portrait only and in my tablet it causes the following:
android.view.WindowLeaked: Activity com.spicycurryman.getdisciplined10.app.InstalledAppActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView{53210b88 V.E..... R.....ID 0,0-1520,192} that was originally added here
at android.view.ViewRootImpl.<init>(ViewRootImpl.java:354)
at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:216)
at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:69)
at android.app.Dialog.show(Dialog.java:281)
at com.spicycurryman.getdisciplined10.app.InstalledAppActivity$LoadApplications.onPreExecute(InstalledAppActivity.java:306)
at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:586)
at android.os.AsyncTask.execute(AsyncTask.java:534)
at com.spicycurryman.getdisciplined10.app.InstalledAppActivity.onCreate(InstalledAppActivity.java:105)
at android.app.Activity.performCreate(Activity.java:5104)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
at android.app.ActivityThread.access$600(ActivityThread.java:141)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5041)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
at dalvik.system.NativeStart.main(Native Method)
I am using an AsyncTask to load a listview of installed apps on the phone and using a progressdialog.
I have researched this problem:
Progress dialog and AsyncTask error
android.view.WindowLeaked exception
Android Error: Window Leaked in AsyncTask
I was able to produce this code so that the whole app doesn't crash and burn, but the exception is still thrown and the activity screen is kind of shaky after the button click and the whole transition is not really smooth.
#Override
protected void onPostExecute(Void result) {
apkList.setAdapter(new ApkAdapter(InstalledAppActivity.this, packageList1, packageManager));
try {
if ((this.pDialog != null) && this.pDialog.isShowing()) {
this.pDialog.dismiss();
}
} catch (final IllegalArgumentException e) {
// Handle or log or ignore
} catch (final Exception e) {
// Handle or log or ignore
} finally {
this.pDialog = null;
}
super.onPostExecute(result);
}
Dismissing the progress dialog or calling finish() doesn't really solve the problem either...
How would I fix this?
Here is most of the AsyncTask code:
private class LoadApplications extends AsyncTask<Void, Void, Void> {
private ProgressDialog pDialog;
List<PackageInfo> packageList1 = new ArrayList<PackageInfo>();
public LoadApplications(Context context){
Context mContext = context;
}
#Override
protected Void doInBackground(Void... params) {
List<PackageInfo> packageList = packageManager
.getInstalledPackages(PackageManager.GET_PERMISSIONS);
List<PackageInfo> packageList2 = packageManager
.getInstalledPackages(PackageManager.GET_PERMISSIONS);
for(PackageInfo pi : packageList) {
boolean b = isSystemPackage(pi);
boolean c = isSystemPackage1(pi);
boolean d = isSystemPackage2(pi);
if ((!b || !c ) && d ){
packageList1.add(pi);
}
}
//here you got email and message apps in the
for(PackageInfo pi : packageList) {
boolean b = isSystemPackage3(pi);
boolean c = isSystemPackage4(pi);
if (b || c){
packageList1.add(pi);
}
}
//sort by application name
final PackageItemInfo.DisplayNameComparator comparator = new PackageItemInfo.DisplayNameComparator(packageManager);
Collections.sort(packageList1, new Comparator<PackageInfo>() {
#Override
public int compare(PackageInfo lhs, PackageInfo rhs) {
return comparator.compare(lhs.applicationInfo, rhs.applicationInfo);
}
});
return null;
}
#Override
protected void onCancelled() {
super.onCancelled();
}
#Override
protected void onPreExecute() {
pDialog = new ProgressDialog(InstalledAppActivity.this);
pDialog.setMessage("Loading your apps...");
pDialog.show();
}
//Inefficient patch to prevent Window Manager error
#Override
protected void onPostExecute(Void result) {
apkList.setAdapter(new ApkAdapter(InstalledAppActivity.this, packageList1, packageManager));
try {
if ((this.pDialog != null) && this.pDialog.isShowing()) {
this.pDialog.dismiss();
}
} catch (final IllegalArgumentException e) {
// Handle or log or ignore
} catch (final Exception e) {
// Handle or log or ignore
} finally {
this.pDialog = null;
}
super.onPostExecute(result);
}
#Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
}
}
try this :
#Override
public Object onRetainNonConfigurationInstance() {
if (progressDialog != null && progressDialog.isShowing()) {
progressDialog = null;
}
if (asynTask!= null) {
asynTask.detach();
}
return ayncTask;
}
Declaring a non-static inner AsyncTask in your activity is not a good idea because it holds a reference to the activity and this could be a couse of the leak. However, various configuration changes could cause the OS to destroy and recreate the activity. There are a number of solutions and Rustam's anser is an example.
However, I prefer to user either AsyncTaskLoader or use some sort of asynchronous callback, like a broadcast. The asynchronous callback decouples your AsyncTask from the Activity.

BadTokenException even after referring to Activity and not the application context

android.view.WindowManager$BadTokenException: Unable to add window -- token android.os.BinderProxy#406a6678 is not valid; is your activity running?
at android.view.ViewRoot.setView(ViewRoot.java:528)
at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:177)
at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:91)
at android.view.Window$LocalWindowManager.addView(Window.java:424)
at android.app.Dialog.show(Dialog.java:241)
at android.app.Activity.showDialog(Activity.java:2569)
at android.app.Activity.showDialog(Activity.java:2527)
at MyCode$8$4.run(MyCode.java:557)
at android.os.Handler.handleCallback(Handler.java:587)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:130)
at android.app.ActivityThread.main(ActivityThread.java:3683)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:507)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:878)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:636)
at dalvik.system.NativeStart.main(Native Method)
I am getting above exception when following code is executed. This file dialog will shown once the processing is done and progressbar reaches 100%. FileSaveDialog extends Dialog and implements OnCompletionListener
runOnUiThread(new Runnable() {
#Override
public void run() {
showDialog(error.Code());//Line 557
}
});
#Override
protected Dialog onCreateDialog(int id) {
Dialog dialog;
AlertDialog.Builder builder;
final ScrollView scrollView = new ScrollView(this);
final TextView textView = new TextView(this);
switch (id) {
// Other cases are here
case 4:
File playFile = new File(mediaPath, TEMP_WAV_FILE_NAME);
dialog = new FileSaveDialog(this, getResources(),
playFile.getAbsolutePath(), saveDiscardHandler);
dialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
#Override
public void onCancel(DialogInterface dialog) {
// do whatever you want the back key to do
cleanUp();
}
});
break;
// Other cases are here
default:
dialog = null;
}
return dialog;
}
You must check activity isFinishing() If the activity is finishing, returns true; else returns false.

NullPointException on algorithm but don't get NPE on same algorithm in another spot in same class [closed]

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 9 years ago.
In my app, the user has 3 different types of quizzes they can choose. When they choose one of quiz types called "levels", I get a NullPointerException. The order of the algorithm for "levels" is the same as when the game type is "original". You can see this in the code below. It is hard to explain why the algorithms are the same so I will spare you those details but just accept the algorithms are the same for now. :)
Why am I getting this NPE exception with the quiz/game type is "levels" but not when the quiz/game type is "original" even though the code/algorithm for them are the same?
public class QuestionView extends Activity {
int correctAnswers = 0;
int wrongAnswers = 0;
int answer = 0;
int i = 0;
long score = 0;
long startTime = 20000;
long interval = 1000;
long points;
boolean timerHasStarted = false;
String category;
Button answer1, answer2, answer3, answer4;
TextView question, pointCounter, questionNumber, timeCounter, timeremaining;
ArrayList<Question> queries;
public static ArrayList<Long> pointsPerQuestion = new ArrayList<Long>(10);
Timer cdTimer;
ProgressBar bar;
Context c;
Singleton singleton = Singleton.getInstance();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.questionview);
c = this;
answer1 = (Button)findViewById(R.id.answer1);
answer2 = (Button)findViewById(R.id.answer2);
answer3 = (Button)findViewById(R.id.answer3);
answer4 = (Button)findViewById(R.id.answer4);
question = (TextView)findViewById(R.id.question);
questionNumber = (TextView)findViewById(R.id.questionnumber);
timeremaining = (TextView)findViewById(R.id.timeremaining);
category = getIntent().getStringExtra("category");
queries = getIntent().getParcelableArrayListExtra("queries");
pointsPerQuestion.clear();
if(singleton.getGameType() == "levels") {
if(singleton.getLevel() <= 10) {
cdTimer = new Timer(startTime, interval);
bar = (ProgressBar)findViewById(R.id.progressbar);
bar.setIndeterminate(false);
bar.setMax(20000);
loadLevelsQuizTen();
}
//...
} else if (singleton.getGameType() == "original") {
cdTimer = new Timer(startTime, interval);
bar = (ProgressBar)findViewById(R.id.progressbar);
bar.setIndeterminate(false);
bar.setMax(20000);
loadOriginalQuiz();
} else if (singleton.getGameType() == "freeplay") {
loadFreeplayQuiz();
}
}
public void loadFreeplayQuiz() {
//...
}
public void loadLevelsQuizTen() {
if(i == 10) {
cdTimer.cancel();
endQuiz();
} else {
if(!timerHasStarted) {
cdTimer.start();
timerHasStarted = true;
} else {
cdTimer.start();
timerHasStarted = false;
}
//answer = queries.get(i).getCorrectAnswer(); //NULLPOINTEREXCEPTION HERE
answer = 2;
question.setText(queries.get(i).getQuery()); // I COMMENTED OUT ABOVE LINE OF CODE AND NOW NPE IS NOW HERE
answer1.setText(queries.get(i).getA1());
answer2.setText(queries.get(i).getA2());
answer3.setText(queries.get(i).getA3());
answer4.setText(queries.get(i).getA4());
answer1.setOnClickListener(new OnClickListener() {
//...
}
});
answer2.setOnClickListener(new OnClickListener() {
//...
});
answer3.setOnClickListener(new OnClickListener() {
//...
});
answer4.setOnClickListener(new OnClickListener() {
//...
});
}
}
public void loadOriginalQuiz() {
if(i == 10) {
cdTimer.cancel();
endQuiz();
} else {
if(!timerHasStarted) {
cdTimer.start();
timerHasStarted = true;
} else {
cdTimer.start();
timerHasStarted = false;
}
answer = queries.get(i).getCorrectAnswer();
question.setText(queries.get(i).getQuery());
answer1.setText(queries.get(i).getA1());
answer2.setText(queries.get(i).getA2());
answer3.setText(queries.get(i).getA3());
answer4.setText(queries.get(i).getA4());
answer1.setOnClickListener(new OnClickListener() {
//...
});
answer2.setOnClickListener(new OnClickListener() {
//...
});
answer3.setOnClickListener(new OnClickListener() {
//...
});
answer4.setOnClickListener(new OnClickListener() {
//...
});
}
}
public ArrayList<Question> getQueries() {
return queries;
}
public static ArrayList<Long> getPointsPerQuestion() {
//...
}
public void correct() {
pointsPerQuestion.add(points);
score = score + points;
i++;
if(singleton.getGameType() == "original") {
loadOriginalQuiz();
} else if(singleton.getGameType() == "levels") {
loadLevelsQuizTen();
}
}
public void incorrect() {
long zero = 0;
pointsPerQuestion.add(zero);
i++;
loadOriginalQuiz();
}
public class Timer extends CountDownTimer {
public Timer(long startTime, long interval) {
super(startTime, interval);
}
#Override
public void onFinish() {
points = 0;
if(i >= 9) {
cdTimer.cancel();
pointsPerQuestion.add(points);
endQuiz();
} else {
wrongAnswers++;
incorrect();
}
}
#Override
public void onTick(long millisUntilFinished) {
bar.setProgress((int) millisUntilFinished);
points = (millisUntilFinished / 200) + 1;
timeremaining.setText("Score remaining: " + points);
if(i < 10) {
questionNumber.setText(c.getResources().getString(R.string.question) + " " + (i + 1) + " " + c.getResources().getString(R.string.of10));
}
}
}
public void endQuiz() {
Intent intent = new Intent(QuestionView.this, Results.class);
intent.putExtra("correctAnswers", correctAnswers);
intent.putExtra("wrongAnswers", wrongAnswers);
intent.putExtra("score", score);
intent.putExtra("pointsPerQuestion", pointsPerQuestion);
intent.putParcelableArrayListExtra("queries", queries);
intent.putExtra("category", category);
startActivity(intent);
}
public void onStop() {
super.onStop();
}
public void onResume() {
super.onResume();
}
}
LogCat
06-14 20:44:45.413: E/AndroidRuntime(1335): java.lang.RuntimeException: Unable to start activity ComponentInfo{matt.lyons.bibletrivia.lite/matt.lyons.bibletrivia.lite.QuestionView}: java.lang.NullPointerException
06-14 20:44:45.413: E/AndroidRuntime(1335): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2180)
06-14 20:44:45.413: E/AndroidRuntime(1335): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
06-14 20:44:45.413: E/AndroidRuntime(1335): at android.app.ActivityThread.access$600(ActivityThread.java:141)
06-14 20:44:45.413: E/AndroidRuntime(1335): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
06-14 20:44:45.413: E/AndroidRuntime(1335): at android.os.Handler.dispatchMessage(Handler.java:99)
06-14 20:44:45.413: E/AndroidRuntime(1335): at android.os.Looper.loop(Looper.java:137)
06-14 20:44:45.413: E/AndroidRuntime(1335): at android.app.ActivityThread.main(ActivityThread.java:5041)
06-14 20:44:45.413: E/AndroidRuntime(1335): at java.lang.reflect.Method.invokeNative(Native Method)
06-14 20:44:45.413: E/AndroidRuntime(1335): at java.lang.reflect.Method.invoke(Method.java:511)
06-14 20:44:45.413: E/AndroidRuntime(1335): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
06-14 20:44:45.413: E/AndroidRuntime(1335): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
06-14 20:44:45.413: E/AndroidRuntime(1335): at dalvik.system.NativeStart.main(Native Method)
06-14 20:44:45.413: E/AndroidRuntime(1335): Caused by: java.lang.NullPointerException
06-14 20:44:45.413: E/AndroidRuntime(1335): at matt.lyons.bibletrivia.lite.QuestionView.loadLevelsQuizTen(QuestionView.java:195)
06-14 20:44:45.413: E/AndroidRuntime(1335): at matt.lyons.bibletrivia.lite.QuestionView.onCreate(QuestionView.java:80)
06-14 20:44:45.413: E/AndroidRuntime(1335): at android.app.Activity.performCreate(Activity.java:5104)
06-14 20:44:45.413: E/AndroidRuntime(1335): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)
06-14 20:44:45.413: E/AndroidRuntime(1335): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144)
Why "accept"? That might be the fatal flaw in your argument.
Here's the problem:
Caused by: java.lang.NullPointerException
06-14 20:44:45.413: E/AndroidRuntime(1335): at matt.lyons.bibletrivia.lite.QuestionView.loadLevelsQuizTen(QuestionView.java:195)
Go to line 195 in the QuestionView.java file, look at the object references on that line, and see which one you failed to initialize.
The sooner you stop telling yourself that everything is fine and start looking at what's really happening, the sooner you'll fix the problem and move on.
You should not be duplicating any code. You should encapsulate it in a single method call and calling it in both places. This is a recipe for error.
You have lots of other issues. You use a private data member i to do different things in different methods. It's not synchronized in any way that I can see. I see no reason why that value couldn't be a method parameter and passed in. That would be more more thread safe.
When you're doing things like that, comparing Strings with ==, and duplicating code it puts everything you've done in doubt for me. No wonder you're having trouble. Voting to close.
Set a breakpoint where you are getting the NPE and check the values of your variables. I would guess either queries is null (not setting or getting from intent bundle correctly), or queries.get(i) is null.
you get the error because you are calling 2 different methods. In levels you call loadLevelsQuizTen();, in original you call loadOriginalQuiz();
Despite the fact you say they are the same, they aren't. I'd use a debugger to step through the method and figure out what is null and why.

Categories