简体   繁体   English

从片段类调用活动函数给出了NPE

[英]calling function of activity from fragment class gives NPE

I have an activity whose parent class is fragment let we call it fragment A, I have another fragment B from where I want to call the function of the activity related to fragment A, How to call this function? 我有一个活动,其父类是片段让我们称它为片段A,我有另一个片段B从哪里我想调用与片段A相关的活动的函数,如何调用这个函数? I have tried this: Respond and SResponses are the activities whose function am calling.and these function are only called when these activites are in active state. 我试过这个:Respond和SResponses是函数调用的活动。只有当这些活动处于活动状态时才会调用这些函数。

if (Respond.getActivityStatus() == true)
{   
if (Respond.getrthreadid().compareTo(threadid) == 0)                                                         
{   
//Respond res = new Respond();     
//res.notiffy(message);                                                 
((Respond)getActivity()).notiffy(message);                                      
}                                       
}               

if (SResponses.getActivityStatus() == true)                                         
{                                               
if (SResponses.getsrthreadid().compareTo(threadid) == 0)                                                
{                                           
//SResponses sres = new SResponses();                                      
//  sres.notiffy(message);                                  
((SResponses)getActivity()).notiffy(message);                                                                                                   
}                                               
}                                               
}

} catch (RuntimeException e) {

// TODO: handle exception                                               
e.printStackTrace();                                                
}                                               
}                                               

}

} catch (RuntimeException e) {

// TODO: handle exception                                       
e.printStackTrace();

}

But its giving me Null pointer exception. 但它给我Null指针异常。 Please help. 请帮忙。

Your fragment is not always attached to an activity, so at times, getActivity() may return null. 您的片段并不总是附加到活动,因此有时getActivity()可能返回null。

Read about this Coordinating With The Activity Lifecycle . 阅读有关此协调活动生命周期的信息

If you want fragment A to communicate with fragment B, you should define an interface inside fragment A (which the parent activity has to implement) to send data from fragment A to parent activity and from the parent activity send that data to fragment B. 如果希望片段A与片段B通信,则应在片段A(父活动必须实现)内定义接口,以将数据从片段A发送到父活动,并从父活动将该数据发送到片段B.

Check this link. 检查此链接。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM