-3

I'm an ameture android app maker, and the below is my first app. What the app basically does is that it gets the location of the phone, delays for 5 seconds, and runs another getLocation; then it figures out speed from the two points and points out if the user is walking while using the phone or not.

The code in the Studio is okay without problems, but when I try to run my app, the phone simply says 'the app has stopped'. And it shuts the app down. I've spent a few hours trying to figure it out, to no avail.

What am I doing wrong?

package com.example.denny.myapplication;

import android.Manifest.permission;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.provider.Settings;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        PackageManager pm = getPackageManager();
        if (pm.checkPermission(permission.ACCESS_FINE_LOCATION, getPackageName()) == PackageManager.PERMISSION_DENIED) {
            alertboxGPS();
        }
        mHandler = new Handler();
        startRepeatingTask();
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        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();

                                   }
                               }
        );
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        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.

        //Also, chuck the subroutine settings here. :3
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    PackageManager pm = getPackageManager();

    protected void alertboxGPS() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setMessage("Your Device's GPS is Disabled")
                .setCancelable(true)
                .setTitle("** Gps Status **")
                .setPositiveButton("Gps On",
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int id) {
                                // finish the current activity
                                // AlertBoxAdvance.this.finish();
                                Intent myIntent = new Intent(
                                        Settings.ACTION_SECURITY_SETTINGS);
                                startActivity(myIntent);
                                dialog.cancel();
                            }
                        })
                .setNegativeButton("Cancel",
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int id) {
                                // cancel the dialog box
                                dialog.cancel();
                            }
                        });
        AlertDialog alert = builder.create();
        alert.show();
    }

    protected void alertboxViolation() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setMessage("Please stop walking. You may get in an accident.")
                .setCancelable(false)
                .setTitle("Walking Warning")
                .setPositiveButton("Stop Walking",
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int id) {
                                // finish the current activity
                                // AlertBoxAdvance.this.finish();
                                Intent myIntent = new Intent(
                                        Settings.ACTION_SECURITY_SETTINGS);
                                startActivity(myIntent);
                                dialog.cancel();
                            }
                        })
                .setNegativeButton("Cancel",
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int id) {
                                // cancel the dialog box
                                dialog.cancel();
                            }
                        });
        AlertDialog alert = builder.create();
        alert.show();
    }

    //Some Default Integers
    int ViolationLimit = 10;
    int SpeedLimit = 100;
    int ExceedInstance = 0;

    //Default Value
    LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    Location location1;
    Location location2;

    private double GetSpeed(Location location1, Location location2) {

        if (location1 == null) {

            location1 = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
            location2 = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
        } else {
            location1 = location2;
            if (checkSelfPermission(permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && checkSelfPermission(permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {

            }
            location2 = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);

        }
        double Distance;
        Distance = location1.distanceTo(location2);
        double Speed = Distance / mInterval;
        return Speed;
    }


    private int Judge(double Speed, int ViolationLimit, int SpeedLimit, int ExceedInstance) {
        if (Speed >= 1 && Speed <= SpeedLimit) {
            ExceedInstance += 1;
        }

        if (ExceedInstance >= ViolationLimit) {
            alertboxViolation();
        }
        return ExceedInstance;
    }

    void stopRepeatingTask() {
        mHandler.removeCallbacks(mStatusChecker);
    }

    private int mInterval = 3000; // 3 seconds by default, can be changed later
    private Handler mHandler;
    Runnable mStatusChecker = new Runnable() {
        @Override
        public void run() {
            updateStatus();
            mHandler.postDelayed(mStatusChecker, mInterval);
        }
    };

    private void updateStatus() {
        //Is used for updating mInterval
    }

    void startRepeatingTask() {
        double Speed = GetSpeed(location1, location2);
        Judge(Speed, ViolationLimit, SpeedLimit, ExceedInstance);
        mStatusChecker.run();
    }
}

Logcat Logs:

10-13 23:23:55.818 13410-13410/? E/SELinux: Function: selinux_android_load_priority [0], There is no sepolicy file 
10-13 23:23:55.818 13410-13410/? E/SELinux:  
10-13 23:23:55.818 13410-13410/? E/SELinux: Function: selinux_android_load_priority , loading version is VE=SEPF_GT-I9505_4.3_0024
10-13 23:23:55.818 13410-13410/? E/SELinux:  
10-13 23:23:55.818 13410-13410/? E/SELinux:  
10-13 23:23:55.818 13410-13410/? E/SELinux: selinux_android_seapp_context_reload: seapp_contexts file is loaded from /data/security/spota/seapp_contexts
10-13 23:23:55.818 13410-13410/? D/dalvikvm: Late-enabling CheckJNI
10-13 23:23:55.928 13410-13410/com.example.denny.myapplication I/dalvikvm: Could not find method com.example.denny.myapplication.MainActivity.checkSelfPermission, referenced from method com.example.denny.myapplication.MainActivity.GetSpeed
10-13 23:23:55.928 13410-13410/com.example.denny.myapplication W/dalvikvm: VFY: unable to resolve virtual method 16261: Lcom/example/denny/myapplication/MainActivity;.checkSelfPermission (Ljava/lang/String;)I
10-13 23:23:55.928 13410-13410/com.example.denny.myapplication D/dalvikvm: VFY: replacing opcode 0x6e at 0x0028
10-13 23:23:55.938 13410-13410/com.example.denny.myapplication D/AndroidRuntime: Shutting down VM
10-13 23:23:55.938 13410-13410/com.example.denny.myapplication W/dalvikvm: threadid=1: thread exiting with uncaught exception (group=0x4190e898)
10-13 23:23:55.948 13410-13410/com.example.denny.myapplication E/AndroidRuntime: FATAL EXCEPTION: main
10-13 23:23:55.948 13410-13410/com.example.denny.myapplication E/AndroidRuntime: java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.denny.myapplication/com.example.denny.myapplication.MainActivity}: java.lang.NullPointerException
10-13 23:23:55.948 13410-13410/com.example.denny.myapplication E/AndroidRuntime:     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2219)
10-13 23:23:55.948 13410-13410/com.example.denny.myapplication E/AndroidRuntime:     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2349)
10-13 23:23:55.948 13410-13410/com.example.denny.myapplication E/AndroidRuntime:     at android.app.ActivityThread.access$700(ActivityThread.java:159)
10-13 23:23:55.948 13410-13410/com.example.denny.myapplication E/AndroidRuntime:     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1316)
10-13 23:23:55.948 13410-13410/com.example.denny.myapplication E/AndroidRuntime:     at android.os.Handler.dispatchMessage(Handler.java:99)
10-13 23:23:55.948 13410-13410/com.example.denny.myapplication E/AndroidRuntime:     at android.os.Looper.loop(Looper.java:137)
10-13 23:23:55.948 13410-13410/com.example.denny.myapplication E/AndroidRuntime:     at android.app.ActivityThread.main(ActivityThread.java:5419)
10-13 23:23:55.948 13410-13410/com.example.denny.myapplication E/AndroidRuntime:     at java.lang.reflect.Method.invokeNative(Native Method)
10-13 23:23:55.948 13410-13410/com.example.denny.myapplication E/AndroidRuntime:     at java.lang.reflect.Method.invoke(Method.java:525)
10-13 23:23:55.948 13410-13410/com.example.denny.myapplication E/AndroidRuntime:     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1187)
10-13 23:23:55.948 13410-13410/com.example.denny.myapplication E/AndroidRuntime:     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1003)
10-13 23:23:55.948 13410-13410/com.example.denny.myapplication E/AndroidRuntime:     at dalvik.system.NativeStart.main(Native Method)
10-13 23:23:55.948 13410-13410/com.example.denny.myapplication E/AndroidRuntime:  Caused by: java.lang.NullPointerException
10-13 23:23:55.948 13410-13410/com.example.denny.myapplication E/AndroidRuntime:     at android.content.ContextWrapper.getPackageManager(ContextWrapper.java:94)
10-13 23:23:55.948 13410-13410/com.example.denny.myapplication E/AndroidRuntime:     at com.example.denny.myapplication.MainActivity.<init>(MainActivity.java:74)
10-13 23:23:55.948 13410-13410/com.example.denny.myapplication E/AndroidRuntime:     at java.lang.Class.newInstanceImpl(Native Method)
10-13 23:23:55.948 13410-13410/com.example.denny.myapplication E/AndroidRuntime:     at java.lang.Class.newInstance(Class.java:1130)
10-13 23:23:55.948 13410-13410/com.example.denny.myapplication E/AndroidRuntime:     at android.app.Instrumentation.newActivity(Instrumentation.java:1078)
10-13 23:23:55.948 13410-13410/com.example.denny.myapplication E/AndroidRuntime:     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2210)
10-13 23:23:55.948 13410-13410/com.example.denny.myapplication E/AndroidRuntime:     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2349) 
10-13 23:23:55.948 13410-13410/com.example.denny.myapplication E/AndroidRuntime:     at android.app.ActivityThread.access$700(ActivityThread.java:159) 
10-13 23:23:55.948 13410-13410/com.example.denny.myapplication E/AndroidRuntime:     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1316) 
10-13 23:23:55.948 13410-13410/com.example.denny.myapplication E/AndroidRuntime:     at android.os.Handler.dispatchMessage(Handler.java:99) 
10-13 23:23:55.948 13410-13410/com.example.denny.myapplication E/AndroidRuntime:     at android.os.Looper.loop(Looper.java:137) 
10-13 23:23:55.948 13410-13410/com.example.denny.myapplication E/AndroidRuntime:     at android.app.ActivityThread.main(ActivityThread.java:5419) 
10-13 23:23:55.948 13410-13410/com.example.denny.myapplication E/AndroidRuntime:     at java.lang.reflect.Method.invokeNative(Native Method) 
10-13 23:23:55.948 13410-13410/com.example.denny.myapplication E/AndroidRuntime:     at java.lang.reflect.Method.invoke(Method.java:525) 
10-13 23:23:55.948 13410-13410/com.example.denny.myapplication E/AndroidRuntime:     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1187) 
10-13 23:23:55.948 13410-13410/com.example.denny.myapplication E/AndroidRuntime:     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1003) 
10-13 23:23:55.948 13410-13410/com.example.denny.myapplication E/AndroidRuntime:     at dalvik.system.NativeStart.main(Native Method) 
10-13 23:24:03.355 13410-13410/com.example.denny.myapplication I/Process: Sending signal. PID: 13410 SIG: 9

It's a pretty big log, but I don't know how to do it in a better way.

Disclaimer This question is not the same to the Null Pointer Question because I've made an app and I don't know what is causing it. That is why I am asking this question.

Mildwood
  • 349
  • 2
  • 13
  • 3
    Can you provide some logs ? – ThomasThiebaud Oct 13 '15 at 13:04
  • Sure... editing to include lolcat (I mean logcat) messages. – Mildwood Oct 13 '15 at 13:05
  • Possible duplicate of [What is a Null Pointer Exception, and how do I fix it?](http://stackoverflow.com/questions/218384/what-is-a-null-pointer-exception-and-how-do-i-fix-it) – Selvin Oct 13 '15 at 13:07
  • You're testing on a device <6 right? checkSelfPermission works for API>23 – JesusS Oct 13 '15 at 13:20
  • No... it really is not. That question is asking something someone does not know. Mine is an app, and I don't know why it's shutting down. Please do not assume that everyone knows everything about what they are doing when they are asking a question. (To Selvin) – Mildwood Oct 13 '15 at 13:20
  • Erm... I am testing on a device 4.3, Galaxy S4... So checkSelfPermission does not work? Is there an alt for checkSelfPermission? – Mildwood Oct 13 '15 at 13:23
  • Nvm, I've found the solution to that particular problem of SelfPerm. I still need to work out why it is shutting down the program with no apparent reason. – Mildwood Oct 13 '15 at 13:26
  • You can't show an alertdialog before super.onCreate. And checkpermissions need to call it only for API >=23 – Santiago Oct 13 '15 at 14:30

1 Answers1

2

Firstly, a word about your comment:

That question is asking something someone does not know. Mine is an app, and I don't know why it's shutting down. Please do not assume that everyone knows everything about what they are doing when they are asking a question.

People are trying to help you. You might want to rethink your attitude before writing such comments.

Secondly, @Selvin is correct. Your logcat output clearly states that your App crash is being caused by a NullPointerException (NPE):

E/AndroidRuntime:  Caused by: java.lang.NullPointerException

NullPointerException's are caused by (amoungst other things) bad logic in code. The fact that your code is part of an App is irrelevant. You should read the linked question to try to understand what NPE's are and why they occur.

Lecture over, lets look into your issue.

Logcat gives you a lot of information about errors and normally includes reasons and stacktrace showing you the problem. So, from the top:

E/AndroidRuntime: FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{...}: java.lang.NullPointerException

OK, it's a NullPointerException during instantiation of your Activity. Why?

Caused by: java.lang.NullPointerException
E/AndroidRuntime:     at android.content.ContextWrapper.getPackageManager(ContextWrapper.java:94)
 at com.example.denny.myapplication.MainActivity.<init>(MainActivity.java:74)

So there's a problem calling getPackageManager(). The nearest location in your code is MainActivity.<init>, MainActivity.java, line 74

<init> is just the Java method for "during construction of an object".

Looking at your source code, you are attempting to initialise a PackageManager pm field instance during object construction:

@Override
public boolean onOptionsItemSelected(MenuItem item) {
...
}

PackageManager pm = getPackageManager();

protected void alertboxGPS() {
...
}

The problem is that getPackageManager() is being called while your Activity instance is in the middle of being constructed - not everything will be ready at this point.

It's almost certainly the case that the call to getPackageManager() is attempting to use objects that haven't been created yet - hence the NullPointerException.

One solution is to remove the initialisation of your pm field and instead, set it during onCreate() - at that point, your Activity instance will be fully constructed and the getPackageManager() call will succeed.

A better solution is to remove the pm field completely and just create local variables when you need it - like you are already doing in onCreate().

Community
  • 1
  • 1
adelphus
  • 10,116
  • 5
  • 36
  • 46
  • Sorry for my rudeness, I get irritable sometimes. I have fixed my problem and am continuing to work on my problems. – Mildwood Oct 17 '15 at 09:26