异步的Andr​​oid JSON解析器android-空指针异常 [英] Async android json parser android- null pointer exception

查看:138
本文介绍了异步的Andr​​oid JSON解析器android-空指针异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

从我的最后一个职位,被T知道,我需要使用JSON用于从URL解析异步任务,都做相同的,附在下面,

 公共类ReadJson扩展ListActivity {
私有静态字符串URL =htt​​p://docs.blackberry.com/sampledata.json;私有静态最后弦乐TAG_VTYPE =vehicleType;
私有静态最后弦乐TAG_VCOLOR =vehicleColor;
私有静态最后弦乐TAG_FUEL =燃料;
私有静态最后弦乐TAG_TREAD =treadType;ArrayList的<&HashMap的LT;字符串,字符串>> jsonlist =新的ArrayList<&HashMap的LT;字符串,字符串>>();LV的ListView;
@覆盖
保护无效的onCreate(捆绑savedInstanceState){
    super.onCreate(savedInstanceState);
    的setContentView(R.layout.activity_read_json);
    新ProgressTask(ReadJson.this).execute();
}
私有类ProgressTask扩展的AsyncTask<弦乐,太虚,布尔> {
    私人ProgressDialog对话框;
    //私有列表<消息>消息;
    公共ProgressTask(ListActivity活动){
        上下文=活动;
        对话框=新ProgressDialog(背景);
    }
    / **进度对话框,显示该备份处理用户。 * /
    / **应用程序上下文。 * /
    私人上下文的背景下;
    在preExecute保护无效(){
        this.dialog.setMessage(进步启动);
        this.dialog.show();
    }
    @覆盖
    保护无效onPostExecute(最终布尔成功){
        如果(dialog.isShowing()){
            dialog.dismiss();
        }
        ListAdapter适配器=新SimpleAdapter(背景下,jsonlist,
                R.layout.list_item,新的String [] {TAG_VTYPE,TAG_VCOLOR,
                TAG_FUEL,TAG_TREAD},新的INT [] {
                R.id.vehicleType,R.id.vehicleColor,R.id.fuel,
                R.id.treadType});
        setListAdapter(适配器);
        //选择单个ListView项
        LV = getListView();
    }
    保护布尔doInBackground(最终字符串参数... args){
        JSONParser jParser =新JSONParser();
        JSONArray JSON = jParser.getJSONFromUrl(URL);
        的for(int i = 0; I< json.length();我++){
            尝试{
                JSONObject的C = json.getJSONObject(I)
                字符串由Vtype = c.getString(TAG_VTYPE);
                字符串vcolor = c.getString(TAG_VCOLOR);
                字符串vfuel = c.getString(TAG_FUEL);
                字符串vtread = c.getString(TAG_TREAD);
                HashMap的<字符串,字符串>地图=新的HashMap<字符串,字符串>();
                map.put(TAG_VTYPE,由Vtype);
                map.put(TAG_VCOLOR,vcolor);
                map.put(TAG_FUEL,vfuel);
                map.put(TAG_TREAD,vtread);
                jsonlist.add(地图);
            }赶上(JSONException E){
                e.printStackTrace();
            }
        }
        返回null;
    }
}

}

当我执行,我得到空指针异常错误的行ASYC后台执行,的for(int i = 0; I< json.length();我++),试了好东西,但没有工作,任何帮助将gr8ly AP preciated !!

编辑1:添加解析器code

 进口java.io.BufferedReader中;
进口java.io.IOException异常;
进口的java.io.InputStream;
进口java.io.InputStreamReader中;
进口java.io.UnsupportedEncodingException;进口org.apache.http.HttpEntity;
进口org.apache.http.Htt presponse;
进口org.apache.http.StatusLine;
进口org.apache.http.client.ClientProtocolException;
进口org.apache.http.client.HttpClient;
进口org.apache.http.client.methods.HttpGet;
进口org.apache.http.client.methods.HttpPost;
进口org.apache.http.impl.client.DefaultHttpClient;
进口org.json.JSONArray;
进口org.json.JSONException;
进口org.json.JSONObject;进口android.util.Log;公共类JSONParser {    静态InputStream为= NULL;
    静态JSONArray jarray = NULL;
    静态JSON字符串=;    //构造
    公共JSONParser(){    }    公共JSONArray getJSONFromUrl(字符串URL){        StringBuilder的建设者=新的StringBuilder();
        HttpClient的客户端=新DefaultHttpClient();
        HTTPGET HTTPGET =新HTTPGET(URL);
        尝试{
            HTT presponse响应= client.execute(HTTPGET);
            状态行状态行= response.getStatusLine();
            INT状态code = statusLine.getStatus code();
            如果(状态code == 200){
                HttpEntity实体= response.getEntity();
                InputStream的内容= entity.getContent();
                读者的BufferedReader =新的BufferedReader(新的InputStreamReader(内容));
                串线;
                而((行= reader.readLine())!= NULL){
                    builder.append(线);
                }
            }其他{
                Log.e(==>中,无法下载文件);
            }
        }赶上(ClientProtocolException E){
            e.printStackTrace();
        }赶上(IOException异常五){
            e.printStackTrace();
        }        //尝试分析字符串到一个JSON对象
        尝试{
            jarray =新JSONArray(builder.toString());
        }赶上(JSONException E){
            Log.e(JSON解析器,错误分析数据+ e.toString());
        }        //返回JSON字符串
        返回jarray;    }
}


解决方案

试试这个获取JSON

 公共静态字符串getJSONString(字符串URL){
    字符串jsonString = NULL;
    HttpURLConnection的linkConnection = NULL;
    尝试{
        网址linkurl =新的URL(网址);
        linkConnection =(HttpURLConnection类)linkurl.openConnection();
        INT响应code = linkConnection.getResponse code();
        如果(响应code == HttpURLConnection.HTTP_OK){
            InputStream的linkinStream = linkConnection.getInputStream();
            ByteArrayOutputStream BAOS =新ByteArrayOutputStream();
            INT J = 0;
            而((J = linkinStream.read())!= - 1){
                baos.write(J);
            }
            字节[]数据= baos.toByteArray();
            jsonString =新的String(数据);
        }
    }赶上(例外五){
        e.printStackTrace();
    } {最后
        如果(linkConnection!= NULL){
            linkConnection.disconnect();
        }
    }
    返回jsonString;
}公共静态布尔isNetworkAvailable(活动活动){
    ConnectivityManager连接=(ConnectivityManager)活动
            .getSystemService(Context.CONNECTIVITY_SERVICE);
    如果(连接== NULL){
        返回false;
    }其他{
        的NetworkInfo []信息= connectivity.getAllNetworkInfo();
        如果(信息!= NULL){
            的for(int i = 0; I< info.length;我++){
                如果(资讯[I] .getState()== NetworkInfo.State.CONNECTED){
                    返回true;
                }
            }
        }
    }
    返回false;
}

使用isNetworkAvailable检查连接

和我分析这样

  {尝试                JSONObject的jObjectm =新的JSONObject(结果);
                JSONObject的jObject = jObjectm.getJSONObject(项目);
                  如果(jObject!= NULL)
                  {
                    迭代器<>的iterator1 = jObject.keys();
                         LinkedHashMap的<弦乐,LinkedHashMap的<弦乐,对象> > inneritem =新的LinkedHashMap<弦乐,LinkedHashMap的<弦乐,对象> >();
                        而(iterator1.hasNext()){
                            项目hashitem =新项目();
                               字符串键1 =(字符串)iterator1.next();
                               JSONObject的jObject1 = jObject.getJSONObject(键1);
                               迭代器<>迭代= jObject1.keys();
                                 LinkedHashMap的<弦乐,对象> inneritem1 =新的LinkedHashMap<弦乐,对象>();
                                而(iterator.hasNext()){
                                    字符串键=(字符串)iterator.next();                                  inneritem1.put(键,jObject1.get(密钥));
                                }
                                 hashitem.setItem(KEY1,inneritem1);
                                inneritem.put(KEY1,inneritem1);
                                arrayOfList.add(hashitem);
                        }
                  }
                }赶上(JSONException E){                    的System.out.println(NO JSO​​N数据中发现);
                }

From my last post, got t know that, i need to use async task for json parsing from url, have done the same and attached below,

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

}

When i execute this, i get null pointer exception for error executing in asyc background in the line, for (int i = 0; i < json.length(); i++), tried several things but not working, any help will be gr8ly appreciated!!

Edit 1: added parser code

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;

    }
}

解决方案

Try this for getting 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;
}

use isNetworkAvailable for checking connection

and i parsed this way

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

这篇关于异步的Andr​​oid JSON解析器android-空指针异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆