无法修复NullPointer异常

时间:2015-10-16 12:32:29

标签: android nullpointerexception null-pointer

我是一名刚刚完成他的应用程序并正在调试的amatuer程序员;直到应用程序崩溃而没有询问:(。

我从lolcat执行了堆栈跟踪,以下内容在ContextWrapper中实现了NullPointerError。

@Override
public PackageManager getPackageManager() {
    return mBase.getPackageManager();
}

但我无法看到它的问题。应用代码如下:

package com.example.denny.myapplication;

import android.Manifest;
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.v4.content.ContextCompat;
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();

                               }
                           }

    );
    getSystemService(Context.LOCATION_SERVICE);

}


@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.menu_main, menu);
    return true;
}

@Override
public PackageManager getPackageManager() {
    return super.getPackageManager();
}

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

protected void alertboxGranted() {
    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setMessage("Access Granted")
            .setCancelable(true)
            .setTitle("Access to GPS")
            .setPositiveButton("Ok",
                    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 boolean canGetLocation() {
    return(ContextCompat.checkSelfPermission(this,
            Manifest.permission.ACCESS_FINE_LOCATION)==
            PackageManager.PERMISSION_GRANTED);
}

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 (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)== PackageManager.PERMISSION_GRANTED) {
                alertboxGranted();
        }
        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();
}

}

Lolcat:

10-17 10:41:39.663 7874-7874/com.example.denny.myapplication D/AndroidRuntime: Shutting down VM
10-17 10:41:39.663 7874-7874/com.example.denny.myapplication W/dalvikvm: threadid=1: thread exiting with uncaught exception (group=0x41967898)
10-17 10:41:39.663 7874-7874/com.example.denny.myapplication E/AndroidRuntime: FATAL EXCEPTION: main
10-17 10:41:39.663 7874-7874/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-17 10:41:39.663 7874-7874/com.example.denny.myapplication E/AndroidRuntime:     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2219)
10-17 10:41:39.663 7874-7874/com.example.denny.myapplication E/AndroidRuntime:     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2349)
10-17 10:41:39.663 7874-7874/com.example.denny.myapplication E/AndroidRuntime:     at android.app.ActivityThread.access$700(ActivityThread.java:159)
10-17 10:41:39.663 7874-7874/com.example.denny.myapplication E/AndroidRuntime:     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1316)
10-17 10:41:39.663 7874-7874/com.example.denny.myapplication E/AndroidRuntime:     at android.os.Handler.dispatchMessage(Handler.java:99)
10-17 10:41:39.663 7874-7874/com.example.denny.myapplication E/AndroidRuntime:     at android.os.Looper.loop(Looper.java:137)
10-17 10:41:39.663 7874-7874/com.example.denny.myapplication E/AndroidRuntime:     at android.app.ActivityThread.main(ActivityThread.java:5419)
10-17 10:41:39.663 7874-7874/com.example.denny.myapplication E/AndroidRuntime:     at java.lang.reflect.Method.invokeNative(Native Method)
10-17 10:41:39.663 7874-7874/com.example.denny.myapplication E/AndroidRuntime:     at java.lang.reflect.Method.invoke(Method.java:525)
10-17 10:41:39.663 7874-7874/com.example.denny.myapplication E/AndroidRuntime:     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1187)
10-17 10:41:39.663 7874-7874/com.example.denny.myapplication E/AndroidRuntime:     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1003)
10-17 10:41:39.663 7874-7874/com.example.denny.myapplication E/AndroidRuntime:     at dalvik.system.NativeStart.main(Native Method)
10-17 10:41:39.663 7874-7874/com.example.denny.myapplication E/AndroidRuntime:  Caused by: java.lang.NullPointerException
10-17 10:41:39.663 7874-7874/com.example.denny.myapplication E/AndroidRuntime:     at android.content.ContextWrapper.getPackageManager(ContextWrapper.java:94)
10-17 10:41:39.663 7874-7874/com.example.denny.myapplication E/AndroidRuntime:     at com.example.denny.myapplication.MainActivity.getPackageManager(MainActivity.java:63)
10-17 10:41:39.663 7874-7874/com.example.denny.myapplication E/AndroidRuntime:     at com.example.denny.myapplication.MainActivity.<init>(MainActivity.java:83)
10-17 10:41:39.663 7874-7874/com.example.denny.myapplication E/AndroidRuntime:     at java.lang.Class.newInstanceImpl(Native Method)
10-17 10:41:39.663 7874-7874/com.example.denny.myapplication E/AndroidRuntime:     at java.lang.Class.newInstance(Class.java:1130)
10-17 10:41:39.663 7874-7874/com.example.denny.myapplication E/AndroidRuntime:     at android.app.Instrumentation.newActivity(Instrumentation.java:1078)
10-17 10:41:39.663 7874-7874/com.example.denny.myapplication E/AndroidRuntime:     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2210)
10-17 10:41:39.663 7874-7874/com.example.denny.myapplication E/AndroidRuntime:     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2349) 
10-17 10:41:39.663 7874-7874/com.example.denny.myapplication E/AndroidRuntime:     at android.app.ActivityThread.access$700(ActivityThread.java:159) 
10-17 10:41:39.663 7874-7874/com.example.denny.myapplication E/AndroidRuntime:     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1316) 
10-17 10:41:39.663 7874-7874/com.example.denny.myapplication E/AndroidRuntime:     at android.os.Handler.dispatchMessage(Handler.java:99) 
10-17 10:41:39.663 7874-7874/com.example.denny.myapplication E/AndroidRuntime:     at android.os.Looper.loop(Looper.java:137) 
10-17 10:41:39.663 7874-7874/com.example.denny.myapplication E/AndroidRuntime:     at android.app.ActivityThread.main(ActivityThread.java:5419) 
10-17 10:41:39.663 7874-7874/com.example.denny.myapplication E/AndroidRuntime:     at java.lang.reflect.Method.invokeNative(Native Method) 
10-17 10:41:39.663 7874-7874/com.example.denny.myapplication E/AndroidRuntime:     at java.lang.reflect.Method.invoke(Method.java:525) 
10-17 10:41:39.663 7874-7874/com.example.denny.myapplication E/AndroidRuntime:     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1187) 
10-17 10:41:39.663 7874-7874/com.example.denny.myapplication E/AndroidRuntime:     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1003) 
10-17 10:41:39.663 7874-7874/com.example.denny.myapplication E/AndroidRuntime:     at dalvik.system.NativeStart.main(Native Method) 
10-17 10:41:42.556 7874-7874/com.example.denny.myapplication I/Process: Sending signal. PID: 7874 SIG: 9

我的代码出了什么问题?

1 个答案:

答案 0 :(得分:3)

从我所看到的情况来看,当你的方法startRepeatingTask()没有初始化时,你可以调用location1和location2。它们需要初始化并处理null异常,就像在getspeed中一样。

Location location1 = null;
Location location2 = null;

/.../

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

/.../


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

看到你的堆栈跟踪后:
空指针异常显示在您使用过的两行:

PackageManager pm = getPackageManager();

首先: 在您的课程范围内声明PackageManager pm; 一次,然后在您的课程中初始化它 onCreate

pm= getPackageManager();

通过在Activity类和onCreate中声明PackckageManager pm = getPackageManager(),您是否意识到您正在处理应用程序中具有相同名称和不同范围的两个单独实例。

我对你的代码感到困惑,说实话。

所以我建议以下内容除了我上面所说的,你需要研究并尝试理解以下内容:

  1. 范围
  2. 初始化对象 - &gt;调用未初始化的对象将导致nullpointerexception。
  3. PackageManagers
  4. 这将真正有助于您的进步。在这个网站上解释这一切非常困难。所以我提供了一些指向每个点的链接。

    1. java-made-easy.com/variable-scope
    2. Object initialization in Java
    3. PackageManagerhow-to-get-list-of-installed-apps-in-androidthe github repository