0

I am trying to display custom toast in my fragment. My code for same is like below

public void showToastFav(){

        LayoutInflater inflater = getLayoutInflater();
        View layout = inflater.inflate(R.layout.correct_toast,
                (ViewGroup) view.findViewById(R.id.toast_layout_root));
        ImageView ToastIconNew = (ImageView) layout.findViewById(R.id.ToastIcon);
        TextView text = (TextView) layout.findViewById(R.id.text);
        text.setText("Helo");
        //ToastIconNew.setImageDrawable(ToastIcon);
        Toast toast = new Toast(getActivity());
        toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
        toast.setDuration(Toast.LENGTH_LONG);
        toast.setView(layout);
        toast.show();

    }

I am calling this on onClick my button but getting error called

    java.lang.NullPointerException: Attempt to invoke virtual method
android.view.View android.view.View.findViewById(int) 
on a null object reference

I have added above function outside onCreateView.

My XML is like below

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/toast_layout_root"
    android:orientation="horizontal"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:padding="10dp"
    android:background="?attr/colorPrimaryDark">


        <ImageView
            android:id="@+id/ToastIcon"
            android:layout_width="@dimen/nav_but_size"
            android:layout_height="@dimen/nav_but_size"
            android:src="@drawable/ic_like"
            android:layout_gravity="center_horizontal|center_vertical"
            android:tint="?attr/TextColor" />
        <TextView
            android:layout_marginLeft="15dp"
            android:layout_marginStart="15dp"
            android:background="?attr/List_Text"
            android:layout_width="2dp"
            android:layout_height="match_parent" />

        <TextView
            android:id="@+id/text"
            android:textStyle="bold"
            android:layout_marginLeft="15dp"
            android:layout_marginStart="15dp"
            android:textSize="@dimen/newMainText"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center_vertical"
            android:gravity="start"
            android:text="two\n newlike "
            android:textColor="?attr/TextColor" />


</LinearLayout>

My Full Fragment code is like below.

public class QuoteFragment extends Fragment implements View.OnClickListener{
    int fragVal;
    String text;
    View view;
    RelativeLayout image,message,whatsapp,facebook,insta;

    public static QuoteFragment init(int val,String text) {
        QuoteFragment truitonFrag = new QuoteFragment();
        // Supply val input as an argument.
        Bundle args = new Bundle();
        args.putInt("val", val);
        args.putString("text",text);
        truitonFrag.setArguments(args);
        return truitonFrag;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        fragVal = getArguments() != null ? getArguments().getInt("val") : 1;
        text = getArguments() != null ? getArguments().getString("text") : "";

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        final View view = inflater.inflate(R.layout.quote_fragment_layout, container, false);
        image = (RelativeLayout) view.findViewById(R.id.image);
        image.setOnClickListener(this);
        whatsapp = (RelativeLayout) view.findViewById(R.id.whatsapp);
        whatsapp.setOnClickListener(this);
        insta = (RelativeLayout) view.findViewById(R.id.insta);
        insta.setOnClickListener(this);
        facebook = (RelativeLayout) view.findViewById(R.id.facebook);
        facebook.setOnClickListener(this);
        message = (RelativeLayout) view.findViewById(R.id.message);
        message.setOnClickListener(this);
        Typeface font = Typeface.createFromAsset(getActivity().getAssets(), constant.font);
        final TextView mQuoteText = (TextView) view.findViewById(R.id.textDetailQuote);
        mQuoteText.setTypeface(font,Typeface.BOLD);
        try {
            mQuoteText.setText(text);
        } catch (Exception e) {
            mQuoteText.setText("Hello !!");
        }


        return view;



    }
    public void showToastFav(){

        LayoutInflater inflater = getLayoutInflater();
        View layout = inflater.inflate(R.layout.correct_toast,
                (ViewGroup).findViewById(R.id.toast_layout_root));
        ImageView ToastIconNew = (ImageView) layout.findViewById(R.id.ToastIcon);
        TextView text = (TextView) layout.findViewById(R.id.text);
        text.setText("Helo");
        //ToastIconNew.setImageDrawable(ToastIcon);
        Toast toast = new Toast(getActivity());
        toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
        toast.setDuration(Toast.LENGTH_LONG);
        toast.setView(layout);
        toast.show();

    }
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.image:
                Intent i = new Intent(getActivity(), NameArt.class);
                i.putExtra("quotetext", text);
                startActivity(i);
                break;
            case R.id.whatsapp:
                try{
                Intent fbIntent = new Intent(Intent.ACTION_SEND);
                fbIntent.putExtra(Intent.EXTRA_TEXT, text);
                fbIntent.setType("text/plain");
                fbIntent.setPackage("com.whatsapp");
                fbIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                startActivity(fbIntent);
                } catch (Exception e) {
                 e.printStackTrace();
                Toast.makeText(getActivity(), "Something Wrong", Toast.LENGTH_SHORT).show();
                 }
                break;
            case R.id.facebook:
                try{
                        Intent fbIntent = new Intent(Intent.ACTION_SEND);
                        fbIntent.putExtra(Intent.EXTRA_TEXT, text);
                        fbIntent.setType("text/plain");
                        fbIntent.setPackage("com.facebook.orca");
                        fbIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                        startActivity(fbIntent);
        } catch (Exception e) {
            e.printStackTrace();
            Toast.makeText(getActivity(), "Please Install Facebook Messenger", Toast.LENGTH_SHORT).show();
        }

                break;
            case R.id.insta:
                Intent emailIntent = new Intent(Intent.ACTION_SENDTO, Uri.fromParts("mailto", "", null));
                emailIntent.putExtra(Intent.EXTRA_SUBJECT, "Best Hindi Status");
                emailIntent.putExtra(Intent.EXTRA_TEXT, text);
                startActivity(Intent.createChooser(emailIntent, "Send email..."));

                break;
            case R.id.message:
                //String myText=currentQuote.getQuText();
                android.content.ClipboardManager clipboard = (android.content.ClipboardManager) getActivity().getSystemService(Context.CLIPBOARD_SERVICE);
                android.content.ClipData clip = android.content.ClipData.newPlainText("Copied Text",text );
                clipboard.setPrimaryClip(clip);
                Toast.makeText(getActivity(),text,Toast.LENGTH_SHORT).show();
                showToastFav();
                break;
            default:
                break;
        }

    }

}

I am trying to get solution from last two hours but not found any. Let me know what I am doing wrong with this. Thanks

Phantômaxx
  • 37,901
  • 21
  • 84
  • 115
Priya
  • 1,602
  • 4
  • 22
  • 37

2 Answers2

3

As the error message tells you, either R.id.toast_layout_root, R.id.ToastIcon or your R.id.text variable is null and therefore the function call is not allowed with a null-value.

Please debug into your code and have a look at which variable is null.

You can also look at the documentation and look what the specific error message actually means.

cramopy
  • 3,459
  • 6
  • 28
  • 42
  • How can I solve it ? Sorry I am learning android yet. Thanks – Priya Sep 17 '17 at 12:55
  • @Priya on which line does the error appear? This is important to reduce the null-field which are possible – cramopy Sep 17 '17 at 12:57
  • I am getting error in (ViewGroup) view.findViewById(R.id.toast_layout_root)); This line – Priya Sep 17 '17 at 13:00
  • @Priya yeah, so now you know where error does appear. I can't tell you anymore than what my answer currently is, because I've got no deep android-java knowledge.. but you can search for `Attempt to invoke virtual method android.view.View android.view.View.findViewById(int) on a null object reference` on stack overflow and look at the existing answers to identify which does solve your special problem. – cramopy Sep 17 '17 at 13:06
  • Thanks all friends for help me to find solution. Thanks a lot :) – Priya Sep 17 '17 at 13:31
  • @Priya no problem, glad to hear you having the solution :) if my answer helped you, please also mark it as solved – cramopy Sep 17 '17 at 13:49
2

There was small mistake in code. I have changed view to getActivity and its working fine now. new code is like below

LayoutInflater inflater = getLayoutInflater();
        View layout = inflater.inflate(R.layout.correct_toast,
                (ViewGroup)getActivity().findViewById(R.id.toast_layout_root));

Thanks

Priya
  • 1,602
  • 4
  • 22
  • 37