我正在尝试将字符串从活动传递到片段,并给出错误“空对象引用”

时间:2019-09-17 00:55:15

标签: android android-fragments android-intent android-activity android-bundle

我不明白为什么不起作用,我已经以许多不同的方式对其进行了测试,但是它不起作用... 如何将字符串从活动传递到片段?

public class Test extends AppCompatActivity {

    Parque p = new Parque();

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.teste);


        Bundle b = new Bundle();

        b.putString("StringVall","Hello:...");
        b.putInt("IntVal", 20);
        p.setArguments(b);
    }

}

public class Parque extends Fragment {

    private RecyclerView mRecyclerView;
    private Parque mExampleAdapter;
    private Context mContext;

    public Parque(){

    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.recyclerview, container, false);

        mContext = getActivity();

        mRecyclerView = view.findViewById(R.id.recycler);

       String val= getArguments().getString("StringVall");

       if(val!=null){
           Log.d("ok",val);
       }
       else if(val==null){
           Log.d("not work","...");
       }
       Toast.makeText(getContext(),"valor: " + val,Toast.LENGTH_SHORT).show();

        return view;
    }

}

3 个答案:

答案 0 :(得分:1)

创建一个界面以获取来自ParqueAdapter的点击

interface RecyclerItemClick{
    void onItemClick(Parque parque);
}

创建一个碎片化交互的界面

interface FragmentInteractionListener{
    // function to pass data
    void passData(Parque parque)
} 

=>在ParqueAdapter

声明RecyclerItemClick的实例并创建其设置器

RecyclerItemClick listener

public void setListener(RecyclerItemClick listener){
    this.listener = listener;
}

onBindViewHolder方法中,调用onItemClick方法

public void onBindViewHolder(...) {
    holder.parentLayout.setOnClickListener(new View.OnClickListener(){
        @Override
        public void onClick(View v) {
            listener.onItemClick(currentItem)
        }
    });
}

=>在发送数据的片段中(我称它为DataSenderFragment

声明一个FragmentInteractionListener变量

private OnFragmentInteractionListener mListener;

将其附加到活动实例

@Override public void onAttach(Context context) {
    super.onAttach(context);
    if (context instanceof OnFragmentInteractionListener) {
        mListener = (OnFragmentInteractionListener) context;
    } else {
        throw new RuntimeException(context.toString()
                + " must implement OnFragmentInteractionListener");
    }
}

实施RecyclerItemClick界面并将其设置为您的适配器

public class SendDataFragment extends Fragment implements RecyclerItemClick{
    ...
    onCreate(...){
        ...
        // After instanciate adapter
        adapter.setListener(this);
    }

    @Override void onItemClick(Parque parque){

    }
}

将数据发送到您的活动。适配器中的click事件后触发此方法

@Override void onItemClick(Parque parque){
    mListener.passData(parque);
}

=>在您管理片段的活动中(例如MainActivity

实施FragmentInteractionListener

public class MainActivity implements FragmentInteractionListener{
    ...
    @override void passData(Parque parque){
    }
}

将数据传递到您的地图片段

@override void passData(Parque parque){
    Integer cod = currentItem.getCod();
    Integer ocup = currentItem.getOcupacao();
    ...
    FragmentTransaction tt = getFragmentManager().beginTransaction();
    tt.replace(R.id.fragment_container,new MapaTeste.newInstance(cod, ocup);
    tt.commit();
}

=>在您的地图片段中

创建newInstance方法以将数据传递到MapaTeste片段

public static newInstance newInstance(Integer param1, Integer param2) {
    Parque fragment = new Parque();
    Bundle args = new Bundle();
    args.putInt("data1", param1);
    args.putInt("data2", param2);
    fragment.setArguments(args);
    return fragment;
  }

最后检索这样的数据

public void onCreate(Bundle bundle) {
 super.onCreate(bundle);
 Bundle arguments = getArguments();
 if (arguments != null){
   Integer data1 = getArguments().getString("data1");
   Integer data2 = getArguments().getString("data1");
}

我希望它将对您有所帮助!

答案 1 :(得分:0)

在onCreate中声明您的Parque对象

public class Test extends AppCompatActivity {

        Parque p;

        @Override
        protected void onCreate(@Nullable Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.teste);

            p = new Parque();
            Bundle b = new Bundle();

            b.putString("StringVall","Hello:...");
            b.putInt("IntVal", 20);
            p.setArguments(b);
        }

    }

答案 2 :(得分:0)

由于您获取不存在的未知密钥而导致的错误。将这段代码放在您的片段中,您将在其中将值传递给oncreate到片段

 @Override
public void onCreate(Bundle bundle) {
    super.onCreate(bundle);
    Bundle arguments = getArguments();
    if (arguments != null && arguments.containsKey("StringVall")){
        //if key exists then do further action
        String val= getArguments().getString("StringVall");

    }

}