【问题标题】:How to pass data from a fragment class to an activity如何将数据从片段类传递到活动
【发布时间】:2021-07-23 21:04:35
【问题描述】:

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

数据是保存在ArrayList 中的 URL,但在使用捆绑附加功能后,我收到空指针异常。我也尝试捕获异常,但我使用 get extra string 获得的数据仍然为空

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

【问题讨论】:

  • 你到底在哪里得到 nullpointerexception ?
  • 当我尝试将数据保存到变量以便我可以使用它时
  • 即使当我尝试烘烤数据以确认其仍然是空白的空字符串时

标签: java android arrays android-studio android-fragments


【解决方案1】:

在片段中

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

【讨论】:

    【解决方案2】:

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

    【讨论】:

    • 好的兄弟我试试
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-24
    相关资源
    最近更新 更多