【问题标题】:How to print an arraylist in Android如何在 Android 中打印数组列表
【发布时间】:2014-07-02 18:29:09
【问题描述】:

我正在尝试在我的应用程序中打印一组对象,但它返回的是空的。这是我得到的日志:

07-02 15:02:44.179  16933-17469/com.representemais I/RM﹕ []

我正在使用 volley 从 API 获取数据,我需要使用对象数组打印该数据。 我需要在日志中查看数组内的对象,我不知道如何打印这些对象。为什么它返回null?

这是同步类:

public class Sincronizar {

    private Context context;

    public Sincronizar(Context ctx) {
        this.context = ctx;
    }

   public void start() {

    try {

        ClientesRest mClientesRest = new ClientesRest(this.context);

        Log.i("RM", "P1");

        mClientesRest.getClientes(new ClientesRest.ClientesRestListener() {
            public void clientesReceived(List<ClienteModel> clientes) {
                // Here modify to do whatever you need to do with clientes
                Log.i("RM", "P:2");
                Log.i("RM", String.valueOf(clientes));
                Log.i("RM", "P:3");
            }
        });

    } catch (Exception e) {
        Log.i("RM", String.valueOf(e.getStackTrace()));
    }

}


    public Integer total() {
        return 100;
    }

}

这是 ClientRest:

public class ClientesRest extends Servidor {

    private String recursoRest = "clientes";

    List<ClienteModel> arrayClientes = new ArrayList<ClienteModel>();

    private RequestQueue mRequestQueue ;



private Context context;
public ClientesRest(Context ctx) {
    this.context = ctx;
}

public interface ClientesRestListener {
    public void clientesReceived(List<ClienteModel> clientes);
}

public final void getClientes(final ClientesRestListener listener) {

    String url = this.URL_WS + recursoRest;
    mRequestQueue = Volley.newRequestQueue(this.context);

    JsonObjectRequest mJsonObjectRequest = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {

        @Override
        public void onResponse(JSONObject response) {
            List<ClienteModel> clientes = null;
            try {
                clientes = parseJSON(response);
            } catch (JSONException e) {
                Log.i("RM", String.valueOf(e.getStackTrace()));
            }
            listener.clientesReceived(clientes);
        }

    }, new Response.ErrorListener() {

        @Override
        public void onErrorResponse(VolleyError error) {
            Log.i("RM", error.getMessage());
        }

    }
    ) {
        @Override
        public Map<String, String> getHeaders() throws AuthFailureError {
            HashMap<String, String> headers = new HashMap<String, String>();
            headers.put("X-API-TOKEN", "99KI9Gj68CgCf70deM22Ka64chef2C40Gm2lFJ2J0G9JkD0bDAcbFfd19MfacGf3FFm8CM1hG0eDiIk8");
            return headers;
        }
    };

    mRequestQueue.add(mJsonObjectRequest);
}

private List<ClienteModel> parseJSON(JSONObject json) throws JSONException {

    Log.i("RM", "executou o parseJSON");

        /* array para armazenar os clientes */
    ArrayList<ClienteModel> arrayClientes = new ArrayList<ClienteModel>();

        /* pega o array "dados" que vem na resposta da consulta ao rest */
    JSONArray dados = json.getJSONArray("dados");

        /* percorre o array */
    for (int i = 0; i < dados.length(); i++) {

            /* pega a posição de cada linha no array */
        JSONObject item = dados.getJSONObject(i);

            /* cria um objeto do tipo ClienteModel */
        ClienteModel mClienteModel = new ClienteModel();

            /* cadastra os dados necessários no objeto mClienteModel */
        mClienteModel.set_idrm(Integer.parseInt(item.optString("id")));
        mClienteModel.set_nome(item.optString("nome"));
        mClienteModel.set_tipo(item.getString("tipo"));
        mClienteModel.set_endereco(item.optString("endereco"));
        mClienteModel.set_numero(item.optString("numero"));
        mClienteModel.set_complemento(item.optString("complemento"));
        mClienteModel.set_cep(item.optString("cep"));
        mClienteModel.set_bairro(item.optString("bairro"));
        mClienteModel.set_cidade(item.optString("cidade"));
        mClienteModel.set_estado(item.optString("estado"));
        mClienteModel.set_informacao_adicional("informacao_adicional");

        /* adicionar o objeto mClienteModel no array de Clientes "arrayClientes" */
        arrayClientes.add(mClienteModel);
    }

    return arrayClientes;

}
}

这是客户端模型:

public class ClienteModel {

    private int _id;
    private int _idrm;
    private String _nome;
    private String _tipo;
    private String _endereco;
    private String _numero;
    private String _complemento;
    private String _cep;
    private String _bairro;
    private String _cidade;
    private String _estado;
    private String _informacao_adicional;

    public ClienteModel() {}

    public ClienteModel(String _nome, String _tipo, String _endereco, String _numero, String _complemento, String _cep, String _bairro, String _cidade, String _estado, String _informacao_adicional) {
        this._nome = _nome;
        this._tipo = _tipo;
        this._endereco = _endereco;
        this._numero = _numero;
        this._complemento = _complemento;
        this._cep = _cep;
        this._bairro = _bairro;
        this._cidade = _cidade;
        this._estado = _estado;
        this._informacao_adicional = _informacao_adicional;
    }

    public ClienteModel(int _idrm, String _nome, String _tipo, String _endereco, String _numero, String _complemento, String _cep, String _bairro, String _cidade, String _estado, String _informacao_adicional) {
        this._idrm = _idrm;
        this._nome = _nome;
        this._tipo = _tipo;
        this._endereco = _endereco;
        this._numero = _numero;
        this._complemento = _complemento;
        this._cep = _cep;
        this._bairro = _bairro;
        this._cidade = _cidade;
        this._estado = _estado;
        this._informacao_adicional = _informacao_adicional;
    }

    public ClienteModel(int _id, int _idrm, String _nome, String _tipo, String _endereco, String _numero, String _complemento, String _cep, String _bairro, String _cidade, String _estado, String _informacao_adicional) {
        this._id = _id;
        this._idrm = _idrm;
        this._nome = _nome;
        this._tipo = _tipo;
        this._endereco = _endereco;
        this._numero = _numero;
        this._complemento = _complemento;
        this._cep = _cep;
        this._bairro = _bairro;
        this._cidade = _cidade;
        this._estado = _estado;
        this._informacao_adicional = _informacao_adicional;
    }

    public int get_id() {
        return _id;
    }

    public void set_id(int _id) {
        this._id = _id;
    }

    public int get_idrm() {
        return _idrm;
    }

    public void set_idrm(int _idrm) {
        this._idrm = _idrm;
    }

    public String get_nome() {
        return _nome;
    }

    public void set_nome(String _nome) {
        this._nome = _nome;
    }

    public String get_tipo() {
        return _tipo;
    }

    public void set_tipo(String _tipo) {
        this._tipo = _tipo;
    }

    public String get_endereco() {
        return _endereco;
    }

    public void set_endereco(String _endereco) {
        this._endereco = _endereco;
    }

    public String get_numero() {
        return _numero;
    }

    public void set_numero(String _numero) {
        this._numero = _numero;
    }

    public String get_complemento() {
        return _complemento;
    }

    public void set_complemento(String _complemento) {
        this._complemento = _complemento;
    }

    public String get_cep() {
        return _cep;
    }

    public void set_cep(String _cep) {
        this._cep = _cep;
    }

    public String get_bairro() {
        return _bairro;
    }

    public void set_bairro(String _bairro) {
        this._bairro = _bairro;
    }

    public String get_cidade() {
        return _cidade;
    }

    public void set_cidade(String _cidade) {
        this._cidade = _cidade;
    }

    public String get_estado() {
        return _estado;
    }

    public void set_estado(String _estado) {
        this._estado = _estado;
    }

    public String get_informacao_adicional() {
        return _informacao_adicional;
    }

    public void set_informacao_adicional(String _informacao_adicional) {
        this._informacao_adicional = _informacao_adicional;
    }

    @Override
    public String toString() {
        return "ClienteModel{" +
                "_id=" + _id +
                ", _idrm=" + _idrm +
                ", _nome='" + _nome + '\'' +
                ", _tipo='" + _tipo + '\'' +
                ", _endereco='" + _endereco + '\'' +
                ", _numero='" + _numero + '\'' +
                ", _complemento='" + _complemento + '\'' +
                ", _cep='" + _cep + '\'' +
                ", _bairro='" + _bairro + '\'' +
                ", _cidade='" + _cidade + '\'' +
                ", _estado='" + _estado + '\'' +
                ", _informacao_adicional='" + _informacao_adicional + '\'' +
                '}';
    }
}

【问题讨论】:

  • Log.i("RM", String.valueOf(mClientesRest.getClientes())); 你忘了toString()了吗?
  • getClientes 无法返回任何内容,因为 mRequestQueue.add 是异步的。
  • 我需要在日志中查看数组中的对象,我不知道如何打印这些对象。为什么它返回 null?
  • OK @njzk2 我该如何解决这个问题?
  • 本质上,Volley 是异步的。这就是整个听众的事情。您还需要异步(除非您绝对想要同步,但这是很多工作却没有什么好处)。您要么需要向您的getClientes 添加一个侦听器系统,要么将您使用的 Volley 侦听器移到 ClientesRest 之外

标签: java android arrays android-volley


【解决方案1】:

你可以这样写:

定义一个接收值的接口:

public interface ClientesRestListener {
    public void clientesReceived(List<ClienteModel> clientes);
}

然后,使用getClientes方法中的接口:

public final void getClientes(final ClientesRestListener listener) {
    String url = this.URL_WS + recursoRest;
    mRequestQueue = Volley.newRequestQueue(this.context);
    JsonObjectRequest mJsonObjectRequest = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {

            @Override
            public void onResponse(JSONObject response) {
                List<ClienteModel> clientes = parseJSON(response);
                listener.clientesReceived(clientes);
            }
        }, /* Error listener here*/) {/* add headers here */};
    mRequestQueue.add(mJsonObjectRequest);
}

修改parseJSON,使其返回List&lt;ClienteModel&gt;,例如在末尾添加return arrayClientes;。 (还应该将arrayClientes设为方法范围内的局部变量,以限制元素之间的依赖关系)

最后,拨打getClientes

mClientesRest.getClientes(new ClientesRestListener() {
    public void clientesReceived(List<ClienteModel> clientes) {
        // Here modify to do whatever you need to do with clientes
        Log.i("RM", String.valueOf(clientes));
    }
});

【讨论】:

  • 我已经编辑了这个问题,我试着按照你说的做,但仍然得到一个空结果,我错过了什么吗?谢谢你的时间
  • 您的编辑似乎是正确的。从服务器接收的实际内容可能存在问题。您需要检查来自服务器的返回值(在onResponse),检查是否有任何异常。要从异常中获取最大信息,请使用e.printStackTrace();(其中e 是您的异常)。它将在日志中打印异常的堆栈跟踪,以便您查看发生了什么。
  • 在可能出错的事情中,Integer.parseInt(item.optString("id")):如果id 不在对象中,optString 将返回"",这将导致parseInt 中的IllegalArgumentException
  • 好的,它解决了我的问题,问题是“java.lang.String 无法转换为 JSONObject”,我把它解决了,谢谢你的帮助,如果可以看看我的其他问题 - stackoverflow.com/questions/24559923/… 代码差不多
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-03-05
  • 1970-01-01
  • 1970-01-01
  • 2018-01-12
  • 2015-09-24
相关资源
最近更新 更多