开发者

How do you specify a CONTEXT

开发者 https://www.devze.com 2023-02-05 05:36 出处:网络
I made a class to handle a simple message popup so I can reuse the code throughout the app.I can\'t seem to be able to get the context right.This is called from all over the place and often from class

I made a class to handle a simple message popup so I can reuse the code throughout the app. I can't seem to be able to get the context right. This is called from all over the place and often from classes that does not have a UI directly. See 开发者_高级运维the line below...

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


    }

    }
}


Is it possible for you to pass the Context in as a parameter?

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

Where are you performing work without a Context? Services do not have a UI, but still have a Context.

Edit:

You could create a small message service that is statically accessible, and created when your application starts. For example:

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

Where MessageService is implemented appropriately

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

Your DBHelper class could use it via

MyActivity.getApplicationMessageService().msghand(...);


Add Context as a parameter in the constructor of class msg and pass this in from whatever activity is using it.

0

精彩评论

暂无评论...
验证码 换一张
取 消