JSON parsing error - not parse in google API 4.1 jelly bean

匿名 (未验证) 提交于 2019-12-03 01:41:02

问题:

i am working on an app using json parsing...in this parsing is done by json of the given url.

As i run my project on emulator having target = "Google APIs (Google Inc.) - API level 10" then it runs properly and shows needed results from the target url.

but when run my project on emulator having target = "Google APIs (Google Inc.) - API level 16" then it shows error and it never parse the given url data and get force close.

i want to make app which run on every API level.

please help...

here's my code:

json parser class:

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.client.ClientProtocolException; 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 jObj = null;     static String json = "";     static String req = "POST";       // constructor     public JSONParser() {      }      public JSONArray getJSONFromUrl(String url, String method) {          // Making HTTP request         try {             // defaultHttpClient             DefaultHttpClient httpClient = new DefaultHttpClient();             HttpResponse httpResponse = null;             if(method == req) {               HttpPost httpC = new HttpPost(url);               httpResponse = httpClient.execute(httpC);             }else {               HttpGet httpC = new HttpGet(url);               httpResponse = httpClient.execute(httpC);             }             HttpEntity httpEntity = httpResponse.getEntity();             is = httpEntity.getContent();                     } catch (UnsupportedEncodingException e) {             e.printStackTrace();         } catch (ClientProtocolException e) {             e.printStackTrace();         } catch (IOException e) {             e.printStackTrace();         }          try {             BufferedReader reader = new BufferedReader(new InputStreamReader(                     is, "iso-8859-1"), 8);             StringBuilder sb = new StringBuilder();             String line = null;             while ((line = reader.readLine()) != null) {                 sb.append(line + "\n");             }             is.close();             json = sb.toString();         } catch (Exception e) {             Log.e("Buffer Error", "Error converting result " + e.toString());         }          // try parse the string to a JSON object         try {             jObj = new JSONArray(json);         } catch (JSONException e) {             Log.e("JSON Parser", "Error parsing data " + e.toString());         }          // return JSON String         return jObj;      } } 

Another class using json parser class snd fetch data:

import java.util.ArrayList; import java.util.HashMap;  import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject;  import android.app.ListActivity; import android.content.Intent; import android.os.Bundle; import android.util.Log; import android.widget.ListAdapter; import android.widget.SimpleAdapter;  public class showData extends ListActivity{      public static String url = "http://something/something/";      public static final String TAG_A = "a";     public static final String TAG_B = "b";     public static final String TAG_C = "c";     public static final String TAG_D = "d";     public static final String TAG_E = "e";     public static final String TAG_F = "f";     public static final String GET = "get";      JSONArray Data1 = null;      @Override     protected void onCreate(Bundle savedInstanceState) {         super.onCreate(savedInstanceState);           ArrayList<HashMap<String, String>> contactList = new ArrayList<HashMap<String, String>>();         EditText editext_text = (EditText) findViewById(R.id.et);         String urlnew = url + editext_text.getText().toString();          Log.d("url", urlnew);          JSONParser jParser = new JSONParser();          // getting JSON string from URL         area1 = jParser.getJSONFromUrl(urlnew, GET);               Log.d("Json String", area1.toString());              try {              for(int i = 0; i < area1.length(); i++){                  JSONObject c = area1.getJSONObject(i);                  // Storing each json item in variable                 String a = c.getString(TAG_A);                 String b = c.getString(TAG_B);                 String c = c.getString(TAG_C);                 String d = c.getString(TAG_D);                 String e = c.getString(TAG_E);  HashMap<String,String> map = new HashMap<String, String>();                  // adding each child node to HashMap key => value                 map.put(TAG_A, a);                 map.put(TAG_B, b);                 map.put(TAG_C, c);                 map.put(TAG_D, d);                 map.put(TAG_E, e);                  // adding HashList to ArrayList                 contactList.add(map);             }              } catch (JSONException e) {                 e.printStackTrace();             }             ListAdapter adapter = new SimpleAdapter(this, contactList,                     R.layout.list_item_area,                     new String[] { TAG_B, TAG_A, TAG_C, TAG_D, TAG_E }, new int[] {                             R.id.b, R.id.a, R.id.c, R.id.d, R.id.e });              setListAdapter(adapter);                      }       } 

回答1:

You are getting a NetworkOnMainThreadException because as the name is self-explaining, you are doing network request on UI Thread that will make your application laggy and create an horrible experience.

The exception that is thrown when an application attempts to perform a networking operation on its main thread.

This is only thrown for applications targeting the Honeycomb SDK or higher. Applications targeting earlier SDK versions are allowed to do networking on their main event loop threads, but it's heavily discouraged. See the document Designing for Responsiveness.

You should use Threads or AsyncTask, do you need some explanations on how to use them?

 private class NetworkTask extends AsyncTask<String, Void, String> {        @Override       protected String doInBackground(String... params) {             //DO YOUR STUFF       }              @Override       protected void onPostExecute(String result) {             //Update UI       }        @Override       protected void onPreExecute() {       }        @Override       protected void onProgressUpdate(Void... values) {       } }    


回答2:

This is Network On Main Thread Exception, You have to use Thread for network connection, because the main thread is UI thread will not give any response for Network connection. Use separate thread for network connection



易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!