簡體   English   中英

Android Parse JSON卡在獲取任務上

[英]Android Parse JSON stuck on get task

我正在嘗試解析一些JSON數據。 我的代碼工作了一段時間,我不確定為突然破壞代碼所做的更改。 運行代碼時,我沒有收到任何運行時錯誤或警告。 我創建一個新的AsyncTask並執行它。 當我在此新任務上調用.get()時,調試器將在此行停頓並花費30多分鍾。 我無法獲得調試器或在運行期間無法完成此任務。

JSON:

protected void setUp(Context context) {
    _context = context;
    getConfig();
}

// get config file
protected void getConfig() { 
    if (config != null)
        return;

    config = new Config();

    String url = configURL;
    AsyncTask<String, Integer, JSONObject> jsonTask = new DownloadJSONTask()
            .execute(url);
    JSONObject configItem = null;
    try {
        configItem = jsonTask.get(); //debugger pauses here
        if (configItem == null)
            return;
        config.configVersion = configItem.getString("field_configversion");
        config.currentAppVersion = configItem
                .getString("field_currentappversion");
        config.getSupportURL = configItem.getString("field_getsupporturl");
        config.getCatalogURL = configItem.getString("field_getcatalogurl");
        config.getDataVersion = configItem.getString("field_dataversion");
        config.getDataUrl = configItem.getString("field_dataurl");
        config.getDataApiKey = configItem.getString("field_dataapikey");
    } catch (InterruptedException e) {
        e.printStackTrace();
        System.err.println("Download of config interrupted");
    } catch (ExecutionException e) {
        e.printStackTrace();
        System.err.println("Download of config failed to execute");
    } catch (JSONException e) {
        e.printStackTrace();
    } 

    cacheStaticData(_context);
}

下載JSONTask.java

package com.example.simplegraph;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.os.AsyncTask;

public class DownloadJSONTask extends AsyncTask<String, Integer, JSONObject> {
private HttpClient client = new DefaultHttpClient();
private HttpGet request;
private HttpResponse response;

DownloadJSONTask() {
    super();
}

// tries to grab the data for a JSONObject
@Override
protected JSONObject doInBackground(String... urls) {

    request = new HttpGet(urls[0]);
    try {
        response = client.execute(request);
        HttpEntity entity = response.getEntity();
        if (entity != null) {
            InputStream instream = entity.getContent();
            String result = convertStreamToString(instream);
            JSONObject json = new JSONObject(result);
            instream.close();
            return json;
        }
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (JSONException e) {
        e.printStackTrace();
    }
    return null;
}

// converts the InputStream to a string and add nl
private String convertStreamToString(InputStream is) {
    BufferedReader br = new BufferedReader(new InputStreamReader(is));
    StringBuilder sb = new StringBuilder();
    String line = null;
    try {
        while ((line = br.readLine()) != null) {
            sb.append(line + "\n");
        }
    } catch (IOException ioe) {
        ioe.printStackTrace();
    } finally {
        try {
            is.close();
        } catch (IOException ioe) {
            ioe.printStackTrace();
        }
    }
    return sb.toString();
}
}

還有HomeActivity.java

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_home);

    new AddStringTask().execute();

}

class AddStringTask extends AsyncTask<Void, String, Void> {
    @Override
    protected Void doInBackground(Void... unused) {

        app = (EconApplication) getApplication();
        getApp().setUp(HomeActivity.this);
        HomeActivity.this.setUpDrawer();
        return (null);
    }

    @Override
    protected void onPostExecute(Void unused) {
        setUpDataDisplay();
        setUpGraphRange();
        createTable();
        createGraph(-1);
    }
}

問題:為什么我的代碼卡在.get()上?

您可以使用droidQuery庫大大簡化一切:

$.getJSON("http://www.example.com", null, new Function() {//this will run using an AsyncTask, get the JSON, and return either a JSONObject or JSONArray on the UI Thread.
    @Overrde
    public void invoke($ droidQuery, Object... params) {
        if (params[0] instanceof JSONObject) { //it's often ok just to assume a JSONObject, making your first line simply: JSONObject obj = (JSONObject) params[0];
            //JSONObject is returned
            JSONObject json = (JSONObject) params[0];
            //to easily parse this Object, convert it to a map first:
            Map<String, ?> map = $.map(json);
            //then you can just make a call like this:
            if (map.contains("field_currentappversion")) {
                config.currentAppVersion = (String) map.get("field_currentappversion");
            }
        }
        else {
            //JSONArray is returned
            JSONArray json = (JSONArray) params[0];
            //if you got an array, you can easily convert it to an Object[] for parsing:
            Object[] array = $.makeArray(json);
        }
    }
});

AsyncTask.get()阻止調用者線程。 請改用AsyncTask.execute()

public final Result get ()

在API級別3中添加

必要時等待計算完成,然后檢索其結果。

返回值計算結果。

從中繪圖

如何從AsyncTask返回布爾值?

試試下面

  new DownloadJSONTask(ActivityName.this).execute(url);

在您的DownloadJSONTask中

在建築中

    TheInterface listener;
    public DownloadJSONTask(Context context)
{

    listener = (TheInterface) context;

}

接口

   public interface TheInterface {

    public void theMethod(ArrayList<String> result); // your result type

     }

在您的doInbackground返回結果。 我假設它的ArrayList是String類型。 將arraylist更改為適合您的要求。

在你的onPostExecute

   if (listener != null) 
   {
      listener.theMethod(result); // result is the ArrayList<String>
      // result returned in doInbackground 
      // result of doInbackground computation is a parameter to onPostExecute 
   }

在活動類中實現接口

 public class ActivityName implements DownloadJSONTask.TheInterface

然后

 @Override
 public void theMethod(ArrayList<String> result) { // change the type of result according yo your requirement
 // use the arraylist here
 }

編輯:替代

您可以將asynctask設為活動類的內部類。 在結果doInbackground計算是一個參數onPostExecute doInbackground返回結果。 onPostExecute更新ui。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM