JSON解析错误 - 不是在谷歌API 4.1果冻豆解析 [英] JSON parsing error - not parse in google API 4.1 jelly bean

查看:233
本文介绍了JSON解析错误 - 不是在谷歌API 4.1果冻豆解析的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在一个应用程序中使用JSON解析工作......在这种分析是由给定的URL JSON完成。

正如我在模拟器上运行我的项目有目标=谷歌的API(谷歌公司) - API级别10
那么它正常运行并显示结果需要从目标网址。

但是当有目标仿真器上运行我的项目=谷歌的API(谷歌公司) - API级别16
那么它会显示错误,它从不解析给定的URL数据,并得到强制关闭。

我想让它在每个API级别上运行应用程序。

请帮忙...

这是我的code:

JSON解析器类:

 进口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.client.ClientProtocolException;
进口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 jObj = NULL;
    静态JSON字符串=;
    静态字符串REQ =POST;
    //构造
    公共JSONParser(){    }    公共JSONArray getJSONFromUrl(URL字符串,字符串的方法){        //使HTTP请求
        尝试{
            // defaultHttpClient
            DefaultHttpClient的HttpClient =新DefaultHttpClient();
            HTT presponse HTT presponse = NULL;
            如果(方法== REQ){
              HttpPost httpC =新HttpPost(URL);
              HTT presponse = httpClient.execute(httpC);
            }其他{
              HTTPGET httpC =新HTTPGET(URL);
              HTT presponse = httpClient.execute(httpC);
            }
            HttpEntity httpEntity = HTT presponse.getEntity();
            是= httpEntity.getContent();        }赶上(UnsupportedEncodingException五){
            e.printStackTrace();
        }赶上(ClientProtocolException E){
            e.printStackTrace();
        }赶上(IOException异常五){
            e.printStackTrace();
        }        尝试{
            读者的BufferedReader =新的BufferedReader(新的InputStreamReader(
                    是,ISO-8859-1),8);
            StringBuilder的SB =新的StringBuilder();
            串线= NULL;
            而((行= reader.readLine())!= NULL){
                sb.append(行+\\ n);
            }
            is.close();
            JSON = sb.toString();
        }赶上(例外五){
            Log.e(缓冲区错误,错误转换结果+ e.toString());
        }        //尝试分析字符串到一个JSON对象
        尝试{
            jObj =新JSONArray(JSON);
        }赶上(JSONException E){
            Log.e(JSON解析器,错误分析数据+ e.toString());
        }        //返回JSON字符串
        返回jObj;    }
}

使用JSON解析器类SND获取数据另一类:

 进口的java.util.ArrayList;
进口的java.util.HashMap;进口org.json.JSONArray;
进口org.json.JSONException;
进口org.json.JSONObject;进口android.app.ListActivity;
进口android.content.Intent;
进口android.os.Bundle;
进口android.util.Log;
进口android.widget.ListAdapter;
进口android.widget.SimpleAdapter;公共类showData扩展ListActivity {    公共静态字符串URL =HTTP://事情/东西/;    公共静态最后弦乐TAG_A =A;
    公共静态最后弦乐TAG_B =B;
    公共静态最后弦乐TAG_C =C;
    公共静态最后弦乐TAG_D =D;
    公共静态最后弦乐TAG_E =E;
    公共静态最后弦乐TAG_F =F;
    公共静态最后弦乐GET =GET;    JSONArray数据1 = NULL;    @覆盖
    保护无效的onCreate(捆绑savedInstanceState){
        super.onCreate(savedInstanceState);
        ArrayList的<&HashMap的LT;字符串,字符串>> contactList =新的ArrayList<&HashMap的LT;字符串,字符串>>();
        的EditText editext_text =(EditText上)findViewById(R.id.et);
        。字符串urlnew = URL + editext_text.getText()的toString();        Log.d(URL,urlnew);        JSONParser jParser =新JSONParser();        // URL从获取JSON字符串
        区1 = jParser.getJSONFromUrl(urlnew,GET);
            Log.d(JSON字符串,area1.toString());            尝试{            的for(int i = 0; I< area1.length();我++){                JSONObject的C = area1.getJSONObject(I)                //存储在变量中的每个JSON项目
                字符串= c.getString(TAG_A);
                字符串B = c.getString(TAG_B);
                字符串C = c.getString(TAG_C);
                STRING D = c.getString(TAG_D);
                串E = c.getString(TAG_E);HashMap的<字符串,字符串>地图=新的HashMap<字符串,字符串>();                //将每个子节点的HashMap键=>值
                map.put(TAG_A,一);
                map.put(TAG_B,B);
                map.put(TAG_C,C);
                map.put(TAG_D,D);
                map.put(TAG_E,E);                //添加HashList到ArrayList的
                contactList.add(地图);
            }            }赶上(JSONException E){
                e.printStackTrace();
            }
            ListAdapter适配器=新SimpleAdapter(这一点,contactList,
                    R.layout.list_item_area,
                    新的String [] {TAG_B,TAG_A,TAG_C,TAG_D,TAG_E},新的INT [] {
                            R.id.b,R.id.a,R.id.c,R.id.d,R.id.e});            setListAdapter(适配器);        }
    }


解决方案

您已经看到了的 NetworkOnMainThreadException 因为作为名字是自我解释,你正在做的UI线程的网络请求,这将使您的应用程序laggy,并创建一个可怕的经历。


  

这是当应用程序试图执行引发的异常
  其主线程联网运行。


  
  

这是只抛出瞄准蜂窝SDK的应用程序或
  更高。针对应用较早的SDK版本都可以做
  网络对他们的主事件循环线程,但它的高度
  灰心。查看文档的设计响应。


您应该使用线程或AsyncTask的,你需要一些解释如何使用它们?

 私有类NetworkTask扩展的AsyncTask<弦乐,太虚,字符串> {      @覆盖
      保护字符串doInBackground(字符串... PARAMS){
            //做你STU​​FF
      }      @覆盖
      保护无效onPostExecute(字符串结果){
            //更新UI
      }      @覆盖
      在preExecute保护无效(){
      }      @覆盖
      保护无效onProgressUpdate(虚空......值){
      }
}

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

        }


    }

解决方案

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) {
      }
}   

这篇关于JSON解析错误 - 不是在谷歌API 4.1果冻豆解析的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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