简体   繁体   中英

How to pass data from a fragment class to an activity

Please, I am having problem sending an ArrayList data to Activity .

The data is an URL saved in ArrayList but after using bundle extras, I am getting null pointer exception. I also try to catch the exception but still the data i get using get extra string is null

// below is the code i used to pass the data
Bundle extras = new Bundle();
extras.putString("VidUrl",VideoLecturesUrl.get(position));
extras.putString("bookUrl",bookUrl.get(position));                
extras.putString("VidTitle",titleList.get(position));

Intent intent = new Intent(getActivity(),DetailsView.class);
intent.putExtras(extras);
startActivity(intent);


 // below is the receiving activity

 Intent intent = getIntent();
 extras =intent.getExtras();
 if (extras!=null){
      try {
           Video_Url = extras.getString("VidUrl");
           BookUrl = extras.getString("bookUrl");
           Title = extras.getString("VidTitle");
           Toast.makeText(this,Video_Url,Toast.LENGTH_SHORT).show();
           Toast.makeText(this,BookUrl,Toast.LENGTH_SHORT).show();
           Toast.makeText(this,Title,Toast.LENGTH_SHORT).show();
           videotexTitle.setText(Title);
           setTitle(Title);
           setVideo(Video_Url.toString());
       }catch (Exception e){
           e.printStackTrace();
       }
   } else {
       Toast.makeText(this, "the extrass is empty", Toast.LENGTH_SHORT).show();
   }

in the fragment

public interface NoticeFragmentListener {
    public void onFragmentSendArray(ArrayType yourArray);
   
}
NoticeFragmentListener listener;
@Override
public void onAttach(Context context) {
    super.onAttach(context);
    // Verify that the host activity implements the callback interface
    try {
        // Instantiate the NoticeFragmentListener so we can send events to the host
        listener = (NoticeFragmentListener) context;
    } catch (ClassCastException e) {
        // The activity doesn't implement the interface, throw exception
       
    }
}
 //metod to send array
 public void SendArray(ArrayType yourArray){listener.onFragmentSendArray(yourArray);}

in de activity

public class yourActivity extends AppCompatActivity implements YourFragment.NoticeFragmentListener

and recive the array

@Override
public onFragmentSendArray(ArrayType yourArray) {
   
}

For simplicity use the SharedPreferences for this purpose

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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