2013-03-29 111 views
0

從我的最後一個職位,被T了知道,我需要使用JSON從URL解析異步任務,也做了同樣的和下方連接,異步的Android JSON解析器android-空指針異常

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

} (int i = 0; i < 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; 

    } 
} 
+0

您是否嘗試過調試並檢查數據是否正確解析? –

+0

進行調試並檢查'JSONArray json'中是否有值。或者做一個'Log.e(「JSON DATA」,json.toString);'並且看到它有一個數據。它將以你的DDMS角度出現。 –

+0

我該怎麼做?我不能添加log.e或在背景r8敬酒?請建議如何檢查json對象是否爲空 – bharath

回答

0

它看起來像你使用this JSONParser我想。看來正在發生的事情是,您的網址沒有生成有效的JSON,導致Exception被引發並在課程的某個地方被抓到 - 很可能在jObj = new JSONObject(json);一行中。最終結果是返回的變量仍然是null。因此,當您在循環中呼叫json.length()時,您試圖在null對象上調用length()。你應該在進入循環之前檢查它,以確保它不是null

+0

好吧,我評論了for循環,並檢查它的解析是否在第一位,然後得到這個錯誤,03-29 09:45:32.019:E/JSON解析器(942):解析數據時出錯org.json.JSONException :在字符0處輸入結束,同時還檢查了其他示例json腳本,腳本很好,解析器有問題嗎? – bharath

+0

它更可能是正在返回的數據的問題。您應該調試並查找來自URL的實際響應數據。 – jprofitt

+0

已經從昨天tryin沒有任何結果,是否有任何樣品我可以重用解析只是從網址使用異步工作的Android 3的元素。0以上?如果是這樣,請建議,想要把這個關掉! – bharath

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

,你還可以繼續在這個代碼解析爲好,希望這可以幫助你,

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

這會給整個內容作爲一個字符串嗎? – bharath

+0

是的..只是將該字符串傳遞給JSONOBJECT並解析爲你的需要 – Akilan