java - fragment 函数中的 NullPointerException

标签 java android android-fragments nullpointerexception

我正在尝试在我的 fragment 中显示自定义 toast。我的代码如下

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();

    }

我在 onClick 我的按钮上调用此函数,但出现错误

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

我在onCreateView之外添加了上述函数。

我的 XML 如下所示

<?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>

我的完整 fragment 代码如下。

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;
        }

    }

}

我试图在过去两个小时内找到解决方案,但没有找到任何解决方案。让我知道我做错了什么。谢谢

最佳答案

正如错误消息告诉您的那样,R.id.toast_layout_rootR.id.ToastIcon 或您的 R.id.text变量为 null,因此不允许使用 null 值进行函数调用。

请调试您的代码并查看哪个变量为 null

您还可以查看文档并了解具体错误消息的实际含义。

关于java - fragment 函数中的 NullPointerException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46264292/

相关文章:

java - 如何使用 Hibernate Annotations 在 Lob/Clob/tinyblob 上添加索引

java - 从文本文件中获取所有单词(Java)

Android: RelativeLayout inside FrameLayout, width height 错误

Android:具有操作栏的众多 fragment 之一,而其他 fragment 则没有

android - android中隐藏和显示复选框问题

java - 如何在 netbeans 7.4 中删除 hibernate 中的警告

java - TabHost 显示一次内容 (onCreate)

Android Firebase 身份验证 : verify account and reset password within the App

android - TextView 安卓 :autoLink attribute recognize IP address pattern unexpectly

android - 使用约束库的 1.0.0-alpha7 版本,该版本已过时