片段中的视图为空 [英] Views in Fragment are null

查看:23
本文介绍了片段中的视图为空的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我仍在开发我的 Android 应用程序.现在我面临这个问题:

Im still working on my Android App. Now im facing this problem:

代码:

package smoca.ch.kreagen.Fragments;

import android.content.Context;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import io.realm.Realm;
import io.realm.RealmQuery;
import smoca.ch.kreagen.R;
import smoca.ch.kreagen.models.Idea;

public class SingleIdeaFragment extends Fragment{
    private TextView title;
    private TextView owner;
    private TextView description;
    private Realm realm;
    private Idea idea;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View layout = inflater.inflate(R.layout.single_idea_fragment_layout, container, false);  // inflate layout for Fragment

        idea = getSingleIdea(getActivity().getBaseContext());

        title = (TextView) container.findViewById(R.id.singleIdeaTitle);
        owner = (TextView) container.findViewById(R.id.singleIdeaOwner);
        description = (TextView) container.findViewById(R.id.singleIdeaDescription);

        title.setText(idea.getTitle());
        owner.setText(idea.getOwnerId());
        description.setText(idea.getText());

        return layout;
    }

    public Idea getSingleIdea(Context ctx) {
        realm = Realm.getInstance(ctx);
        RealmQuery<Idea> ideaQuery = realm.where(Idea.class);
        idea = ideaQuery.findFirst();
        return idea;
    }
}

错误:

java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
            at smoca.ch.kreagen.Fragments.SingleIdeaFragment.onCreateView(SingleIdeaFragment.java:35)

我知道,问题是我的 TextViews(标题、所有者、描述)为空.但我不知道为什么.我将它们分配给布局中的 TextView,引用 ID.

I know, the problem is that my TextViews (title, owner, description) are null. But I don't know why. I assigned them to the TextView's from the layout, referencing the IDs.

我做错了什么?

推荐答案

当您调用 inflater.inflate 时,您将第三个参数 attachToRoot 指定为 错误.这意味着充气器返回的只是 R.layout.single_idea_fragment_layout 的视图.因此,应该在 layout 而不是 container

When you called inflater.inflate, you specified your third parameter, attachToRoot, as false. This means that what gets returned by the inflater is just the view for R.layout.single_idea_fragment_layout. Thus, findViewById should be called on layout rather than container

title = (TextView) layout.findViewById(R.id.singleIdeaTitle);
owner = (TextView) layout.findViewById(R.id.singleIdeaOwner);
description = (TextView) layout.findViewById(R.id.singleIdeaDescription);

这篇关于片段中的视图为空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆