【问题标题】:null pointer exception when trying to start new activity尝试开始新活动时出现空指针异常
【发布时间】:2016-08-19 07:27:56
【问题描述】:

我对 java 和 android studio 还是很陌生。当用户在地图上指定点的一定距离内时,我正在尝试启动一个新活动。

以下类确定用户与每个点的距离,当用户在一定距离内(10m)时,我希望启动一个新活动,用户将能够根据位置回答问题。

但是,当我尝试启动新活动时,出现错误:

E/AndroidRuntime: FATAL EXCEPTION: main

Process: uk.ac.ucl.cege.cegeg077.ucfapwh.firstapp, PID: 6616
    java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.Context android.content.Context.getApplicationContext()' on a null object reference
    at android.content.ContextWrapper.getApplicationContext(ContextWrapper.java:106)
    at uk.ac.ucl.cege.cegeg077.ucfapwh.firstapp.CustomLocationListener.onLocationChanged(CustomLocationListener.java:67)
    at android.location.LocationManager$ListenerTransport._handleMessage(LocationManager.java:281)
    at android.location.LocationManager$ListenerTransport.access$000(LocationManager.java:210)
    at android.location.LocationManager$ListenerTransport$1.handleMessage(LocationManager.java:226)
    at android.os.Handler.dispatchMessage(Handler.java:102)
    at android.os.Looper.loop(Looper.java:135)
    at android.app.ActivityThread.main(ActivityThread.java:5343)
    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:905)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:700)

这是我目前的代码:

import android.app.Activity;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
import java.lang.reflect.Array;
import java.util.ArrayList;

public class CustomLocationListener extends Map implements LocationListener {
public Map parentActivity ;
public ArrayList<GeoPoint> coordList;
// this method is called every time the user moves around - i.e. changes     location
// it pops up a toast message with the new coordinates
public void onLocationChanged(Location location) {

    // now measure distance from all the pre-set proximity alerts
    for (int i = 0; i < coordList.size(); i++) {

        // create GeoPoint object for each pair of coordinates
        GeoPoint gp = coordList.get(i);

        // create Location object
        Location fixedLoc = new Location("one");

        // get lat and lng values from GeoPoint object
        Float lat = Float.valueOf(String.valueOf(gp.getLatitude()));
        Float lng = Float.valueOf(String.valueOf(gp.getLongitude()));

        // set location for proximity alert
        fixedLoc.setLatitude(lat);
        fixedLoc.setLongitude(lng);

        // use Android distanceTo function to calculate the distances
        float distance = location.distanceTo(fixedLoc);

        Log.i("****DISTANCE****",String.valueOf(distance));
        Log.i("*****FIXEDLOC****", fixedLoc.toString());

        for (int j = 0; j < coordList.size(); j++ ) {

            if (i == j && distance < 120) {

                GeoPoint geoPoint = coordList.get(j);

                Log.i("****PROXI LAT*****", geoPoint.getLatitude().toString());
                Log.i("****PROXI LNG****", geoPoint.getLongitude().toString());

                Intent quizIntent = new Intent(getApplicationContext(),Questions.class);
                startActivity(quizIntent);

            }
        }

    }

}

// these methods are called when the GPS is switched on or off
// and will allow the App to warn the user and then
// shut down without an error
public void onProviderDisabled(String s) {
}
public void onProviderEnabled(String s) {
}

// this method is required by the LocationListener
// we do not need to do anything here
// but in a full implementation this could be used to react when the GPS signal is not available
public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
    // TODO Auto-generated method stub

}

}

对糟糕的格式表示歉意。任何帮助将不胜感激。

【问题讨论】:

    标签: java android android-studio android-activity


    【解决方案1】:

    已解决:

    要从非活动类中检索上下文,需要以下代码:

    private Context context;
    
    public NonActivityClass(Context context) {
        this.context = context.getApplicationContext();
    }
    

    然后触发 Intent 并启动新活动:

                    Intent i = new Intent(context, Activity.class);
                    i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    context.startActivity(i);
    

    感谢您的帮助。

    get Context in non-Activity class

    【讨论】:

      【解决方案2】:

      您不能使用应用程序上下文来启动应用程序。您应该使用活动上下文。如果(猜测)地图是您的活动,则更新开始活动代码

      Intent quizIntent = new Intent(this,Questions.class);
                      startActivity(quizIntent);
      

      有关为什么应用程序上下文不能用于启动活动的更多详细信息https://possiblemobile.com/2013/06/context/

      【讨论】:

      • 按照您的建议,我收到以下错误:java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.content.Context.getPackageName()' on a null object参考
      【解决方案3】:

      在我看来,您有两种选择:

      1. NameOfYourActivity 内部声明CustomLocationListener 为私有。

      接下来,将 Intent 构造函数从 getApplicationContext() 更改为 NameOfYourActivity.this

      1. NameOfYourActivityContext设置为CustomLocationListener中的属性,然后将Intent构造函数从getApplicationContext()更改 到上下文属性。

      希望对你有帮助

      【讨论】:

        【解决方案4】:

        你得到 null 因为你的类没有扩展 android 活动。您可以在非活动类中获取应用程序上下文,如 here 所解释的。

        【讨论】:

        • 我使用了以下代码,我不确定我所做的是否正确:public Context context; public CustomLocationListener(Context context) { this.context=context; }。然后我用以下内容声明了一个新实例:Intent quizIntent = new Intent(new CustomLocationListener(this),Questions.class)。但是我得到了相同的 java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.content.Context.getPackageName() on a null object 错误
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2017-07-09
        • 1970-01-01
        • 1970-01-01
        • 2020-11-13
        • 1970-01-01
        • 1970-01-01
        • 2014-04-12
        相关资源
        最近更新 更多