这是我的Fragment类:
公共类StanzeFragment扩展Fragment {
public StanzeFragment(){}
Button vis_stanze;
public TextView testo;
View rootView;
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.activity_log_stanze, container, false);
testo = (TextView) rootView.findViewById(R.id.testo);
vis_stanze = (Button)rootView.findViewById(R.id.bottone_stanze);
vis_stanze.setOnClickListener( new View.OnClickListener() {
@Override
public void onClick(View v) {
getStanze backgroundTask = new getStanze();
backgroundTask.execute();
}
});
return rootView;
}
public void setTesto(String value){
testo.setText(value);
}
}
但是现在我需要在onPostExecute方法中调用其他类(AsyncTask类)中的方法“setTesto”:
@Override
protected void onPostExecute(String result) {
StanzeFragment test = new StanzeFragment();
test.setTesto(result);
}
他给我这个错误:
“java.lang.NullPointerException:尝试在空对象引用上调用虚方法'void com.androidnuovosa.bocci.navdriwerdb.Utente.StanzeFragment.setTesto(java.lang.String)'”..我想因为他不喜欢看看片段视图,我该如何解决这个问题?谢谢你的回答 . (我也有其他课程的这个问题)
编辑:
AsyncTask不在StanzeFragment中
2 回答
Fragments
应该由系统实例化(因为它们在布局XML中定义)或者通过使用FragmentManager方法从代码实例化 .如果您只是实例化
StanzeFragment
,它实际上不会出现在视图堆栈上,而testo
TextView
是null
. This 似乎是你的问题 .在你的情况下,显然
Fragment
在AsyncTask
运行时已经可见,你应该只获得对该Fragment
实例的引用,而不是创建一个新实例 .FragmentManager
有方法通过id
(在XML中定义)或tag
(在以编程方式显示时给定)来查找Fragment
:findFragmentById()
findFragmentByTag()
EDIT:
在你的布局XML中
Activity
你可能有一个Fragment
:现在,根据您的应用程序的确切配置(实际上是
Activity
类型),您将调用以下任一方式:getFragmentManager()
...要么...
getSupportFragmentManager()
......所以,例如:
访问
FragmentManager
. 然后你找到你的MyFragment
,其id为my_fragment
:这应该都在包含所述
Fragment
的Activity
中完成 .保持对Fragments的引用的另一种(替代)方法是在
Activity
中实现onAttachFragment()
方法 . (在Activity
中将包含所述Fragment
):onAttachFragment()
方法在构造Fragment
并由系统显示时运行 . documentation中的确切措辞是所以在这一点上
Fragment
还没有完全准备就绪,但无论如何这会得到对实际出现在设备屏幕上的正确Fragment
实例的引用 . 因此,当您稍后在代码中使用stanzeFragment
时,您可以访问其TextViews等等 .如果您在StanzeFragment中执行AsyncTask,则只需执行以下操作: