Activity has Leaked window Android

4

I make a connection to MySQL and it returns me a JSON that I play in a list of products. When I click on any of these items it picks up the ID (called PID in the code) of the product and sends it to another Acitivity. In this other Activity the ID is retrieved, and made a new connection with MySQL to return the data for that product. The problem is that when you click on one of these products, at the time of going to another activity, the application simply displays the error "Unfortunately, (name of the app) has been stopped." The strange thing is that it happens sometimes only. Sometimes it usually opens the second Acitivity, sometimes it gives that error there.

(ps .: I used this article as a base: link )

Logcat:

        14166-14166/com.example.victorcatao.booktrade E/WindowManager﹕ android.view.WindowLeaked: Activity com.example.victorcatao.booktrade.DetalhesLivros has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView{1994769 V.E..... R......D 0,0-1026,348} that was originally added here
        at android.view.ViewRootImpl.<init>(ViewRootImpl.java:363)
        at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:261)
        at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:69)
        at android.app.Dialog.show(Dialog.java:298)
        at com.example.victorcatao.booktrade.DetalhesLivros$LoadAllProducts.onPreExecute(DetalhesLivros.java:97)
        at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:587)
        at android.os.AsyncTask.execute(AsyncTask.java:535)
        at com.example.victorcatao.booktrade.DetalhesLivros.onCreate(DetalhesLivros.java:65)
        at android.app.Activity.performCreate(Activity.java:5937)
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1105)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2251)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360)
        at android.app.ActivityThread.access$800(ActivityThread.java:144)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278)
        at android.os.Handler.dispatchMessage(Handler.java:102)
        at android.os.Looper.loop(Looper.java:135)
        at android.app.ActivityThread.main(ActivityThread.java:5221)
        at java.lang.reflect.Method.invoke(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:372)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)

AllProductsActivity.java (first Activity):

 public class AllProductsActivity extends ListActivity {

// Progress Dialog
private ProgressDialog pDialog;

// Creating JSON Parser object
JSONParser jParser = new JSONParser();

ArrayList<HashMap<String, String>> productsList;

// url to get all products list
private static String url_all_products = "http://localhost/android_connect/get_all_products.php";

// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_PRODUCTS = "products";
private static final String TAG_PID = "pid";
private static final String TAG_NAME = "name";
private static final String TAG_AUTOR = "autor";
private static final String TAG_PRECO = "preco";

// products JSONArray
JSONArray products = null;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.all_products);

    // Hashmap for ListView
    productsList = new ArrayList<HashMap<String, String>>();

    // Loading products in Background Thread
    new LoadAllProducts().execute();

    // Get listview
    ListView lv = getListView();

    // on seleting single product
    // launching Edit Product Screen
    lv.setOnItemClickListener(new OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> parent, View view,
                int position, long id) {
            // getting values from selected ListItem
            String pid = ((TextView) view.findViewById(R.id.pid)).getText()
                    .toString();

            // Starting new intent
            Intent in = new Intent(getApplicationContext(),
                    DetalhesLivros.class);
            // sending pid to next activity
            in.putExtra(TAG_PID, pid);
            startActivity(in);

        }
    });

}


/**
 * Background Async Task to Load all product by making HTTP Request
 * */
class LoadAllProducts extends AsyncTask<String, String, String> {

    /**
     * Before starting background thread Show Progress Dialog
     * */
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        pDialog = new ProgressDialog(AllProductsActivity.this);
        pDialog.setMessage("Carregando livros. Aguarde...");
        pDialog.setIndeterminate(false);
        pDialog.setCancelable(false);
        pDialog.show();
    }

    /**
     * getting All products from url
     * */
    protected String doInBackground(String... args) {
        // Building Parameters
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        // getting JSON string from URL - pega a resposta JSON do php
        JSONObject json = jParser.makeHttpRequest(url_all_products, "GET", params);

        // Check your log cat for JSON reponse
        Log.d("All Products: ", json.toString());

        try {
            // Checking for SUCCESS TAG
            int success = json.getInt(TAG_SUCCESS);

            if (success == 1) {
                // products found
                // Getting Array of Products
                products = json.getJSONArray(TAG_PRODUCTS);

                // looping through All Products
                for (int i = 0; i < products.length(); i++) {
                    JSONObject c = products.getJSONObject(i);

                    // Storing each json item in variable
                    String id = c.getString(TAG_PID);
                    String name = c.getString(TAG_NAME);
                    String autor = c.getString(TAG_AUTOR);
                    String preco = c.getString(TAG_PRECO);

                    // creating new HashMap
                    HashMap<String, String> map = new HashMap<String, String>();


                    //jogando os dados no textview
                    // adding each child node to HashMap key => value
                    map.put(TAG_PID, id);
                    map.put(TAG_NAME, name);
                    map.put(TAG_AUTOR, autor);
                    map.put(TAG_PRECO, "R$ "+preco);

                    // adding HashList to ArrayList
                    productsList.add(map);
                }
            } else {
                // no products found
                // Launch Add New product Activity
                Intent i = new Intent(getApplicationContext(),
                        NewProductActivity.class);
                // Closing all previous activities
                i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                startActivity(i);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

        return null;
    }

    /**
     * After completing background task Dismiss the progress dialog
     * **/
    protected void onPostExecute(String file_url) {
        // dismiss the dialog after getting all products
        pDialog.dismiss();
        // updating UI from Background Thread
        runOnUiThread(new Runnable() {
            public void run() {
                /**
                 * Updating parsed JSON data into ListView
                 *
                 * JOGANDO OS VALORES DENTRO DO LISTVIEW*/
                ListAdapter adapter = new SimpleAdapter(
                        AllProductsActivity.this, productsList,
                        R.layout.list_item, new String[] { TAG_PID,
                                TAG_NAME, TAG_AUTOR, TAG_PRECO},
                        new int[] { R.id.pid, R.id.name, R.id.autor, R.id.preco });
                // updating listview
                setListAdapter(adapter);
            }
        });

    }

}
}

Details.java (Second Activity):

public class DetalhesLivros extends ListActivity {

String pid;
TextView txtNome, txtNome2, txtAutor, txtPreco, txtDescricao, txtDDD, txtTelefone, txtEmailContato;
Button btnEnviarEmail;

// Progress Dialog
private ProgressDialog pDialog;

// Creating JSON Parser object
JSONParser jParser = new JSONParser();


// url to get all products list
private static String url_all_products = "http://localhost/android_connect/get_some_products.php?pid="; //variável pid entra aqui

// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_PRODUCTS = "products";
private static final String TAG_PID = "pid";
private static final String TAG_NAME = "name";
private static final String TAG_AUTOR = "autor";
private static final String TAG_PRECO= "price";
private static final String TAG_DESCRICAO = "descricao";
private static final String TAG_DDD = "ddd";
private static final String TAG_TELEFONE = "telefone";
private static final String TAG_TIPO = "tipo";
private static final String TAG_EMAILCONTATO = "emailcontato";

// products JSONArray
JSONArray products = null;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_detalhes_livros);

    //RECUPERANDO O ID DO PRODUTO (PID)
    Intent i = getIntent();
    pid = i.getStringExtra(TAG_PID);

    new LoadAllProducts().execute();

}


/**
 * Background Async Task to Load all product by making HTTP Request
 */
class LoadAllProducts extends AsyncTask<String, String, String> {

    /**
     * Before starting background thread Show Progress Dialog
     */
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        pDialog = new ProgressDialog(DetalhesLivros.this);
        pDialog.setMessage("Loading products. Please wait...");
        pDialog.setIndeterminate(false);
        pDialog.setCancelable(false);
        pDialog.show();
    }

    /**
     * getting All products from url
     */
    protected String doInBackground(String... args) {
        // Building Parameters
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        // getting JSON string from URL - pega a resposta JSON do php
        //Relacionando a url+numero do id, que será pego pelo PHP e blablabla
        JSONObject json = jParser.makeHttpRequest(url_all_products + pid, "GET", params);

        // Check your log cat for JSON reponse
        Log.d("All Products: ", json.toString());

        try {
            // Checking for SUCCESS TAG
            int success = json.getInt(TAG_SUCCESS);

            if (success == 1) {
                // products found
                // Getting Array of Products
                products = json.getJSONArray(TAG_PRODUCTS);

                // looping through All Products

                JSONObject c = products.getJSONObject(0);

                // Storing each json item in variable
                String id = c.getString(TAG_PID);
                String name = c.getString(TAG_NAME);
                String autor = c.getString(TAG_AUTOR);
                String preco = c.getString(TAG_PRECO);
                String descricao = c.getString(TAG_DESCRICAO);
                String ddd = c.getString(TAG_DDD);
                String telefone = c.getString(TAG_TELEFONE);
                String emailcontato = c.getString(TAG_EMAILCONTATO);


                //inserindo os textos nos campos
                txtNome = (TextView) findViewById(R.id.txtNome);
                txtNome2 = (TextView) findViewById(R.id.txtNome2);
                txtAutor = (TextView) findViewById(R.id.txtAutor);
                txtPreco = (TextView) findViewById(R.id.txtPreco);
                txtDescricao = (TextView) findViewById(R.id.txtDescricao);
                txtDDD = (TextView) findViewById(R.id.txtDDD);
                txtTelefone = (TextView) findViewById(R.id.txtTelefone);
                txtEmailContato = (TextView) findViewById(R.id.txtEmailContato);

                txtNome.setText(name);
                txtNome2.setText(name);
                txtAutor.setText("("+autor+")");
                txtPreco.setText("R$"+preco);
                txtDescricao.setText(descricao);
                txtDDD.setText(ddd);
                txtTelefone.setText(telefone);
                txtEmailContato.setText(emailcontato);


            } else {
                // no products found
                // Launch Add New product Activity
                Intent i = new Intent(getApplicationContext(),
                        MainActivity.class);
                // Closing all previous activities
                i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                startActivity(i);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

        return null;
    }

    /**
     * After completing background task Dismiss the progress dialog
     * *
     */
    protected void onPostExecute(String file_url) {
        // dismiss the dialog after getting all products
        pDialog.dismiss();
    }

}
}
    
asked by anonymous 12.05.2015 / 18:37

1 answer

1

I was able to solve the problem. The fact is you can not access a view and make a .setText through the doInBackground. I threw the results in onPostExecute () and gave .setText from there.

If someone has the same problem someday .....

    
15.05.2015 / 16:15