【发布时间】:2020-02-12 05:18:15
【问题描述】:
我只是简单地调用了Textview对象上的全局变量并将其打印出来,但是我得到了以下错误
如何正常运行以下代码?
p.s.textread_buf 是全局变量。
日志猫
E/AndroidRuntime: 致命异常: main 进程:com.example.sentence_app,PID:26177
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
at com.example.sentence_app.senten_check_example_mean.onCreateView(senten_check_example_mean.java:40)
//错误代码
public class senten_check_example_mean extends Fragment {
public static senten_check_example_mean newInstance(){
return new senten_check_example_mean();
}
public senten_check_example_mean() {
// Required empty public constructor
}
Button return_sentence_check_button;
TextView textView_name ;
TextView textView_mean ;
TextView textView_example ;
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Inflate the layout for this fragment
textView_name =(TextView) ((MainActivity)getActivity()).findViewById(R.id.text_read_name);
textView_mean =(TextView) ((MainActivity)getActivity()).findViewById(R.id.text_read_mean);
textView_example =(TextView) ((MainActivity)getActivity()).findViewById(R.id.text_read_example);
textView_name.setText(((MyApplication) getActivity().getApplicationContext()).textread_buf.getSentence_name());
textView_mean.setText(((MyApplication) getActivity().getApplicationContext()).textread_buf.getSentence_example());
textView_example.setText(((MyApplication) getActivity().getApplicationContext()).textread_buf.getSentence_mean());
return inflater.inflate(R.layout.fragment_senten_check_example_mean, container, false);
}
}
//textread.class
package com.example.sentence_app;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Stack;
public class textread {
String sentence_name;
String sentence_example;
Queue<String> sentence_mean;
textread(){
}
textread(String temp){
String []cs = temp.split("\\|");
this.setSentence_name(cs[0]);
this.setSentence_mean(cs[1]);
this.setSentence_example(cs[2]);
}
public String getSentence_example() {
return sentence_example;
}
public String getSentence_mean() {
return sentence_mean.peek();
}
public String getSentence_name() {
return sentence_name;
}
}
【问题讨论】:
-
在 onViewCreated 中执行相同的实现。您将在 onViewCreated 中获取视图作为参数,使用它来初始化视图。像 view.findViewById(R.id.text_read_name);这会工作
-
像 id
text_read_name这样的文本视图在您的片段布局中fragment_senten_check_example_mean对吗?
标签: java android nullpointerexception