Reputation: 5586
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!!!
Upvotes: 0
Views: 356
Reputation: 37729
Well I think when you call
act.startActivity(window);
it should be called from current context. i.e
context.startActivity(window);
Upvotes: 1
Reputation: 234847
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;
}
}
Upvotes: 5