凌空不发送正确的数据。如何实现以onPostExecute)替代(? [英] Volley not sending correct data. How to implement an alternative to onPostExecute()?

查看:126
本文介绍了凌空不发送正确的数据。如何实现以onPostExecute)替代(?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用抽射得到一些JSON数据来填充RecyclerView列表。最初的JSON文件返回一些信息,如:

I'm using Volley to get some JSON data to populate a RecyclerView list. The initial JSON file returns some information like:


  • 标识

  • 服务器

  • 状态

如果我要求使用服务器URL /服务器/ ID的新JSON话,我可以了解服务器/项目显示在诸如查看一些额外的信息:

If I request a new JSON using "Server URL/server/id" then I can get some extra information about the server/item to display on the view like:


  • 地址

  • 键入

  • 味道

我要为每个项目在我RecyclerView列表中显示两组信息,如:

I want to display in my RecyclerView list both sets of info for each item, like:


  • 服务器

  • 状态

  • 地址

  • 键入

  • 味道

不过,我需要在每个服务器的ID使用辅助JSON文件,以获得额外的信息。

However I need the id of each server to get the extra info using a secondary JSON file.

要ilustrate我需要:

To ilustrate I need to get:


  1. server1的活性-1.1.1.1-TYPE1-flavor1

  2. 服务器2-停2.2.2.2-2型-flavor2

  3. 服务器3-暂停-3.3.3.3-3型-flavor3

但我发现:


  1. server1的活性-1.1.1.1-TYPE1-flavor1

  2. 服务器2-停1.1.1.1-TYPE1-flavor1

  3. 服务器3-暂停-1.1.1.1-TYPE1-flavor1

我把下面的code在地方得到每个项目要求额外的数据的额外的信息,当主JSON文件不过分析我得到完全相同的地址,型,味对于每一个项目:

I put the following code in place to get the extra info for each item to request the extra data when the main JSON file is parsed however I get the exact same "address", "type", "flavor" for every single item:

解析类:

public class NovaParser extends Activity{

    public static final String ID = "id";
    public static final String NAME = "name";
    public static final String STATUS = "status";
    public static final String FLAVOR = "flavor";
    public static final String NETID = "netid";
    public static final String ADDR = "addr";
    public static final String HOST = "host";

    public String authToken;
    public String novaURL;

    public SharedPreferences shPref;

    public ArrayList<HashMap<String, String>> flavorList;

    public static NovaParser parser = null;

    public static NovaParser shared(){
        if (parser  == null){
            parser  = new NovaParser();
        }
        return parser ;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    public void setFlavorList(ArrayList<HashMap<String, String>> flavorList) {
        this.flavorList = flavorList;
    }

    public ArrayList<HashMap<String, String>> getFlavorList(){
        return flavorList;
    }

    public static ArrayList<HashMap<String, String>> parseJSON(String novaJSON){
        ArrayList<HashMap<String, String>> jsonList = new ArrayList<HashMap<String, String>>();
        ArrayList<HashMap<String, String>> tempList = new ArrayList<HashMap<String, String>>();
        try {
            NovaInstances novaInstance = new NovaInstances();
            JSONObject nova = new JSONObject(novaJSON);
            JSONArray servers = nova.getJSONArray("servers");

            for (int i = 0; i < servers.length(); i++) {
                JSONObject objsrv = servers.getJSONObject(i);
                novaInstance.setName(objsrv.getString("name"));
                novaInstance.setId(objsrv.getString("id"));
                novaInstance.setStatus(objsrv.getString("OS-EXT-STS:vm_state"));
                novaInstance.setHost(objsrv.getString("OS-EXT-SRV-ATTR:host"));
                String id = novaInstance.getId();
                String instanceDetail = NovaJSON.shared().receiveDetail(id);
                if (instanceDetail != null) {
                    novaInstance.setFlavor(parseFlavor(instanceDetail));
                }
                String netDetail = NovaJSON.shared().receiveIP(id);
                if (netDetail != null) {
                    tempList = parseNet(netDetail);
                }
                for (int j = 0; j < tempList.size(); j++) {
                    novaInstance.setNetid(tempList.get(j).get(NETID));
                    novaInstance.setAddr(tempList.get(j).get(ADDR));
                }
                HashMap<String, String> map = new HashMap<String, String>();
                map.put(NAME, novaInstance.getName());
                map.put(ID, novaInstance.getId());
                map.put(STATUS, novaInstance.getStatus());
                map.put(FLAVOR, novaInstance.getFlavor());
                map.put(HOST, novaInstance.getHost());
                map.put(NETID, novaInstance.getNetid());
                map.put(ADDR, novaInstance.getAddr());
                jsonList.add(map);
            }
        } catch (JSONException e) {
            Log.d("ErrorInitJSON", e.toString());
            e.printStackTrace();
        }

        Collections.sort(jsonList, new Comparator<HashMap<String, String>>() {
        @Override
        public int compare(HashMap<String, String> lhs, HashMap<String, String> rhs) {
                return (lhs.get("name")).compareToIgnoreCase(rhs.get("name"));
            }
        });


        return jsonList;
    }

    public static String parseFlavor(String instanceDetail){
        ArrayList<HashMap<String, String>> flavorList = NovaParser.shared().getFlavorList();
        String temp = null;
        JSONObject novaDetail = null;
        try {
            novaDetail = new JSONObject(instanceDetail);
            JSONObject server = novaDetail.getJSONObject("server");
            JSONObject flavor = server.getJSONObject("flavor");
            if (flavorList !=null){
            temp = flavor.getString("id");
            for (Map<String,String> map : flavorList) {
                if (map.containsValue(temp)) {
                    temp = map.get(NAME);
                }
            }
            }
            /*JSONObject addresses = server.getJSONObject("addresses");
            Iterator<String> keys=addresses.keys();
            while(keys.hasNext())
            {
                String key=keys.next();
                String value=addresses.getString(key);
                novaInstance.setNet(value);
            }
            JSONObject security_groups = server.getJSONObject("security_groups");*/

        } catch (JSONException e) {
            e.printStackTrace();
        }

        return temp;
    }

    public static ArrayList<HashMap<String, String>> parseNet(String netDetail){
        ArrayList<HashMap<String, String>> netList = new ArrayList<HashMap<String, String>>();
        String netId = null, addr = null;
        JSONObject net = null;
        try {
            net = new JSONObject(netDetail);
            JSONObject addresses = net.getJSONObject("addresses");
            Iterator<String> keys=addresses.keys();
            while(keys.hasNext())
            {
                String key=keys.next();
                String value=addresses.getString(key);
                netId = key;

            JSONArray network = addresses.getJSONArray(key);
            for (int i = 0; i < network.length(); i++) {
                JSONObject objnet = network.getJSONObject(i);
                addr = objnet.getString("addr");
                HashMap<String, String> map = new HashMap<String, String>();
                map.put(NETID, netId);
                map.put(ADDR, addr);
                netList.add(map);
            }
            }


        } catch (JSONException e) {
            e.printStackTrace();
        }

        return netList;
    }

}

排球类来获得JSON数据:

Volley class to get JSON data:

public class NovaJSON extends Activity {

    String novaJSON;
    String nova;
    String auth;
    String novaJSONdetail;
    String novaJSONip;
    String id;
    RequestQueue queue = null;

    public static NovaJSON parser = null;

    public static NovaJSON shared(){
        if (parser  == null){
            parser  = new NovaJSON();
        }
        return parser ;
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getNovaJSON() {
        return novaJSON;
    }

    public void setNovaJSON(String novaJSON) {
        this.novaJSON = novaJSON;
    }

    public String getNova() {
        return nova;
    }

    public void setNova(String nova) {
        this.nova = nova;
    }

    public String getAuth() {
        return auth;
    }

    public void setAuth(String auth) {
        this.auth = auth;
    }

    public String getNovaJSONdetail() {
        return novaJSONdetail;
    }

    public void setNovaJSONdetail(String novaJSONdetail) {
        this.novaJSONdetail = novaJSONdetail;
    }

    public String getNovaJSONip() {
        return novaJSONip;
    }

    public void setNovaJSONip(String novaJSONip) {
        this.novaJSONip = novaJSONip;
    }

    public String receiveData (String novaURL, String authToken){
        setNova(novaURL);
        setAuth(authToken);
        getJSON();
        getNovaJSON();
        return novaJSON;
    }

    public String receiveDetail (String id){
        setId(id);
        getJSONdetail();
        getNovaJSONdetail();
        return novaJSONdetail;
    }

    public String receiveIP (String id){
        setId(id);
        getJSONip();
        getNovaJSONip();
        return novaJSONip;
    }

    public void getJSON() {
        final String authToken = getAuth();
        String novaURL = getNova();
        novaURL = novaURL+"/servers/detail";


        JsonObjectRequest getRequest = new JsonObjectRequest(Request.Method.GET, novaURL, null,
                new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {
                        Log.d("Nova on Response", response.toString());
                        setNovaJSON(response.toString());
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        VolleyLog.d("Nova on Error", "Error: " + error.getMessage());
                        setNovaJSON(error.toString());
                    }
                }
        ) {
            public Map<String, String> getHeaders() throws AuthFailureError {
                Map<String, String> params = new HashMap<String, String>();
                params.put("X-Auth-Token", authToken);
                params.put("User-Agent", "stackerz");
                params.put("Accept", "application/json");
                params.put("Content-Type", "application/json; charset=utf-8");
                return params;
            }

        };


        queue = VolleySingleton.getInstance(this).getRequestQueue();
        //VolleySingleton.getInstance(this).addToRequestQueue(getRequest);
        queue.add(getRequest);
    }

    public void getJSONdetail() {
        final String authToken = getAuth();
        String novaURL = getNova();
        novaURL = novaURL+"/servers/"+id;


        JsonObjectRequest getRequest = new JsonObjectRequest(Request.Method.GET, novaURL, null,
                new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {
                        Log.d("Nova on Response", response.toString());
                        setNovaJSONdetail(response.toString());
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        VolleyLog.d("Nova on Error", "Error: " + error.getMessage());
                        setNovaJSONdetail(error.toString());
                    }
                }
        ) {
            public Map<String, String> getHeaders() throws AuthFailureError {
                Map<String, String> params = new HashMap<String, String>();
                params.put("X-Auth-Token", authToken);
                params.put("User-Agent", "stackerz");
                params.put("Accept", "application/json");
                params.put("Content-Type", "application/json; charset=utf-8");
                return params;
            }

        };


        queue = VolleySingleton.getInstance(this).getRequestQueue();
        //VolleySingleton.getInstance(this).addToRequestQueue(getRequest);
        queue.add(getRequest);
    }

    public void getJSONip() {
        final String authToken = getAuth();
        String novaURL = getNova();
        novaURL = novaURL+"/servers/"+id+"/ips";


        JsonObjectRequest getRequest = new JsonObjectRequest(Request.Method.GET, novaURL, null,
                new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {
                        Log.d("Nova on Response", response.toString());
                        setNovaJSONip(response.toString());
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        VolleyLog.d("Nova on Error", "Error: " + error.getMessage());
                        setNovaJSONip(error.toString());
                    }
                }
        ) {
            public Map<String, String> getHeaders() throws AuthFailureError {
                Map<String, String> params = new HashMap<String, String>();
                params.put("X-Auth-Token", authToken);
                params.put("User-Agent", "stackerz");
                params.put("Accept", "application/json");
                params.put("Content-Type", "application/json; charset=utf-8");
                return params;
            }

        };


        queue = VolleySingleton.getInstance(this).getRequestQueue();
        //VolleySingleton.getInstance(this).addToRequestQueue(getRequest);
        queue.add(getRequest);
    }
}

一些调试,我发现后,排球是在下面的方法太慢:

After some debugging I found out Volley is too slow on the following methods:

public String receiveDetail (String id){
    setId(id);
    getJSONdetail();
    getNovaJSONdetail();
    return novaJSONdetail;
}

public String receiveIP (String id){
    setId(id);
    getJSONip();
    getNovaJSONip();
    return novaJSONip;
}

getJSONxxx()工作正常,并设置novaJSONxxx弦细为每个单项JSON数据然而吸气getNovaxxx()始终返回第一个项的值。这似乎吸气剂是凌空太快。有了AsyncTask的有可能运行onPostExecute()当数据准备凌空但是没有此选项。

getJSONxxx() works fine and sets the novaJSONxxx string fine with the JSON data for each single item however the getter getNovaxxx() always returns the value for the very first item. It seems the getter is too fast for Volley. With AsyncTask it's possible to run onPostExecute() when the data is ready however Volley doesn't have this option.

有没有办法得到它的工作或者所以每个JSON数据返回到正确的项目实施方法吗?

Is there a way to get it working or implement an alternative so each JSON data is returned to the correct item?

推荐答案

我解决了完全倾倒排球和运动改装我的问题。我安装所有的调用能够同步/阻塞,摸索出使用try /渔获物和设置OkHTTP客户端上的短超时异常/错误。现在,它的工作,因为我想要的。

I solved my problem by dumping Volley altogether and moving to Retrofit. I setup all the calls to be sync/blocking, worked out the exceptions/errors using try/catches and setup a short timeout on the OkHTTP client. Now it's working as I wanted.

这篇关于凌空不发送正确的数据。如何实现以onPostExecute)替代(?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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