1

アプリ全体でコードを再利用できるように、単純なメッセージポップアップを処理するクラスを作成しました。文脈を正しく理解できないようです。これは、あちこちから呼び出され、多くの場合、UIを直接持たないクラスから呼び出されます。以下の行を参照してください...

public class msg  {

    public void msghand(String message, Exception e) {
    {

        String s;

        if (e != null) 
        {
            s=  message + "\n" + e.getLocalizedMessage() + " " + e.toString();
        }
        else
        {
            s= message ;
        }

        new AlertDialog.Builder(  getApplicationContext () )  <<<< HERE IS THE PROBLEM
        .setMessage(s)

        .setPositiveButton("OK", new DialogInterface.OnClickListener() {

            public void onClick(DialogInterface dialog, int whichButton) {
            }
        })
        .create()
        .show();


    }

    }
}
4

2 に答える 2

2

コンテキストをパラメーターとして渡すことは可能ですか?

public void msghand(String message, Exception e, Context context) {
    ...
    new AlertDialog.Builder(context)
    ...

コンテキストなしでどこで作業を行っていますか?サービスにはUIはありませんが、コンテキストはあります。

編集:

静的にアクセス可能で、アプリケーションの起動時に作成される小さなメッセージサービスを作成できます。例えば:

class MyActivity extends Activity
{
    public void onCreate(Bundle savedInstanceState)
    {
        // create the Message service that can be statically accessed
        s_MessageService = new MessageService(getApplicationContext());
        ...
    }

    public static MessageService getApplicationMessageService()
    {
        return s_MessageService;
    }

    private static MessageService s_MessageService;
}

MessageServiceが適切に実装されている場所

class MessageService
{
    public MessageService(Context messageContext)
    {
        m_MyContext = messageContext;
    }

    public msghand(String message, Exception e)
    {
        // exactly the same as before, except using the stored context
    }

    Context m_MyContext = null;
}

あなたのDBHelperクラスはそれを経由して使用することができます

MyActivity.getApplicationMessageService().msghand(...);
于 2011-01-14T19:21:04.397 に答える
0

クラスmsgのコンストラクターにパラメーターとしてContextを追加し、それを使用しているアクティビティからこれを渡します。

于 2011-01-14T19:20:24.750 に答える