Java Android-在文本视图中显示日期错误

Java Android-在文本视图中显示日期错误,java,android,android-fragments,textview,android-date,Java,Android,Android Fragments,Textview,Android Date,所以我创建了一个导航抽屉活动和一些片段。在一个片段中,我有一个文本视图,其中我需要显示像dd.MM.yyyy这样的日期 我设法在另一个应用程序上使用: //show date TextView datumprikaz = (TextView)findViewById(R.id.datumprikaz); Date danas = new Date(); SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy");

所以我创建了一个导航抽屉活动和一些片段。在一个片段中,我有一个文本视图,其中我需要显示像dd.MM.yyyy这样的日期 我设法在另一个应用程序上使用:

//show date
    TextView datumprikaz = (TextView)findViewById(R.id.datumprikaz);
    Date danas = new Date();

    SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy");
    String novDatum = sdf.format(danas);

    datumprikaz.setText(novDatum);
 //End of show date
但当我现在在MainActivity.java中使用它时,会显示错误:

尝试在空对象引用上调用虚拟方法“void android.widget.TextView.setText(java.lang.CharSequence)”

这是错误日志MainActivity.java和my fragment.xml(忽略大代码,日期部分为一行):

您的文本视图
datumprikaz
setContentView


这就是为什么变量
datumprikaz
null

原因是您的文本视图没有正确初始化,这就是为什么会出现NullPointerException。如果您的代码位于片段类中,则应获得如下文本视图:

TextView datumprikaz = (TextView)getView().findViewById(R.id.datumprikaz); 

希望它能起作用。

我想出来了!我只需要将代码添加到该片段(在我的例子中是TvrdjavaFragment)。 代码如下:

public class TvrdjavaFragment extends Fragment {


public TvrdjavaFragment() {
    // Required empty public constructor
}


@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {

    View view = inflater.inflate(R.layout.fragment_tvrdjava, container, false);
    // Inflate the layout for this fragment
    //show date
    TextView datumprikaz = (TextView) view.findViewById(R.id.datumprikaz);
    Date danas = new Date();

    SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy");
    String novDatum = sdf.format(danas);

    datumprikaz.setText(novDatum);
    //End of show date
    return view;
}

我添加了显示日期(查看注释标记)

getView是红色的。它表示无法解析方法“getView()”请帮助您尝试在何处调用getView()?TextView位于片段中。我应该将代码放在MainActivity.java中的什么位置?
public class TvrdjavaFragment extends Fragment {


public TvrdjavaFragment() {
    // Required empty public constructor
}


@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {

    View view = inflater.inflate(R.layout.fragment_tvrdjava, container, false);
    // Inflate the layout for this fragment
    //show date
    TextView datumprikaz = (TextView) view.findViewById(R.id.datumprikaz);
    Date danas = new Date();

    SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy");
    String novDatum = sdf.format(danas);

    datumprikaz.setText(novDatum);
    //End of show date
    return view;
}