Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
200 views
in Technique[技术] by (71.8m points)

java - Passing ArrayList from Fragment class to Activity

I have main fragment and I want to pass ArrayList to Activity class, where I will show the result in ListView.

Fragment class:

public class StudentActivity extends Fragment implements OnClickListener {
}

I have data

ArrayList<> allStudents = new ArrayList();
allStudents.add(new Student("H", 99, 93) );    
allStudents.add(new Student("C", 98, 92) );
allStudents.add(new Student("B", 98, 91) );    
allStudents.add(new Student("A", 80, 94) );
allStudents.add(new Student("F", 70, 84) );

Now I want to send "allStudents" object to new activity class StudentResult();

I am using in fragment class:

Intent intent = new Intent(getActivity(), StudentResult.class);
intent.putExtra("ExtraData", allStudents);
startActivity(intent);

and in target class to show the objects in ListView();

public class ResultActivity extends Activity {

    public void myData(ArrayList<allStudents> myArray) {
    marjslistview = (ListView) findViewById(R.id.listView1);
    arrayAdapter = new ArrayAdapter<allStudents>(this, R.layout.student_list, myArray);
    ...
    ScoreLV.setAdapter(arrayAdapter);
    ...
    }
}

thanks in advance!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Create an custom interface in your Fragment:

public interface OnFragmentInteractionListener {    
    public void onFragmentSetStudents(ArrayList<Student>);         
}

Implement this interface in your Activity:

public class YourActivity extends Activity implements YourFragment.OnFragmentInteractionListener {
   private ArrayList<Student> allStudents;
}

Now you have to override the declared method (in your Activity):

@Override
public void onFragmentSetStudents(ArrayList<Student> students) {
  allStudents = students;
}

Then you just have to start this method with an Listener in your Fragment:

OnFragmetInteractionListener listener = (OnFragmentInteractionListener) activity;
listener.onFragmentStudents(allStudents)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...