0

I'm very new to develop android apps, I'm struggling with my code, I'm getting the following error, and I can't understand why it is happening, I'm trying to use volley to connect to an API, but before that the user has to login first an then see the content.

07-01 17:21:16.143  22971-23604/com.rep E/YOUR_APP_LOG_TAG﹕ I got an error
    java.lang.NullPointerException
            at com.rep.webservice.volley.toolbox.Volley.newRequestQueue(Volley.java:45)
            at com.rep.webservice.rest.ClientesRest.getClientes(ClientesRest.java:52)
            at com.rep.webservice.Sincronizar.start(Sincronizar.java:26)
            at com.rep.app.login.LoginActivity$SincronizarTask.doInBackground(LoginActivity.java:311)
            at com.rep.app.login.LoginActivity$SincronizarTask.doInBackground(LoginActivity.java:280)
            at android.os.AsyncTask$2.call(AsyncTask.java:288)
            at java.util.concurrent.FutureTask.run(FutureTask.java:237)
            at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
            at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
            at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
            at java.lang.Thread.run(Thread.java:841)

What I'm doing is, first I get the API data:

mSincronizarTask = new SincronizarTask(getApplicationContext());
            mSincronizarTask.execute((Void) null);

Then I create an Asynctask:

public class SincronizarTask extends AsyncTask<Void, Void, Boolean> {

        private Context ctx;
        private ProgressDialog mProgressDialog;
        private Sincronizar mSincronizar = new Sincronizar(this.ctx);

        public SincronizarTask(Context activity) {
            Log.i("RM", "construct");
            ctx = activity;

        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            Log.i("RM", "onPreExecute");
        }

        @Override
        protected Boolean doInBackground(Void... params) {

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

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

//            this.mProgressDialog.dismiss();
            return true;

        }

        @Override
        protected void onPostExecute(final Boolean success) {
            Log.i("RM", "TOTAL: " + String.valueOf(mSincronizar.total()));
        }

        @Override
        protected void onCancelled() {
            Log.i("RM", "onCancelled");
            mAutenticacaoLocalTask = null;
//            this.mProgressDialog.dismiss();
        }

    }    

And this is the Sync class:

public class Sincronizar {

    private Context context;
    private List Clientes;

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

    public void start() {

        try {
            /* cria o objeto ClienteReste */
            ClientesRest mClientesRest = new ClientesRest(this.context);

            /* dispara a consulta pelo recurso "clientes" da API */
            this.Clientes = mClientesRest.getClientes();
        } catch (Exception e) {
            Log.i("RM", String.valueOf(e.getStackTrace()));
        }

    }

    public Integer total() {
        return 100;
    }

}

And finally the Clientrest class:

 public class ClientesRest extends Servidor {

    private String recursoRest = "clientes";

    private List arrayClientes;

    private RequestQueue mRequestQueue ;

    private Context context;

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

    public final List getClientes() {

        String url = this.URL_WS + recursoRest;

        Log.i("RM", "URL DE CONSULTA: " + url);


        try {



            mRequestQueue = Volley.newRequestQueue(this.context);

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


                @Override
                public void onResponse(JSONObject response) {
                    parseJSON(response);

                    Log.i("RM", "resposta da api: " + response.toString());


                }

            }, 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("TOKEN", "99KI9Gj68CgCf70deM22Ka64chef2C40Gm2lFJ0bDAcbFfd19MfacGf3FFm8CM1hG0eDiIk8");
                    return headers;
                }
            };

            mRequestQueue.add(mJsonObjectRequest);





        } catch (Exception e) {
            Log.e("YOUR_APP_LOG_TAG", "I got an error", e);
        }

        return this.arrayClientes;

    }

    private void parseJSON(JSONObject json) {
        try {

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

            /* array para armazenar os clientes */
            this.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" */
                this.arrayClientes.add(mClienteModel);
            }

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


    }
}

And this is the ClientsModel:

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 + '\'' +
                '}';
    }
}
AND4011002849
  • 1,971
  • 8
  • 38
  • 81
  • Can you post more of your stack trace, in particular, the portion where it starts to complain about the line of your code where the problem takes place. Then tell us which line of your code contains the error. – MarsAtomic Jul 01 '14 at 20:32
  • Good read: http://stackoverflow.com/questions/218384/what-is-a-null-pointer-exception-and-how-do-i-fix-it/24100776#24100776 – assylias Jul 01 '14 at 20:33
  • mRequestQueue = Volley.newRequestQueue(this.context); the error starts here – AND4011002849 Jul 01 '14 at 20:47

3 Answers3

1

I think that the null pointer exception is been thrown because in the constructor you're not passing the context correctly, this is an assumption because you didn't published the ClientesRest(Context ctx) call.

My advice is that you call the constructor from your main activity like this:

ClientesRest clientesRest = new ClientesRest(getApplicationContext());
Typo
  • 1,875
  • 1
  • 19
  • 32
  • I've edited the question, as you can see I'm calling the constructor as you say, "mSincronizarTask = new SincronizarTask(getApplicationContext());" but still getting the null pointer error – AND4011002849 Jul 02 '14 at 14:39
1

You declare

private Sincronizar mSincronizar = new Sincronizar(this.ctx);

but at this point, ctx is null. It is only initialized in the constructor

ctx = activity;

You need to delay the initialization of mSincronizar until after ctx is not null, in the constructor:

    public SincronizarTask(Context activity) {
        ctx = activity;
        mSincronizar = new Sincronizar(this.ctx);
    }
njzk2
  • 38,969
  • 7
  • 69
  • 107
0

Have you added this line in your manifest file?

  android:name=".helper.AppController"

Here is an example.

   <application
    android:name=".helper.AppController"
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:largeHeap="true"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
    ...
    ...
    />
Theo
  • 3,099
  • 12
  • 53
  • 94