Passing ArrayList from Fragment class to Activity

2019-01-20 05:15发布

问题:

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!

回答1:

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)


回答2:

In your Activity:

Bundle bundle = getIntent().getExtras(); 
ArrayList allStudents = bundle.get("ExtraData");

and I think you need to define your ArrayAdapter as:

arrayAdapter = new ArrayAdapter<Student>(this, R.layout.student_list, allStudents);

You have the rest of the code, just add the above. It should work.