user3091531
user3091531

Reputation: 107

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? 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.

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. Please help.

Upvotes: 0

Views: 121

Answers (2)

Kanwaljit Singh
Kanwaljit Singh

Reputation: 4377

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.

Check this link.

Upvotes: 0

Greg Ennis
Greg Ennis

Reputation: 15379

Your fragment is not always attached to an activity, so at times, getActivity() may return null.

Read about this Coordinating With The Activity Lifecycle.

Upvotes: 2

Related Questions