0

我是编程新手,我正在制作一个 json 解析器,但是我的线程方法无法访问,我该如何去做。当我调试时,它进入了我的 getjson 方法,但随后跳过了 run 方法。我已经在 stack over flow 上进行了搜索,但是我对线程非常困惑,有什么好的方法可以做到这一点吗?

public class jsonParser {
 static InputStream is = null;
    static JSONObject jObj = null;
    static String json = "";
    // constructor
    public jsonParser() {

    }

    public JSONObject getJSONFromUrl(final String url) {

         Thread t = new Thread() {

public  void run() {
Looper.prepare(); //For Preparing Message Pool for the child Thread
       // Making HTTP request
        try {
            // defaultHttpClient
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(url);

            HttpResponse httpResponse = httpClient.execute(httpPost);
            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 JSONObject(json);
            } catch (JSONException e) {
                // TODO Auto-generated catch block
Log.e("JSON Parser", "Error parsing data " + e.toString());     
                 }
            Looper.loop(); 
       return;     
      }
}; t.start();
return jObj;      
         }
                }
4

1 回答 1

0

它进入run()方法。但是线程的原理是与当前线程并行执行。所以这是时间线上发生的事情:

main thread
_______________________________________________________________________
    |                    |
    start parser thread  return jObj

parser thread
      _________________________________________________________________
       |                                                       |
       execute an HTTP request and parse json                  assign JSON object to jObj

当您jObj从当前线程返回时,您刚刚启动了解析器线程。也许它甚至还没有开始执行。也许它仍在等待 HTTP 响应。可以肯定的是,它完成执行并将结果存储在静态 jObj 变量中的可能性为 0%。因此,从当前线程返回的值为 null。

很难告诉你应该做什么,除了阅读更多关于线程和 android 提供的支持类的信息。

于 2013-07-18T14:05:20.130 回答