Fragment中的视图为空

时间:2015-09-30 14:41:46

标签: android android-fragments layout null textview

我还在使用我的Android应用程序。现在即将面临这个问题:

代码:

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:尝试在空对象引用上调用虚方法'void android.widget.TextView.setText(java.lang.CharSequence)'               在smoca.ch.kreagen.Fragments.SingleIdeaFragment.onCreateView(SingleIdeaFragment.java:35)

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

我做错了什么?

谢谢&amp;问候 约翰

1 个答案:

答案 0 :(得分:4)

当您致电inflater.inflate时,您将第三个参数 attachToRoot 指定为false。这意味着inflater返回的内容只是R.layout.single_idea_fragment_layout的视图。因此,应findViewById而不是layout

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