2013-03-29 1 views
0

De mon dernier message, se sont sais que je dois utiliser la tâche async pour JSON analyse syntaxique de l'URL, ont fait la même chose et ci-joint,Async d'analyseur android JSON Android- NullPointerException

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

} Lorsque j'exécute cela, j'obtiens une exception de pointeur nul pour l'erreur exécutée en arrière-plan asyc dans la ligne, pour (int i = 0; i < json.length(); i ++), essayé plusieurs choses mais ne fonctionne pas, tout l'aide sera gr8ly appréciée!

Edit 1: Code analyseur ajouté

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

avez-vous essayé le débogage et vérifié si les données sont analysées correctement? –

+0

Effectuez un débogage et vérifiez que 'JSONArray json' contient des valeurs. Ou faire un 'Log.e (" JSON DATA ", json.toString);' et voir qu'il a une donnée. Il apparaîtra dans votre perspective DDMS. –

+0

Comment puis-je faire ça ?? Je ne peux pas ajouter log.e ou toast en arrière-plan r8 ?? S'il vous plaît suggérer comment vérifier si l'objet json n'est pas nul – bharath

Répondre

0

On dirait que vous utilisez this JSONParser je pense. Ce qui semble se produire est que vous avez une URL qui ne produit pas de JSON valide, ce qui se traduit par un Exception jeté et pris dans la classe quelque part sur le chemin - probablement dans la ligne jObj = new JSONObject(json);. Le résultat final est que la variable renvoyée est toujours null. Ainsi, lorsque vous appelez json.length() dans votre boucle, vous essayez d'appeler length() sur un objet null. Vous devriez faire une vérification avant d'entrer dans la boucle pour vous assurer que ce n'est pas null.

+0

Ok, j'ai commenté la boucle for et vérifié si son analyse du tout en premier lieu, puis obtenu cette erreur, 03-29 09: 45: 32.019: E/JSON Parser (942): Erreur d'analyse des données org.json.JSONException : Fin de l'entrée au caractère 0, vérifié avec d'autres exemples de scripts json, les scripts sont bien, y a-t-il un problème avec l'analyseur ?? – bharath

+0

Il est plus probable que cela pose un problème avec les données renvoyées. Vous devez déboguer et trouver les données de réponse réelles à partir de l'URL. – jprofitt

+0

ont été tryin à partir d'hier sans aucun résultat, y at-il des échantillons que je peux réutiliser pour l'analyse juste un élément de l'URL en utilisant async pour travailler pour android 3.0 et ci-dessus ?? si oui, s'il vous plaît suggérer, voulez envelopper ceci! – bharath

0

Je pense que, vous ne recevez pas le format JSON valide du serveur. Avant d'analyser, vérifiez la réponse de votre serveur, voici un extrait de code, passez ici l'URL et obtenez votre chaîne de réponse checkReponseInJSONStr dans logcat si elle est au format JSON ou non, puis effectuez l'opération d'analyse.

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

vous pouvez aussi continuer l'analyse syntaxique dans ce code ainsi, espérons que cela vous aide,

0

Essayez ceci pour obtenir 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; 
} 

utilisation isNetworkAvailable pour la connexion de vérification

et i analysé de cette façon

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

Est-ce que cela donnera le contenu entier comme une chaîne? – bharath

+0

yep..juste passer cette chaîne à JSONOBJECT et analyser comme ur besoin – Akilan