68310

Unable to add window Android dialog box

Question:

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

Answer1:

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

replace it with

private Sincronizar mSincronizar;

Recommend

  • Application Crashes on orientation change while showing Progress Bar in AsyncTask
  • Mobile Number verification for dual SIM devices in Android
  • Routing to a different channels based on condition
  • 200kb image to base64 cannot send to web service
  • Other thread wont let me change Activity layout!? Android
  • How to return data in Android LocationListener
  • how to get json data from framework (Yii)
  • Expand in the same as
  • query to get last message only from all users
  • Is it possible to reference object within the same object?
  • IOError 22 in python Invalid on windows
  • Wordpress Geocoding using direction or a map
  • 8086 Assembly - DIV going ape, IP jumping to a weird location endlessly
  • Localization using resources file not working
  • Styling tabBar-indicator with ActionBarSherlock
  • Generating prime numbers between m and n [duplicate]
  • Extract java script from html document using regular expression
  • Chart js - Draw center of each bubbles of a bubble chart
  • Google script gmail addon update TextInput value,on change function
  • Macros: knownDirectSubclasses broken with nested type?
  • Facebook API: cannot login on Android
  • Store additional information during registration with Firebase in Android
  • Delphi: Where is the shortcut that started the application? [duplicate]
  • Bad interaction between Zope2 XML-RPC and AT Image mutator?
  • Elasticsearch script query involving root and nested values
  • Why use database factory in asp.net mvc?
  • close() was never explicitly called on database
  • How do I configure context broker accept post requests from my remote sensor?
  • presentShareDialogWithParams posts to FB wall, but callback handler results say error
  • Chart.js Multiple dataset
  • How to render a blob on a canvas element?
  • how to adjust image in a panel in Java swing?
  • Possible to stop flickering java tooltip in heavyweight mode?
  • Javascript Callbacks with Object constructor
  • Javascript + PHP Encryption with pidCrypt
  • JTable with a ScrollPane misbehaving
  • Getting Messege Twice Using IMvxMessenger
  • EntityFramework adding new object to nested object collection
  • How can i traverse a binary tree from right to left in java?
  • How can I use threading to 'tick' a timer to be accessed by other threads?