0

I'm having the same issues getting a custom toast class for reuse in any activity.

I get a null pointer exception or a invoke findviewbyid method error no matter what I try. please help

class Toaster extends Activity {
Toaster(Context context, String message) {

    {
        LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);


        View layout = inflater.inflate(R.layout.toast_layout, (ViewGroup)context.findViewById(R.id.toastroot));

        TextView text = (TextView) layout.findViewById(R.id.toasttext);

        text.setText(message);

        Toast toast = new Toast(context);
        toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
        toast.setDuration(Toast.LENGTH_SHORT);
        toast.setView(layout);
        toast.show();

    }
}}
vinitius
  • 3,212
  • 2
  • 17
  • 22
Robert Goodrick
  • 190
  • 1
  • 11

2 Answers2

0

I don't understand why you are extending Activity. You never construct an activity directly, so constructor here is pointless.
If you are trying to make custom Toast message try this solution:
https://stackoverflow.com/a/11288522/2180461

Edit:

To be more specific about why are you getting NPE:

View layout = inflater.inflate(R.layout.toast_layout, (ViewGroup)context.findViewById(R.id.toastroot));

You are casting context to ViewGroup, and than using it to find R.id.toastroot inside that ViewGroup. Most probably - context here is null, so that's the origin of your Exception.

Community
  • 1
  • 1
  • You are definitely correct. FindByID doesnt work by itself for whatever reason. I have tried every combination I can think of. I'm missing something here. Goal is to be able to call this toast class from any of my 3 activities and just send a different message into it. – Robert Goodrick Mar 28 '15 at 00:18
0

Not the best way to have thins kind of functionality in an Activity.

Instead you could use a class with static methods to do it for you, like this:

 public final class Toaster {

   public static void showToast(final Context context, String message) {
     LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);


    View layout = inflater.inflate(R.layout.toast_layout, (ViewGroup)context.findViewById(R.id.toastroot));

    TextView text = (TextView) layout.findViewById(R.id.toasttext);

    text.setText(message);

    Toast toast = new Toast(context);
    toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
    toast.setDuration(Toast.LENGTH_SHORT);
    toast.setView(layout);
    toast.show();
     }

  }

Then, you would make calls like this:

 Toaster.showToast(context,"some message");
vinitius
  • 3,212
  • 2
  • 17
  • 22