如何解决内存泄漏问题?

时间:2018-02-17 08:33:27

标签: java android memory-leaks

我不想使用@SuppressLint("StaticFieldLeak")。如何解决正确的方法呢? (Do not place Android context classes in static fields)

“DataConnect”

public class DataConnect {

    public static DialogPlus dialog;

    public static void showDialog(Context context) {
        dialog = DialogPlus.newDialog(context)
                .setContentHolder(new ViewHolder(R.layout.content))
                .create();
                //
        dialog.show();
        // 
    }
}

然后,当我运行MainActivity时,java.lang.NullPointerException: Attempt to invoke virtual method 'boolean com.orhanobut.dialogplus.DialogPlus.isShowing()' on a null object reference。如何以正确的方式从另一个类调用对话变量?

“MainActivit.java”

public class MainActivity extends AppCompatActivity {

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


    @Override
    public void onBackPressed() {
        try {
            if (dialog.isShowing()) {
                dialog.dismiss();
            } else {
                super.onBackPressed();
            }
        } catch (NullPointerException e) {
            e.printStackTrace();
        }
    }
}

1 个答案:

答案 0 :(得分:1)

在持有android活动/片段或任何视图时,你永远不应该使用静态,因为你会泄漏它们。

如果要在帮助程序类中创建对话框,可以这样做:

public static DialogPlus showDialog(Context context) {
        DialogPlus dialog = DialogPlus.newDialog(context)
                .setContentHolder(new ViewHolder(R.layout.content))
                .create();
                //
        dialog.show();
        return dialog;

    }

在您的活动的某个地方,您可以这样做:

public class MainActivity extends AppCompatActivity {
    private DialogPlus dialog;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        dialog = DataConnect.showDialog(this);
    }


    @Override
    public void onBackPressed() {
            if (dialog != null && dialog.isShowing()) {
                dialog.dismiss();
            } else {
                super.onBackPressed();
            }
    }
}