繁体   English   中英

如何将片段 class 中的数据传递给活动

[英]How to pass data from a fragment class to an activity

拜托,我在向Activity发送ArrayList数据时遇到问题。

数据是 URL 保存在ArrayList但使用捆绑附加功能后,我收到 null 指针异常。 我也尝试捕获异常,但我使用 get extra string 获得的数据仍然是 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();
   }

在片段中

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);}

在活动中

public class yourActivity extends AppCompatActivity implements YourFragment.NoticeFragmentListener

并接收数组

@Override
public onFragmentSendArray(ArrayType yourArray) {
   
}

为简单起见,为此目的使用 SharedPreferences

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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