我一直在使用JSON对象调用获取nullpointer异常

时间:2014-10-16 14:05:22

标签: java android android-gradle

出于某种原因,我通过双重解析得到了一个nullpointer异常。在进一步调查后,我的JSON对象似乎有些问题,但我不知道问题是什么。我从openweathermap api中提取JSON数据。我scrassfully拉,并将数据打印到log.i,但是当我尝试使用JSONObject访问时,我收到一个错误。请帮忙。

代码:

package com.anuraagy.myweather;

import android.app.Activity;
import android.app.ActionBar;
import android.app.Fragment;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.*;
import android.content.*;
import android.os.Build;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;


public class MyActivity extends Activity {
    private String s;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_my);
        if (savedInstanceState == null) {
            getFragmentManager().beginTransaction()
                    .add(R.id.container, new PlaceholderFragment())
                    .commit();
        }
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.my, 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) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    /**
     * A placeholder fragment containing a simple view.
     */
    public static class PlaceholderFragment extends Fragment {
        private JSONObject myObject,mainObject,nameObject;
        private ImageView myImage;
        private TextView titleText;
        private String hello,weatherName,max_temp,min_temp;
        public PlaceholderFragment() {
        }

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                 Bundle savedInstanceState) {
            View rootView = inflater.inflate(R.layout.fragment_my, container, false);


            RequestTask task = new RequestTask();
            task.execute(new String[]{"http://api.openweathermap.org/data/2.5/weather?q=Ashburn&APPID=970bf0e4978dae293b065f8f2830ba58"});

            return rootView;
        }


        public class RequestTask extends AsyncTask<String, String, String> {
            private TextView myView;
            private String s;
            @Override
            protected String doInBackground(String... uri) {
                HttpClient httpclient = new DefaultHttpClient();
                HttpResponse response;
                String responseString = null;
                try {
                    response = httpclient.execute(new HttpGet(uri[0]));
                    StatusLine statusLine = response.getStatusLine();
                    if (statusLine.getStatusCode() == HttpStatus.SC_OK) {
                        ByteArrayOutputStream out = new ByteArrayOutputStream();
                        response.getEntity().writeTo(out);
                        out.close();
                        responseString = out.toString();
                    } else {
                        //Closes the connection.
                        response.getEntity().getContent().close();
                        throw new IOException(statusLine.getReasonPhrase());
                    }
                } catch (ClientProtocolException e) {
                    //TODO Handle problems..
                } catch (IOException e) {
                    //TODO Handle problems..
                }

                Log.i("", responseString);
                return responseString;
            }

            @Override
            protected void onPostExecute(String result){
                Log.i("","hello");
                super.onPostExecute(result);
                try {
                     myObject = new JSONObject(result);
                     nameObject = myObject.getJSONObject("weather");
                     weatherName = nameObject.getString("main");
                     mainObject = myObject.getJSONObject("main");
                    Log.i("Wather Name",weatherName);
                    Log.i("mainObject",mainObject.toString());
                     hello = mainObject.getString("temp");
                     max_temp = mainObject.getString("temp_max");
                     min_temp = mainObject.getString("temp_min");


                } catch(JSONException jsonException){

                }
                double f = Double.parseDouble(hello);
                double max = Double.parseDouble(max_temp);
                double min = Double.parseDouble(min_temp);

                double realMax = (max - 273)* 1.8 + 32;
                double realMin = (min - 273)* 1.8 + 32;
                double realTemp = (max - 273)* 1.8 + 32;

                int myMax = (int)realMax;
                int myMin = (int)realMin;

                int myWeather = (int)realTemp;


                titleText = (TextView)getActivity().findViewById(R.id.textView3);
                String fe = titleText.getText().toString();
                fe.replace("definetly",weatherName);
                myView = (TextView)getActivity().findViewById(R.id.textView);

//                if()
//                {
//
//                }
//                else
//                {
//
//                }
                myImage = (ImageView)getActivity().findViewById(R.id.imageView);
                myImage.setImageResource(R.drawable.clearnight);
                String weather = myWeather + "";
                myView.setText(weather + (char) 0x00B0 +"F");
//                //Do anything with response..
            }
        }
    }
}

错误:

10-16 10:01:26.398      664-664/com.anuraagy.myweather E/Trace﹕ error opening trace file: No such file or directory (2)
10-16 10:01:35.058      664-668/com.anuraagy.myweather D/dalvikvm﹕ GC_CONCURRENT freed 75K, 2% free 11112K/11335K, paused 17ms+3ms, total 312ms
10-16 10:01:35.058      664-664/com.anuraagy.myweather D/dalvikvm﹕ WAIT_FOR_CONCURRENT_GC blocked 282ms
10-16 10:01:35.498      664-664/com.anuraagy.myweather D/gralloc_goldfish﹕ Emulator without GPU emulation detected.
10-16 10:01:38.388      664-680/com.anuraagy.myweather I/﹕ {"coord":{"lon":-77.49,"lat":39.04},"sys":{"type":1,"id":2856,"message":0.0194,"country":"US","sunrise":1413458470,"sunset":1413498574},"weather":[{"id":701,"main":"Mist","description":"mist","icon":"50d"},{"id":721,"main":"Haze","description":"haze","icon":"50d"},{"id":741,"main":"Fog","description":"fog","icon":"50d"}],"base":"cmc stations","main":{"temp":288.03,"pressure":1008,"humidity":100,"temp_min":286.15,"temp_max":290.15},"wind":{"speed":2.86,"deg":261.502},"clouds":{"all":90},"dt":1413468071,"id":4744870,"name":"Ashburn","cod":200}
10-16 10:01:38.398      664-664/com.anuraagy.myweather I/﹕ hello
10-16 10:01:38.438      664-664/com.anuraagy.myweather D/AndroidRuntime﹕ Shutting down VM
10-16 10:01:38.438      664-664/com.anuraagy.myweather W/dalvikvm﹕ threadid=1: thread exiting with uncaught exception (group=0x40a13300)
10-16 10:01:38.448      664-664/com.anuraagy.myweather E/AndroidRuntime﹕ FATAL EXCEPTION: main
    java.lang.NullPointerException
            at java.lang.StringToReal.parseDouble(StringToReal.java:244)
            at java.lang.Double.parseDouble(Double.java:295)
            at com.anuraagy.myweather.MyActivity$PlaceholderFragment$RequestTask.onPostExecute(MyActivity.java:141)
            at com.anuraagy.myweather.MyActivity$PlaceholderFragment$RequestTask.onPostExecute(MyActivity.java:91)
            at android.os.AsyncTask.finish(AsyncTask.java:631)
            at android.os.AsyncTask.access$600(AsyncTask.java:177)
            at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:644)
            at android.os.Handler.dispatchMessage(Handler.java:99)
            at android.os.Looper.loop(Looper.java:137)
            at android.app.ActivityThread.main(ActivityThread.java:4745)
            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:786)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
            at dalvik.system.NativeStart.main(Native Method)

2 个答案:

答案 0 :(得分:3)

小心 - &#34;天气&#34;是JSONArray,而不是JSONObject。 NullPointerException可能是由于这个原因。

尝试使用myObject.getJSONArray("weather"),然后从里面遍历JSONObjects。

有关最后一部分的更多信息,请参见此处:Accessing members of items in a JSONArray with Java

答案 1 :(得分:0)

看起来myObject没有名为"temp"的项目,所以:
- 在第133行,您将hello设置为null
- 在第141行,您将null传递给Double.parseDouble()
- 获取您的例外情况,因为课程Double无法消化null 那就是它!

在调试器中检查它,但我几乎可以肯定 - 根据您的堆栈跟踪