简体   繁体   中英

I'm getting a null pointer exception when I subclass an OnClickListener()

I'm trying to subclass one of my OnClickListener() 's and I'm getting a 'null pointer' exception, but I'm not sure why.. I'm going nuts over this.. any help would be greatly appreciated..

Here is the code in my Utilities Class located in com.Tools

public class Utilities 
{
public static View.OnClickListener CreateOnClickListener(final Context context,final Class<?> cls)
{
    final Activity act = new Activity();
    View.OnClickListener listener = new View.OnClickListener() 
    {
            public void onClick(View v) 
            {
                Intent window = new Intent(context, cls);
                act.startActivity(window);
                act.finish();
            }
    };

    return listener;
}
}

And when I call it from my main class I do this:

final Button button1 = (Button) findViewById(R.id.button1);
button1.setOnClickListener(Utilities.CreateOnClickListener(MainMenu.this, SettingsMenu.class));

When I debug, the exception occurs on this line:

act.startActivity(window);

Any ideas??? Thank you very much in advance!!!

You can't use an Activity that you create out of thin air like that. It needs to be attached to the system to be useful. Besides, you don't need it. Try this implementation instead:

public class Utilities 
{
public static View.OnClickListener CreateOnClickListener(final Context context,final Class<?> cls)
{
    View.OnClickListener listener = new View.OnClickListener() 
    {
            public void onClick(View v) 
            {
                Intent window = new Intent(context, cls);
                context.startActivity(window);
            }
    };

    return listener;
}
}

Well I think when you call

act.startActivity(window);

it should be called from current context. ie

context.startActivity(window);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM