Passing Data from Fragment to Activity

For passing the data from the fragment to the activity we can define "interface" in the fragment class which should be implemented it the activity class in which you want to transfer the data. for this, here is an small example which will show you how to pass the data the to the activity class.

interface is the collection of abstract methods that are implemented by the class. A class that implements an interface must implement all of the non-default methods described in the interface, or be an abstract class.

inside myfragment.java class:

 //define the interface as shown below and call it in the fragment wher you want // to pass the data to the activity..in this case for example we will be passing //sample strings.

public interface myInterface{ 

public void addData(ArrayList<String> lst) ;
//here we can pass the data using Bundle also.

 }


inside myActivity.java class:


//Activity in which you are recieving your data must look like the the one written below implementing //the interface

public myActivity implements myInterface{


 //array list in which data from the fragment will be updated
ArrayList<String> names;

 @override
protected void onCreate(Bundle savedInstance){ //onCreate method of mainActivity. }

public void getData(ArrayList<String> recievedData){

for(int i=0;i<recievedData.getSize();i++)
           { names.add(recievedData.get(i));  } 
}
}

if you have any other issues feel free to ask in the comment section. :)  #MyAndroidThing :D

_______________________________The End__________________________________
Hoping this would be helpful to you, if not, post your problem in the comment section and i will try to get back to you as soon as possible.

tell me, how do you like this solution? and what is there that i can improve...

follow me on hackerrank: www.hackerrank.com/satyansh_sagar

Comments

Popular posts from this blog

Contest Leaderboard: hackerrank problem (Level medium)

Placements: SQL Advance join (Hackerrank Problem)

The Occupation: hackerrank problem