简体   繁体   中英

Unable to add window Android dialog box

First the user enter his username and password, then the app gets a list of data from an API.

I'm trying to show a dialog box while the the app is synchronizing the data from an API, but I'm getting the following error:

Log:

ERROR

07-03 14:12:29.791  24439-24439/com.rep E/AndroidRuntime﹕ FATAL EXCEPTION: main
    android.view.WindowManager$BadTokenException: Unable to add window -- token null is not for an application
            at android.view.ViewRootImpl.setView(ViewRootImpl.java:571)
            at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:246)
            at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:69)
            at android.app.Dialog.show(Dialog.java:281)
            at com.app.login.LoginActivity$SincronizarTask.(LoginActivity.java:292)
            at com.app.login.LoginActivity$AutenticacaoLocalTask.onPostExecute(LoginActivity.java:248)
            at com.app.login.LoginActivity$AutenticacaoLocalTask.onPostExecute(LoginActivity.java:163)
            at android.os.AsyncTask.finish(AsyncTask.java:631)
            at android.os.AsyncTask.access$600(AsyncTask.java:177)
            at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:644)
            at android.os.Handler.dispatchMessage(Handler.java:99)
            at android.os.Looper.loop(Looper.java:137)
            at android.app.ActivityThread.main(ActivityThread.java:5226)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:511)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:795)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:562)
            at dalvik.system.NativeStart.main(Native Method)

The Sync class:

 public class SincronizarTask extends AsyncTask {

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

        public SincronizarTask(Context activity) {

            ctx = activity;
            mSincronizar = new Sincronizar(ctx);

            dialog = new ProgressDialog(ctx);
            dialog.setCancelable(false);
            dialog.setTitle("Sincronizando");
            dialog.setMessage("Aguarde...");

            if (!dialog.isShowing()) {
                dialog.show();
            }

        }

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

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

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

            try {
                ClientesRest mClientesRest = new ClientesRest(this.ctx);

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

                mClientesRest.getClientes(new ClientesRest.ClientesRestListener() {
                    public void clientesReceived(List clientes) {
                        Log.i("RM", "doInBackground : P:2");
                        Log.i("RM", String.valueOf(clientes));
                        Log.i("RM", "doInBackground : P:3");
                    }
                });
            } catch (Exception e) {
                e.printStackTrace();
            }

            return true;

        }

        @Override
        protected void onPostExecute(final Boolean success) {
            dialog.dismiss();
        }

        @Override
        protected void onCancelled() {
            mAutenticacaoLocalTask = null;
            dialog.dismiss();
        }

    }

The ClientRest class:

import android.content.Context;
import android.util.Log;

import com.model.ClienteModel;
import com.webservice.Servidor;
import com.webservice.volley.AuthFailureError;
import com.webservice.volley.Request;
import com.webservice.volley.RequestQueue;
import com.webservice.volley.Response;
import com.webservice.volley.VolleyError;
import com.webservice.volley.toolbox.JsonObjectRequest;
import com.webservice.volley.toolbox.Volley;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static java.lang.String.valueOf;

public class ClientesRest extends Servidor {

    private String recursoRest = "clientes";

    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) {
                    e.printStackTrace();
                   // 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--TOKEN", "xxxxxxxxxxxxxxxxxxxxxxxx");
                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;

    }
}

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

replace it with

private Sincronizar mSincronizar;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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