调用getOwnerActivity()方法始终返回null

时间:2017-05-12 06:40:06

标签: android android-intent android-activity

我创建了一个简单的自定义对话框类。在进一步的代码中,我想运行新的Intent

 Intent intent = new Intent(android.content.Intent.ACTION_VIEW,
                    Uri.parse("http://maps.google.com/maps?saddr=20.344,34.34&daddr=20.5666,45.345"));
           startActivity(intent);

但问题是每当我打电话要改变Intent我总是在null得到getOwnerActivity()时 - 如何正确调用该方法?

public class AddToQueueDialog extends Dialog implements View.OnClickListener {

    Activity mActivity;
    private final String android_id = Settings.Secure.getString(getContext().getContentResolver(),
            Settings.Secure.ANDROID_ID);

    public Activity getmActivity() {
        return mActivity;
    }

    public void setmActivity(Activity mActivity) {
        this.mActivity = mActivity;
    }

    public AddToQueueDialog(Context context, WashLocation washLocation) {
        super(context);
        setWashLocation(washLocation);
        setmActivity(getOwnerActivity());
    }

3 个答案:

答案 0 :(得分:1)

如果要检查源代码,则返回的活动仅在setOwnerActivity(活动活动)中设置,而不在任何地方调用。因此,如果您希望getOwnerActivity()返回不同于null的值,则必须更改构造函数,如下所示

 public AddToQueueDialog(Context context, WashLocation washLocation) {
        super(context);
        if (context instanceof Activity) {
             setOwnerActivity((Activity) context);
        }
        setWashLocation(washLocation);
        setmActivity(getOwnerActivity());
    }

答案 1 :(得分:0)

你无法在Oncreate中调用getOwnerActivity()

  

如果您尝试从构造函数中获取所有者,Android尚未挂钩,因此您还没有所有者。

试试这个

public void onAttachedToWindow() {
    super.onAttachedToWindow();
    // getOwnerActivity() should be defined here if called via showDialog(), so do the related init here
    Activity owner = getOwnerActivity();
    if (owner != null) {
        // owner activity defined here
    }
}

答案 2 :(得分:0)

context是拥有Activity。使用context调用构造函数。这是拥有Activity