简体   繁体   English

如何在Android中打印arraylist

[英]How to print an arraylist in Android

I'm trying to print an array of objects in my app, but it is returning empty. 我正在尝试在应用程序中打印对象数组,但返回的是空的。 This is the log that I'm getting: 这是我得到的日志:

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

I'm using volley to get the data from an API, and I need to print that data using an object array. 我正在使用volley从API获取数据,并且需要使用对象数组打印该数据。 I need to see in the log the objects that's inside the array, what I don't know is how can I print the objects. 我需要在日志中查看数组内部的对象,但我不知道该如何打印对象。 Why it is returning null? 为什么返回null?

This is the Sync Class: 这是同步类:

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

}

This is the ClientRest: 这是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;

}
}

This is the ClientModel: 这是ClientModel:

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 + '\'' +
                '}';
    }
}

You could write it like that: 您可以这样写:

Define an interface for receiving the values: 定义用于接收值的接口:

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

Then, use the interface in the getClientes method: 然后,使用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);
}

Modify parseJSON so it returns a List<ClienteModel> , add return arrayClientes; 修改parseJSON使其返回List<ClienteModel> ,添加return arrayClientes; at the end, for example. 例如,最后。 (You should also make arrayClientes a local variable in the scope of the method, to limit the dependencies between elements) (您还应该在方法范围内使arrayClientes成为局部变量,以限制元素之间的依赖关系)

Finally, call getClientes : 最后,调用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));
    }
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM