异步android json解析器android- null指针异常

时间:2013-03-29 03:46:02

标签: android json android-asynctask

从我上一篇文章中得知,我需要使用异步任务从url解析json,做了同样的事情并附在下面,

public class ReadJson extends ListActivity {
private static String url = "http://docs.blackberry.com/sampledata.json";

private static final String TAG_VTYPE = "vehicleType";
private static final String TAG_VCOLOR = "vehicleColor";
private static final String TAG_FUEL = "fuel";
private static final String TAG_TREAD = "treadType";

ArrayList<HashMap<String, String>> jsonlist = new ArrayList<HashMap<String, String>>();

ListView lv ;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_read_json);
    new ProgressTask(ReadJson.this).execute();
}
private class ProgressTask extends AsyncTask<String, Void, Boolean> {
    private ProgressDialog dialog;
    // private List<Message> messages;
    public ProgressTask(ListActivity activity) {
        context = activity;
        dialog = new ProgressDialog(context);
    }
    /** progress dialog to show user that the backup is processing. */
    /** application context. */
    private Context context;
    protected void onPreExecute() {
        this.dialog.setMessage("Progress start");
        this.dialog.show();
    }
    @Override
    protected void onPostExecute(final Boolean success) {
        if (dialog.isShowing()) {
            dialog.dismiss();
        }
        ListAdapter adapter = new SimpleAdapter(context, jsonlist,
                R.layout.list_item, new String[] { TAG_VTYPE, TAG_VCOLOR,
                TAG_FUEL, TAG_TREAD }, new int[] {
                R.id.vehicleType, R.id.vehicleColor, R.id.fuel,
                R.id.treadType });
        setListAdapter(adapter);
        // selecting single ListView item
        lv = getListView();
    }
    protected Boolean doInBackground(final String... args) {
        JSONParser jParser = new JSONParser();
        JSONArray json = jParser.getJSONFromUrl(url);
        for (int i = 0; i < json.length(); i++) {
            try {
                JSONObject c = json.getJSONObject(i);
                String vtype = c.getString(TAG_VTYPE);
                String vcolor = c.getString(TAG_VCOLOR);
                String vfuel = c.getString(TAG_FUEL);
                String vtread = c.getString(TAG_TREAD);
                HashMap<String, String> map = new HashMap<String, String>();
                map.put(TAG_VTYPE, vtype);
                map.put(TAG_VCOLOR, vcolor);
                map.put(TAG_FUEL, vfuel);
                map.put(TAG_TREAD, vtread);
                jsonlist.add(map);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        return null;
    }
}

}

当我执行此操作时,我在行中的asyc背景中执行错误时得到空指针异常,因为(int i = 0; i&lt; json.length(); i ++),尝试了几件事但没有工作,任何帮助将受到赞赏!!

编辑1:添加了解析器代码

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
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.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.util.Log;

public class JSONParser {

    static InputStream is = null;
    static JSONArray jarray = null;
    static String json = "";

    // constructor
    public JSONParser() {

    }

    public JSONArray getJSONFromUrl(String url) {

        StringBuilder builder = new StringBuilder();
        HttpClient client = new DefaultHttpClient();
        HttpGet httpGet = new HttpGet(url);
        try {
            HttpResponse response = client.execute(httpGet);
            StatusLine statusLine = response.getStatusLine();
            int statusCode = statusLine.getStatusCode();
            if (statusCode == 200) {
                HttpEntity entity = response.getEntity();
                InputStream content = entity.getContent();
                BufferedReader reader = new BufferedReader(new InputStreamReader(content));
                String line;
                while ((line = reader.readLine()) != null) {
                    builder.append(line);
                }
            } else {
                Log.e("==>", "Failed to download file");
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        // try parse the string to a JSON object
        try {
            jarray = new JSONArray( builder.toString());
        } catch (JSONException e) {
            Log.e("JSON Parser", "Error parsing data " + e.toString());
        }

        // return JSON String
        return jarray;

    }
}

3 个答案:

答案 0 :(得分:0)

我认为你正在使用this JSONParser。似乎正在发生的事情是你有一个没有生成有效JSON的URL,这会导致Exception被抛出并在整个过程中的某个类中被捕获 - 最有可能出现在jObj = new JSONObject(json);线。最终结果是返回的变量仍为null。因此,当您在循环中调用json.length()时,您尝试在length()对象上调用null。您应该在进入循环之前对其进行检查,以确保它不是null

答案 1 :(得分:0)

我认为,您没有从服务器获取有效的JSON格式。在解析之前检查从服务器获取的响应,这里是代码片段,这里传递url并在logcat中获取yourReponseInJSONStr检查响应字符串是否采用正确的JSON格式,然后进行解析操作。

 try {
                HttpClient httpclient = new DefaultHttpClient();
                HttpPost httppost = new HttpPost(
                        url);

            List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);

            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
            ResponseHandler<String> responseHandler = new BasicResponseHandler();

            String yourReponseInJSONStr = httpclient.execute(httppost,
                    responseHandler);

            Log.d("yourReponseInJSONStr ", yourReponseInJSONStr );

                    JSONObject yourJsonObj = new JSONObject(yourReponseInJSONStr);


} catch (Exception e) {
            e.printStackTrace();
        }

你也可以继续解析这段代码,希望这对你有所帮助,

答案 2 :(得分:0)

尝试获取json

public static String getJSONString(String url) {
    String jsonString = null;
    HttpURLConnection linkConnection = null;
    try {
        URL linkurl = new URL(url);
        linkConnection = (HttpURLConnection) linkurl.openConnection();
        int responseCode = linkConnection.getResponseCode();
        if (responseCode == HttpURLConnection.HTTP_OK) {
            InputStream linkinStream = linkConnection.getInputStream();
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            int j = 0;
            while ((j = linkinStream.read()) != -1) {
                baos.write(j);
            }
            byte[] data = baos.toByteArray();
            jsonString = new String(data);
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (linkConnection != null) {
            linkConnection.disconnect();
        }
    }
    return jsonString;
}

public static boolean isNetworkAvailable(Activity activity) {
    ConnectivityManager connectivity = (ConnectivityManager) activity
            .getSystemService(Context.CONNECTIVITY_SERVICE);
    if (connectivity == null) {
        return false;
    } else {
        NetworkInfo[] info = connectivity.getAllNetworkInfo();
        if (info != null) {
            for (int i = 0; i < info.length; i++) {
                if (info[i].getState() == NetworkInfo.State.CONNECTED) {
                    return true;
                }
            }
        }
    }
    return false;
}

使用isNetworkAvailable检查连接

我用这种方式解析

try {

                JSONObject jObjectm = new JSONObject(result);
                JSONObject jObject=jObjectm.getJSONObject("items");
                  if(jObject!=null)
                  {
                    Iterator<?> iterator1=jObject.keys();
                         LinkedHashMap<String,LinkedHashMap<String, Object> > inneritem = new LinkedHashMap<String, LinkedHashMap<String, Object> >();
                        while (iterator1.hasNext() ){
                            Item hashitem=new Item();
                               String key1 = (String)iterator1.next();
                               JSONObject jObject1=jObject.getJSONObject(key1);
                               Iterator<?> iterator=jObject1.keys();
                                 LinkedHashMap<String, Object> inneritem1 = new LinkedHashMap<String, Object>();
                                while (iterator.hasNext() ){


                                    String key =(String) iterator.next();

                                  inneritem1.put(key, jObject1.get(key));


                                }
                                 hashitem.setItem(key1,inneritem1);
                                inneritem.put(key1,inneritem1);
                                arrayOfList.add(hashitem); 
                        }




                  }
                } catch (JSONException e) {

                    System.out.println("NO Json data found");
                }