Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Activity has leaked window that was originally added here

I am getting this error when i try to execute this class file.I am not getting what the error is..?can anyone pls identify where i am going wrong..?

Mnst.class

    //this is class file
    public class Mnst extends AppCompatActivity implements
        View.OnClickListener {

    Button btnDatePicker,save;
    EditText txtDate;
    EditText txtnormal;
    private int mYear, mMonth, mDay;
    String value;
    private String vault;

    public static final String SHARED_PREF_NAME = "myloginapp";
    //We will use this to store the boolean in sharedpreference to track user is loggedin or not
    public static final String LOGGEDIN_SHARED_PREF = "loggedin";

    public static final String MYLAST_SHARED_PREF = "my_last_period";
    public static final String NORMAL_SHARED_PREF = "normal_cycle";
    public static final String REVISED_SHARED_PREF = "revised_cycle";
    public static final String NEXT_SHARED_PREF = "next_period_date";
    public static final String PREDICTEDSTART_SHARED_PREF = "predicted_start_date";
    public static final String PREDICTEDEND_SHARED_PREF = "predicted_end_date";

    DatePickerDialog datePickerDialog;

    private boolean loggedIn = false;


    public static final String UPLOAD_URL = "http://oursite.com/predict.php";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.mnst);

        btnDatePicker=(Button)findViewById(R.id.btn_date);
        save = (Button)findViewById(R.id.save);

        txtDate=(EditText)findViewById(R.id.in_date);
        txtnormal = (EditText) findViewById(R.id.in_date1);

        SharedPreferences sharedPreferences = getSharedPreferences(ProfileLogin.SHARED_PREF_NAME, MODE_PRIVATE);
        vault = sharedPreferences.getString(ProfileLogin.EMAIL_SHARED_PREF,"Not Available");

        btnDatePicker.setOnClickListener(this);
        save.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {

        if (v == btnDatePicker) {

            // Get Current Date
            final Calendar c = Calendar.getInstance();
            mYear = c.get(Calendar.YEAR);
            mMonth = c.get(Calendar.MONTH);
            mDay = c.get(Calendar.DAY_OF_MONTH);


             datePickerDialog = new DatePickerDialog(this,
                    new DatePickerDialog.OnDateSetListener() {

                        @Override
                        public void onDateSet(DatePicker view, int year,
                                              int monthOfYear, int dayOfMonth) {

                            txtDate.setText(dayOfMonth + "-" + (monthOfYear + 1) + "-" + year);
                            value = txtDate.getText().toString();

                        }
                    }, mYear, mMonth, mDay);
            datePickerDialog.show();
        }
        if( v == save)
        {
            registerUser();
            Toast.makeText(getApplicationContext(), value, Toast.LENGTH_SHORT).show();
        }

    }

    /*@Override
    protected void onDestroy() {
        if(datePickerDialog !=null && datePickerDialog.isShowing())
        {
            //<HERE I WANT THE STATE TO BE SAVED IN THE BUNDLE>
            datePickerDialog.dismiss();
        }
        super.onDestroy();
    }*/

    private void registerUser() {

        final String vault_no = vault;

        final String my_last_period = txtDate.getText().toString();
        final String normal_cycle = txtnormal.getText().toString();

        register(vault_no,my_last_period,normal_cycle);

    }

    public void register(String vault_no , String my_last_period , String normal_cycle){

        class RegisterUser extends AsyncTask<String, Integer, JSON> {
            ProgressDialog loading;

            RequestHandler7 ruc = new RequestHandler7();

            @Override
            protected void onPreExecute() {
                super.onPreExecute();
                loading = ProgressDialog.show(Mnst.this, "Please Wait",null, true, true);
            }

                    @SuppressWarnings("deprecation")
                    @Override
                    protected void onPostExecute(JSON s) {
                        super.onPostExecute(s);
                        loading.dismiss();
                        Toast.makeText(getApplicationContext(),"Welcome to Miisky",Toast.LENGTH_LONG).show();

                        SharedPreferences sharedPreferences1 = Mnst.this.getSharedPreferences(SHARED_PREF_NAME, Context.MODE_PRIVATE);

                        //Creating editor to store values to shared preferences
                        SharedPreferences.Editor editor = sharedPreferences1.edit();

                        //Adding values to editor

                        editor.putBoolean(LOGGEDIN_SHARED_PREF, true);
                        editor.putString(MYLAST_SHARED_PREF,  s.my_last_period);
                        editor.putString(NORMAL_SHARED_PREF, s.normal_cycle);
                        editor.putString(REVISED_SHARED_PREF,  s.revised_cycle);
                        editor.putString(NEXT_SHARED_PREF,  s.next_period_date);
                        editor.putString(PREDICTEDSTART_SHARED_PREF,  s.predicted_start_date);
                        editor.putString(PREDICTEDEND_SHARED_PREF, s.predicted_end_date);

                        editor.apply();

                        Intent i = new Intent(Mnst.this,DisplayMnst.class);

                        startActivity(i);
                    }

                    @Override
                    protected JSON doInBackground(String... params) {

                        HashMap<String, String> data = new HashMap<String,String>();
                        data.put("vault_no", params[0]);
                        data.put("my_last_period" , params[1]);
                        data.put("normal_cycle", params[2]);

                        JSON result = ruc.sendPostRequest(UPLOAD_URL,data);
                        return  result;
                    }
                }

        RegisterUser ru = new RegisterUser();
        ru.execute(vault_no,my_last_period,normal_cycle);
    }
}

EDIT

I have added the RequestHandler class..

RequestHandler7

public class RequestHandler7 {

    public JSON sendPostRequest(String requestURL,
                                  HashMap<String, String> postDataParams) {

        URL url;

        StringBuilder sb = new StringBuilder();
        try {
            url = new URL(requestURL);

            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setReadTimeout(15000);
            conn.setConnectTimeout(15000);
            conn.setRequestMethod("POST");
            conn.setDoInput(true);
            conn.setDoOutput(true);


            OutputStream os = conn.getOutputStream();
            BufferedWriter writer = new BufferedWriter(
                    new OutputStreamWriter(os, "UTF-8"));
            writer.write(getPostDataString(postDataParams));

            writer.flush();
            writer.close();
            os.close();
            int responseCode = conn.getResponseCode();

            if (responseCode == HttpsURLConnection.HTTP_OK) {
                BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
                sb = new StringBuilder();
                String response;
                while ((response = br.readLine()) != null){
                    sb.append(response);
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return new Gson().fromJson(sb.toString(),JSON.class);
    }

    private String getPostDataString(HashMap<String, String> params) throws UnsupportedEncodingException {
        StringBuilder result = new StringBuilder();
        boolean first = true;
        for (Map.Entry<String, String> entry : params.entrySet()) {
            if (first)
                first = false;
            else
                result.append("&");

            result.append(URLEncoder.encode(entry.getKey(), "UTF-8"));
            result.append("=");
            result.append(URLEncoder.encode(entry.getValue(), "UTF-8"));
        }

        return result.toString();
    }
}

Log

This is my logcat error..here it is showing "Activity com.example.android.Mnst has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView@5383cdc0 that was originally added here"

E/WindowManager: Activity com.example.miisky.Mnst has leaked window    com.android.internal.policy.impl.PhoneWindow$DecorView@5383cdc0 that was originally added here
android.view.WindowLeaked: Activity com.example.miisky.Mnst has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView@5383cdc0 that was originally added here
at android.view.ViewRootImpl.<init>(ViewRootImpl.java:374)
at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:292)
at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:224)
at android.view.WindowManagerImpl$CompatModeWrapper.addView(WindowManagerImpl.java:149)
at android.view.Window$LocalWindowManager.addView(Window.java:547)
at android.app.Dialog.show(Dialog.java:277)
at android.app.ProgressDialog.show(ProgressDialog.java:116)
at android.app.ProgressDialog.show(ProgressDialog.java:104)
at com.example.miisky.Mnst$1RegisterUser.onPreExecute(Mnst.java:132)
at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:586)
at android.os.AsyncTask.execute(AsyncTask.java:534)
at com.example.miisky.Mnst.register(Mnst.java:178)
at com.example.miisky.Mnst.registerUser(Mnst.java:118)
at com.example.miisky.Mnst.onClick(Mnst.java:95)
at android.view.View.performClick(View.java:4084)
at android.view.View$PerformClick.run(View.java:16966)
at android.os.Handler.handleCallback(Handler.java:615)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4745)
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:786)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
at dalvik.system.NativeStart.main(Native Method)
like image 285
sunil y Avatar asked Mar 12 '23 06:03

sunil y


1 Answers

Window leaked exceptions have two reasons:

1) showing the dialog when Activity Context doesn't exists, to solve this you should show the dialog only you are sure Activity exists:

if(getActivity() != null && !getActivity().isFinishing()) {
     Dialog.show(); // if fragment use getActivity().isFinishing() or isAdded() method
}

2) not dismiss the dialog appropriately, to solve use this code:

@Override
public void onDestroy(){
   super.onDestroy();
   if (Dialog != null && Dialog.isShowing()) {
        Dialog.dismiss();
   }
}

EDIT

in preExecute() use this code

  if (!isFinishing() && loading != null) {
      loading = ProgressDialog.show(Mnst.this, "Please Wait",null, true, true);
  }

and postExecute()

 if (loading != null && loading.isShowing() {
     loading.dismiss();
     loading = null;
 }
like image 66
Sanoop Surendran Avatar answered Apr 26 '23 21:04

Sanoop Surendran