活动已泄露最初添加的窗口

时间:2016-08-31 11:57:11

标签: android memory-leaks

当我尝试执行此类文件时,我收到此错误。我没有得到错误是什么..?任何人都可以确定我哪里出错了吗?

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

修改

我添加了RequestHandler类..

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

日志

这是我的logcat错误..它显示“Activity com.example.android.Mnst已泄漏窗口com.android.internal.policy.impl.PhoneWindow$DecorView@5383cdc0,最初是在这里添加的”

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)

1 个答案:

答案 0 :(得分:5)

窗口泄露异常有两个原因:

  

1)当活动上下文不存在时显示对话框,要解决此问题,您应该只显示对话框,确定活动存在:

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

2)不要适当地关闭对话框,解决使用此代码:

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

编辑

preExecute()中的

使用此代码

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

和postExecute()

 if (loading != null && loading.isShowing() {
     loading.dismiss();
     loading = null;
 }