首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Android,Google,JSON问题。获取空指针异常

Android,Google,JSON问题。获取空指针异常
EN

Stack Overflow用户
提问于 2017-04-17 22:56:11
回答 1查看 181关注 0票数 1

我正在开发一个小型人事应用程序来帮助我学习Android和Java。

让我首先告诉大家,谷歌地图部分正在应用程序中工作。当应用程序启动并获得手机的正确当前位置时,它正在加载。

而且,我的JSON功能也很好。这些数据是使用API从www.wunderground.com中提取出来的,我的代码获取了我所要求的内容,并创建了一个Arraylist,并将其填充得很好,并在应用程序中按其应有的方式显示。

问题是,我正在尝试获取一些JSON数据,并创建一个google地图标记对象并在地图上显示。

下面是我的代码:

这个方法是从JsonData.java获得的JSON数据创建一个Cyclone,我在下面展示了这一点。

Cyclone.java

代码语言:javascript
复制
public class Cyclone {

// Category of the cyclone (e.g. -2, -1, 0, 1, 2, 3, 4, or 5)
private int category;

// Latitude & Longitude of Cyclone
private float latitude, longitude;

// Cyclone name
private String name;

// Cyclone heading (N, S, E, or W)
private String heading;

// Wind speed in Cyclone
private String windSpeedKnots;

// Url to website with Cyclone data
private String url;

/**
* CONSTRUCTOR
* Create a new Cyclone object.
*
* @param constCategory is the category of the cyclone (e.g. -2, -1, 0, 1, 2, 3, 4, or 5)
* @param constLatitude is the Latitude of the cyclone
* @param constLongitude is the Longitude of the cyclone
* @param constName is the name of the Cyclone
* @param constHeading is the direction the cyclone is moving
* @param constWindSpeedKnots is the speed of the wind the Cyclone is producing
* @param constUrl is the url of the website that is providing the data
*/
public Cyclone(int constCategory, float constLatitude, float constLongitude,String constName,
               String constHeading, String constWindSpeedKnots, String constUrl) {

    category = constCategory;
    latitude = constLatitude;
    longitude = constLongitude;
    name = constName;
    heading = constHeading;
    windSpeedKnots = constWindSpeedKnots;
    url = constUrl;
}

/**
 * Setting public getters for the private variables above for use of other classes
 */
// Get the storm category
public int getCategory() {
    return category;
}

// Get the cyclones Latitude
public float getLatitude() {
    return latitude;
}

//Get the cyclones Longitude
public float getLongitude() {
    return longitude;
}

// Get the cyclones name
public String getName() {
    return name;
}

// Get the cyclones heading
public String getHeading() {
    return heading;
}

// Get the cyclones wind speed
public String getWindSpeedKnots() {
    return windSpeedKnots;
}

// Get the Url
public String getUrl() {
    return url;
}

}

这个类从www.wunderground.com中提取JSON数据。我已经从底部剪掉了一堆代码。如果什么都不返回的话,它通常只是处理异常。JsonData.java

代码语言:javascript
复制
/**
 * Return a list of {@link Cyclone} objects that has been built up from
 * parsing a JSON response.
 */
public static ArrayList<Cyclone> extractFeatureFromJson(String cycloneJSON) {

    // Create an empty ArrayList to start adding Cyclones to
    ArrayList<Cyclone> cyclones = new ArrayList<>();

    // Try to parse the cycloneJSON response string. If there's a problem with the way the JSON
    // is formatted, a JSONException exception object will be thrown.
    // Catch the exception , and print the error message to the logs.

    try {

        JSONObject rootJsonObject = new JSONObject(cycloneJSON);

        // Create JSONArray associated with the key called "currenthurricane", which represents
        // a list of cyclones from JSON response.
        JSONArray currentHurricaneArray = rootJsonObject.getJSONArray("currenthurricane");

        /**
         * Loop through each section in the currentHurricaneArray array & create an
         * {@link Cyclone} object for each one
         *
         */
        for (int i = 0; i < currentHurricaneArray.length(); i++) {
            //Get cyclone JSONObject at position i in the array
            JSONObject cycloneProperties = currentHurricaneArray.getJSONObject(i);

            // Extract "stormInfo" object
            JSONObject stormInfo = cycloneProperties.optJSONObject("stormInfo");
            //Extract “stormName_Nice” & "requesturl" for Cyclone's name and url
            String name = stormInfo.optString("stormName_Nice");
            String url = stormInfo.optString("wuiurl");

            // Extract "Current" object
            JSONObject current = cycloneProperties.optJSONObject("Current");
            // Extract "SaffirSimpsonCategory" key
            int category = current.optInt("SaffirSimpsonCategory");

            //Extract "Lat" & "Lon" keys to get cyclone position
            float latitude = (float) current.optDouble("lat");
            float longitude = (float) current.optDouble("lon");

            //Extract "WindSpeed" object
            JSONObject windSpeed = current.optJSONObject("WindSpeed");
            //Extract wind speed in "Knots" Key
            int Kts = windSpeed.optInt("Kts");
            String knots = Kts + " Knots";

            //Extract "Movement" object
            JSONObject movement = current.optJSONObject("Movement");
            //Extract movement direction in "Text" key
            String direction = movement.optString("Text");

            Cyclone cyclone = new Cyclone(category, latitude, longitude, name, direction, knots, url);
            //Add new cyclone to list
            cyclones.add(cyclone);
        }

我会在这里展示相关的细节。

MainActivity.java

代码语言:javascript
复制
public class MainActivity extends AppCompatActivity implements
    LoaderManager.LoaderCallbacks<List<Cyclone>>,
    OnMapReadyCallback,
    GoogleApiClient.ConnectionCallbacks,
    GoogleApiClient.OnConnectionFailedListener,
    LocationListener {

....

//Creating a Cyclone object, calling it from Cyclone.java
    Cyclone trackedCyclone = null;

    //getting the three bits of info I need/want (Name, lat, lon)
    String name = trackedCyclone.getName();
    float lat = trackedCyclone.getLatitude();
    float lon = trackedCyclone.getLongitude();

 @Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.cyclone_list);
....

// Obtain the SupportMapFragment and get notified when the map is ready
    //Calling up the map fragment from cyclone_list.xml
    MapFragment mapFragment = (MapFragment) getFragmentManager().findFragmentById(R.id.google_map);
    mapFragment.getMapAsync(this);

....

@Override
public void onMapReady(GoogleMap mapLocalInstance) {
    //Setting mapReady to true
    mapReady = true;

    //displaying cyclone map marker on the map
    LatLng cycloneMarker = new LatLng(lat, lon);
    googleMap.addMarker(new MarkerOptions().position(cycloneMarker).title(name));

    //Loading local instance map from Callback
    googleMap = mapLocalInstance;
    googleMap.setMapType(GoogleMap.MAP_TYPE_SATELLITE);

    //checks for permission using the Support library before enabling the My Location layer
    //Initialize Google Play Services
    if (android.os.Build.VERSION.SDK_INT >= M) {
        if (ContextCompat.checkSelfPermission(this,
                Manifest.permission.ACCESS_FINE_LOCATION)
                == PackageManager.PERMISSION_GRANTED) {
            buildGoogleApiClient();
            googleMap.setMyLocationEnabled(true);
        }
    } else {
        buildGoogleApiClient();
        googleMap.setMyLocationEnabled(true);
    }
}

当应用程序启动时,它会崩溃,如下所示:

04-17 16:11:29.546 7028-7028/com.palarran.cyclopsE/AndroidRuntime:致命异常:主进程: com.palarran.cycloops,PID: 7028 java.lang.NullPointerException:尝试在java.lang.NullPointerException上调用空对象引用上的虚拟方法“java.lang.String com.palarran.cycloops.Cyclone.getName()”( com.google.android.gms.maps.MapFragment$zza$1.zza(Unknown来源))在com.google.android.gms.maps.internal.zzt$zza.onTransact(Unknown来源)在com.google.android.gms.maps.internal.bw.a(:com.google.android.gms.DynamiteModulesB:82的android.os.Binder.transact(Binder.java:499))在com.google.maps.api.android.lib6.impl.bf.run(:com.google.android.gms.DynamiteModulesB:1805) at android.os.Handler.handleCallback(Handler )。android.os.Handler.dispatchMessage(Handler.java:95) at android.os.Looper.loop(Looper.java:154)在android.app.ActivityThread.main(ActivityThread.java:6121) at java.lang.reflect.Method.invoke(原生方法)在com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:889) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:779)

我在Android和Java上玩了一年左右。所以OOP对我来说还是很新鲜的。我不太明白。我大概有一半认为问题在于,由于JsonData.java类正在创建一个JsonArray,我可能无法使用Cyclone.java类调用我需要的部分。如果是这样的话,那么我是否创建了不同的JsonArray?对我来说很笨重?但我真的不知道。

谢谢你能提供的任何帮助。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-04-18 02:40:27

代码语言:javascript
复制
//Creating a Cyclone object, calling it from Cyclone.java
Cyclone trackedCyclone = null;

// Here is a problem. You need to init your trackedCyclone
trackedCyclone = new Cyclone(??????????);

//getting the three bits of info I need/want (Name, lat, lon)
String name = trackedCyclone.getName();
float lat = trackedCyclone.getLatitude();
float lon = trackedCyclone.getLongitude();

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/43460921

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档