0

我正在开发一个使用 json 解析的应用程序......在这个解析是由给定 url 的 json 完成的。

当我在具有 target = "Google APIs (Google Inc.) - API level 10" 的模拟器上运行我的项目时,它会正常运行并显示来自目标 url 的所需结果。

但是当在模拟器上运行我的项目时,目标 = "Google APIs (Google Inc.) - API level 16" 然后它显示错误并且它从不解析给定的 url 数据并强制关闭。

我想制作在每个 API 级别上运行的应用程序。

请帮忙...

这是我的代码:

json解析器类:

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;

    }
}

另一个类使用 json 解析器类 snd 获取数据:

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

        }


    }
4

2 回答 2

1

您收到NetworkOnMainThreadException 异常,因为名称不言自明,您正在 UI 线程上执行网络请求,这将使您的应用程序滞后并产生可怕的体验。

当应用程序尝试在其主线程上执行网络操作时引发的异常。

这仅针对面向 Honeycomb SDK 或更高版本的应用程序抛出。允许以早期 SDK 版本为目标的应用程序在其主事件循环线程上进行网络连接,但非常不鼓励这样做。请参阅文档设计响应性。

你应该使用 Threads 或 AsyncTask,你需要一些关于如何使用它们的解释吗?

 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) {
      }
}   
于 2013-07-02T19:24:08.037 回答
0

这是 Network On Main Thread 异常,您必须使用 Thread 进行网络连接,因为主线程是 UI 线程,不会对网络连接做出任何响应。使用单独的线程进行网络连接

于 2013-09-03T07:22:43.650 回答