Reputation: 187
I want to display a toast Message. If I'd do this in onCreate() it'd work fine. But I want to do it like this and I get an error:
Java.Lang.NullPointerException: Attempt to invoke virtual method 'android.content.res.Resources android.content.Context.getResources()' on a null object reference
What should I do?
public void textToast(string textToDisplay) {
Toast.MakeText(this,
textToDisplay, ToastLength.Long).Show();
}
class SampleTabFragment : Fragment
{
Button add;
MainActivity main = new MainActivity();
public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
base.OnCreateView(inflater, container, savedInstanceState);
var view = inflater.Inflate(Resource.Layout.Tab, container, false);
add = view.FindViewById<Button>(Resource.Id.add);
add.Click += Click;
return view;
}
void Click(object sender, EventArgs eventArgs)
{
main.textToast( "I like Toast!");
}
}
Upvotes: 3
Views: 4950
Reputation: 162
If I understand correctly your question, I think a good solution may be this one:
public void makeToast(Context ctx, string str)
{
Toast.MakeText(ctx, str, ToastLength.Long).Show();
}
And when you use it in every fragment you have, you can call it just writing:
makeToast(this.Activity, "test!");
Works for me, let me know :)
Upvotes: 1
Reputation: 12190
The Java.Lang.NullPointerException
is triggered because you are manually creating and using an instance of MainActivity
.
Instead of using a custom instance of MainActivity
to display your toast message in Click
, simplify your code to use the fragments existing activity reference:
public void textToast(string textToDisplay) {
Toast.MakeText(this,
textToDisplay, ToastLength.Long).Show();
}
class SampleTabFragment : Fragment
{
Button add;
// Remove manual creation code
// MainActivity main = new MainActivity();
// ...
void Click(object sender, EventArgs eventArgs)
{
(Activity as MainActivity).textToast( "I like Toast!");
}
}
This code assumes that the owning activity is always an instance of MainActivity
.
See:
Upvotes: 6