从两个不同的活动调用函数显示警报对话框

Calling a function show alert dialog from two different activities

我遇到过我的两个活动应该调用相同函数的情况。主活动和短信活动。我编写了一个 HelperClass 并创建了一个函数 getTagSelectionFromDialogBox()。 getTagSelectionFromDialogBox() 显示警告对话框并做一些工作。

我正在从 MainActivity 实例化 HelperClass 并通过传递上下文调用 helperclass.getTagSelectionFromDialogBox() 工作正常。

但是当我从 SMSActivity 执行相同操作时,应用程序崩溃了。我认为这是因为上下文错误但不确定。

启动 HelperClass() 时,我从 MainActivity 调用 HelperClass.getinstance(getApplicationContext()),从 SMSActivity 调用时,我调用 HelperClass.getinstalce(getApplicationContext())。

下面是来自 MainActivity 的代码

    HelperClass helperclass = HelperClass.getInstalce(getApplicationContext());
    tagHandler.getTagSelectionFromDialogBox(rowData);

来自 SMSActivity

    HelperClass helperclass = HelperClass.getInstalce(getApplicationContext());
    helperclass.getTagSelectionFromDialogBox(rowData);     

HelperClass的部分代码是

    public class HelperClass {

Context context = null;
private static HelperClass HelperClass = null;

private HelperClass(Context context) {
    this.context = context;

}

public static synchronized HelperClass getInstalce(Context context) {
    if(helperclass == null) {
        helperclass = new TagHandler(context.getApplicationContext());
    }

    return helperclass;
}

public  void getTagSelectionFromDialogBox(final RowData rowData) {
    String selectedTitle = null;
String[] navTitles = = {"one", "tow", "Three"};

    AlertDialog.Builder alertDialog = new AlertDialog.Builder(context.getApplicationContext());
    alertDialog.setTitle("Select Category");
    alertDialog.setSingleChoiceItems(navTitles, -1, new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            int title_position = which;
            String selectedTitle = navTitles[which];
            dialog.cancel();
            if (rowData.getInfoPath() != null) {
                //doing some work
            } else {
                //doing some work
            }
        }
    });
    AlertDialog ad = alertDialog.create();
    ad.show();
}

}

Logcat 显示以下错误

        android.view.WindowManager$BadTokenException: Unable to add window -- token null is not for an application
        at android.view.ViewRootImpl.setView(ViewRootImpl.java:570)
        at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:282)
        at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:85)
        at android.app.Dialog.show(Dialog.java:306)
        at com.srids.tagit.TagHandler.getTagSelectionFromDialogBox(HelperClass.java:75)
        at com.srids.tagit.SMSActivity.onClick(SMSActivity.java:140)
        at android.view.View.performClick(View.java:4856)
        at android.view.View$PerformClick.run(View.java:19956)
        at android.os.Handler.handleCallback(Handler.java:739)
        at android.os.Handler.dispatchMessage(Handler.java:95)

其中 HelperClass.java:75 是 ad.show()。我怀疑问题可能与传递的上下文有关,但不确定如何解决该问题。

MainActivity代码部分。它很大,所以放上它的 onCreate() 代码:

    Below is the code

    public class MainActivity extends ActionBarActivity implements NavigationDrawerFragment.FragmentDrawerListener, shareDataInterface {

private Toolbar toolbar;
NavigationDrawerFragment navigationDrawerFragment;
HelperClass helperclass = null;


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

    toolbar = (Toolbar) findViewById(R.id.toolbar);
    toolbar.setTitle("tagIt");
    toolbar.setSubtitle("make search easy..");
    toolbar.setTitleTextColor(getResources().getColor(R.color.colorAccent));
    setSupportActionBar(toolbar);
    getSupportActionBar().setDisplayShowHomeEnabled(true);

    utils= new Utils();
    prefs = MyPrefs.getInstance(this);
    if(prefs.getBool(MyGlobals.PASSWORD_PROTECT) == true) {
        if(loggedin == 0) {
            loggedin = 1;
            utils.showDialog(MainActivity.this, MyGlobals.DIALOG_PIN_INPUT);
        }
    }

    // populate navigation drawer
    navigationDrawerFragment = (NavigationDrawerFragment) getSupportFragmentManager().findFragmentById(R.id.fragment_navigation_drawer);
    navigationDrawerFragment.setUp(R.id.fragment_navigation_drawer, (DrawerLayout) findViewById(R.id.drawer_layout), toolbar);
    navigationDrawerFragment.setDrawerListener(this);

    // establish data base connection and first read tags list for NAV drawer
    db = DatabaseHelper.getInstance(getApplicationContext());

    navTitles =navigationDrawerFragment.titles;

    // create tag handler
    helperclass = HelperClass.getInstalce(getApplicationContext());   

}

}

您所做的不是处理此类情况的正确方法更新您的代码

  public class HelperClass {

    public static void getTagSelectionFromDialogBox(final Context context,final RowData rowData) {
        String selectedTitle = null;
    String[] navTitles = = {"one", "tow", "Three"};

        AlertDialog.Builder alertDialog = new AlertDialog.Builder(context);
        alertDialog.setTitle("Select Category");
        alertDialog.setSingleChoiceItems(navTitles, -1, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                int title_position = which;
                String selectedTitle = navTitles[which];
                dialog.cancel();
                if (rowData.getInfoPath() != null) {
                    //doing some work
                } else {
                    //doing some work
                }
            }
        });
        AlertDialog ad = alertDialog.create();
        ad.show();
    }

    }

用法

HelperClass.getTagSelectionFromDialogBox(MainActivty.this,rowData);

用下面的代码替换 MainActivity 代码

    public class MainActivity extends ActionBarActivity implements NavigationDrawerFragment.FragmentDrawerListener, shareDataInterface {

private Toolbar toolbar;
NavigationDrawerFragment navigationDrawerFragment;


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

    toolbar = (Toolbar) findViewById(R.id.toolbar);
    toolbar.setTitle("tagIt");
    toolbar.setSubtitle("make search easy..");
    toolbar.setTitleTextColor(getResources().getColor(R.color.colorAccent));
    setSupportActionBar(toolbar);
    getSupportActionBar().setDisplayShowHomeEnabled(true);

    utils= new Utils();
    prefs = MyPrefs.getInstance(this);
    if(prefs.getBool(MyGlobals.PASSWORD_PROTECT) == true) {
        if(loggedin == 0) {
            loggedin = 1;
            utils.showDialog(MainActivity.this, MyGlobals.DIALOG_PIN_INPUT);
        }
    }

    // populate navigation drawer
    navigationDrawerFragment = (NavigationDrawerFragment) getSupportFragmentManager().findFragmentById(R.id.fragment_navigation_drawer);
    navigationDrawerFragment.setUp(R.id.fragment_navigation_drawer, (DrawerLayout) findViewById(R.id.drawer_layout), toolbar);
    navigationDrawerFragment.setDrawerListener(this);

    // establish data base connection and first read tags list for NAV drawer
    db = DatabaseHelper.getInstance(getApplicationContext());

    navTitles =navigationDrawerFragment.titles;

 //Get your rowdata before calling the method

  HelperClass.getTagSelectionFromDialogBox(MainActivty.this,rowData);

除了 anoop 的回答之外,请这样做以获得更好的性能 如果您使用的是应用程序 class,请将以下代码放入应用程序 class、

HelperClass mHelperClass;
public final HelperClass getHelperClass() {
    if(mHelperClass == null) {
        mHelperClass = new HelperClass();
    }
    return mHelperClass;
}

并在任何需要的地方使用 getHelperClass() 方法。

希望这对您有所帮助..

您不应该使用应用程序上下文来显示您的对话框,而不是 activity。没有附加到应用程序上下文的对话框视图。如果要在 MainActivity 和 SMSActivity 处显示两个对话框,则需要更新 class HelperClass 中的上下文值。

或许您可以这样更改您的代码:

主要活动

HelperClass helperclass = HelperClass.getInstalce();
helperclass .getTagSelectionFromDialogBox(MainActivity.this, rowData);

SMSActivity

HelperClass helperclass = HelperClass.getInstalce();
helperclass .getTagSelectionFromDialogBox(SMSActivity.this, rowData);

辅助类

public class HelperClass {

private static HelperClass helperclass = null;

private HelperClass() {

}

public static synchronized HelperClass getInstalce() {
    if (helperclass == null) {
        helperclass = new HelperClass();
    }
    return helperclass;
}

public void getTagSelectionFromDialogBox(Context context, final RowData rowData) {
    String selectedTitle = null;
    String[] navTitles = {"one", "tow", "Three"};

    AlertDialog.Builder alertDialog = new AlertDialog.Builder(context);
    alertDialog.setTitle("Select Category");
    alertDialog.setSingleChoiceItems(navTitles, -1, new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            int title_position = which;
            String selectedTitle = navTitles[which];
            dialog.cancel();
            if (rowData.getInfoPath() != null) {
                //doing some work
            } else {
                //doing some work
            }
        }
    });
    AlertDialog ad = alertDialog.create();
    ad.show();
}

}