无法从一个片段接收数据到另一个片段

时间:2017-05-11 05:29:58

标签: android android-fragments

我想实现片段通信。实际上我正在尝试将编辑文本数据从一个片段发送到第二个片段。我已经尝试了一些代码,但我的要求没有得到满足。

My First Fragment就在这里

我以不同的方式尝试过,但我无法解决,所以请指导我。

Verification.java 第一个片段

public class Verification extends Fragment {
    EditText card_NO,pin_code;
    Button button;
    Toolbar toolbar;


    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view=inflater.inflate(R.layout.verificaton,null);
        card_NO=(EditText)view.findViewById(R.id.cardNo);
        pin_code=(EditText)view.findViewById(R.id.pin);
        button=(Button)view.findViewById(R.id.varify);


        toolbar=(Toolbar)view.findViewById(R.id.toolbar);
        toolbar.setTitle("Verification");
        listeners();
        return view;

    }

    private void listeners() {
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                acc_logIn();

            }
        });
    }

    private void acc_logIn(){
        String cardid = card_NO.getText().toString().trim();
        String pin = pin_code.getText().toString().trim();
        verify(cardid,pin);
//
    }

    private void verify(final String cardid, final String pin){
        class UserVerification extends AsyncTask<String,Void,String> {
            ProgressDialog loading;
            @Override
            protected void onPreExecute() {
                super.onPreExecute();
                loading = ProgressDialog.show(getActivity(),"Please Wait",null,true,true);
            }

            @Override
            protected void onPostExecute(String s) {
                super.onPostExecute(s);
                loading.dismiss();
                if(s.equalsIgnoreCase("Welcome....")){
                    Toast.makeText(getActivity(),"Successfully Verified",Toast.LENGTH_LONG).show();
                    String cardid = card_NO.getText().toString();

                    FragmentManager manager=getFragmentManager();
                    FragmentTransaction transaction=manager.beginTransaction();
                    Bundle bundle=new Bundle();

                    bundle.putString(Config.KEY_ACCOUNT, cardid);
                    BankServices bankServices=new BankServices();
                    bankServices.setArguments(bundle);
                    transaction.add(R.id.myFrame,bankServices);
                    transaction.commit();
                }else{
                    Toast.makeText(getActivity(),s,Toast.LENGTH_LONG).show();
                }
            }

            @Override
            protected String doInBackground(String... params) {
                HashMap<String,String> data = new HashMap<>();
                data.put("cardid",params[0]);
                data.put("pin",params[1]);

                RequestHandler rh=new RequestHandler();

                String result=rh.sendPostRequest(Config.URL_VERIFY,data);

                return result;

            }
        }
        UserVerification uv = new UserVerification();
        uv.execute(cardid,pin);
    }

}

BankServices.java 第二个片段

    public class BankServices extends Fragment {
    private Button balance,transfer,bill;
    private TextView textView;
    private Toolbar toolbar;


    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        Bundle bundle = this.getArguments();
        if (bundle != null) {
            String cardid = bundle.getString(Config.KEY_ACCOUNT);
            textView.setText(cardid);
        }
    }


    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View v=inflater.inflate(R.layout.services,null);
        balance=(Button)v.findViewById(R.id.bt_balanceInq);
        transfer=(Button)v.findViewById(R.id.bt_transfer);
        bill=(Button)v.findViewById(R.id.bt_payBill);

        toolbar= (Toolbar) v.findViewById(R.id.toolbar);
        toolbar.setTitle("Services");

//        Bundle bundle = this.getArguments();
//        if (bundle != null) {
//            String cardid = bundle.getString(Config.KEY_ACCOUNT);
//            textView.setText(cardid);
//        }

        listeners();
        return v;
    }

    private void listeners() {

        balance.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                FragmentManager manager=getFragmentManager();
                FragmentTransaction transaction = manager.beginTransaction();

                CheckBal checkBal=new CheckBal();
               // transaction.add(R.id.myFrame,checkBal);
                transaction.replace(R.id.myFrame,checkBal);
                transaction.addToBackStack(null);
                transaction.commitAllowingStateLoss();
              //  transaction.commit();
            }
        });

        transfer.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                FragmentManager manager=getFragmentManager();
                FragmentTransaction transaction = manager.beginTransaction();

                Transfer tr=new Transfer();
            //    transaction.add(R.id.myFrame,tr);
                transaction.replace(R.id.myFrame,tr);
                transaction.addToBackStack(null);
                transaction.commitAllowingStateLoss();
            }
        });
        bill.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                FragmentManager manager=getFragmentManager();
                FragmentTransaction transaction = manager.beginTransaction();

                PayBill payBill=new PayBill();
        //        transaction.add(R.id.myFrame,payBill);
                transaction.replace(R.id.myFrame,payBill);
                transaction.addToBackStack(null);
                transaction.commitAllowingStateLoss();
            }
        });
    }
}

I try this now and it gives this error occurred ..

流程:com.example.hp.amibank,PID:3532                   java.lang.NullPointerException:尝试在空对象引用上调用虚方法'void android.widget.TextView.setText(java.lang.CharSequence)'                       在com.example.hp.amibank.BankServices.onViewCreated(BankServices.java:31)                       在android.app.FragmentManagerImpl.moveToState(FragmentManager.java:1010)                       在android.app.FragmentManagerImpl.moveToState(FragmentManager.java:1171)

4 个答案:

答案 0 :(得分:1)

嗨Abdulmateen关注你的问题https://stackoverflow.com/questions/43920934/error-on-sending-data-from-one-fragment-to-another#43920934。你的问题的解决方案是在OnCreateView中添加textView =(TextView)findViewById(id here),类似于bill =(Button)v.findViewById(R.id.bt_payBill)。您的错误堆栈跟踪清楚地表明您正在尝试在尚未初始化textView的null引用上调用setText,希望它有所帮助。

答案 1 :(得分:0)

尝试

Verification.java 第一个片段

public class Verification extends Fragment {

    EditText card_NO,pin_code;
    Button button;
    Toolbar toolbar;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view=inflater.inflate(R.layout.verificaton,null);
        card_NO=(EditText)view.findViewById(R.id.cardNo);
        pin_code=(EditText)view.findViewById(R.id.pin);
        button=(Button)view.findViewById(R.id.varify);


        toolbar=(Toolbar)view.findViewById(R.id.toolbar);
        toolbar.setTitle("Verification");
        listeners();
        return view;

    }

    private void listeners() {
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                acc_logIn();

                String cardid = card_NO.getText().toString();
                PayBill payBill = new PayBill();
                Bundle bundle = new Bundle();
                bundle.putString(Config.KEY_ACCOUNT, cardid);
                payBill.setArguments(bundle);

            }
        });
    }

    private void acc_logIn(){
        String cardid = card_NO.getText().toString().trim();
        String pin = pin_code.getText().toString().trim();
        verify(cardid,pin);
//
    }

    private void verify(final String cardid, final String pin){
        class UserVerification extends AsyncTask<String,Void,String> {
            ProgressDialog loading;
            @Override
            protected void onPreExecute() {
                super.onPreExecute();
                loading = ProgressDialog.show(getActivity(),"Please Wait",null,true,true);
            }

            @Override
            protected void onPostExecute(String s) {
                super.onPostExecute(s);
                loading.dismiss();
                if(s.equalsIgnoreCase("Welcome....")){
                    Toast.makeText(getActivity(),"Successfully Verified",Toast.LENGTH_LONG).show();
                    FragmentManager manager=getFragmentManager();
                FragmentTransaction transaction=manager.beginTransaction();
                BankServices bankServices=new BankServices();
                transaction.add(R.id.myFrame,bankServices);
                transaction.commit();
                    Bundle bundle=new Bundle();

                    bundle.putString(Config.KEY_ACCOUNT, cardid);
                    PayBill payBill=new PayBill();
                    payBill.setArguments(bundle);

                    FragmentManager manager= getActivity().getFragmentManager(); //getSupportFragmentManager
                    FragmentTransaction transaction=manager.beginTransaction();
                    Bundle bundle=new Bundle();

                    bundle.putString(Config.KEY_ACCOUNT, cardid);
                    PayBill payBill=new PayBill();
                    payBill.setArguments(bundle);
                    transaction.add(R.id.yourFragmeID,payBill);
                    transaction.commit();

//                   Intent intent = new Intent(getActivity(),PayBill.class);
//                    intent.putExtra(Config.KEY_ACCOUNT,cardid);
//                    startActivity(intent);
                }else{
                    Toast.makeText(getActivity(),s,Toast.LENGTH_LONG).show();
                }
            }

            @Override
            protected String doInBackground(String... params) {
                HashMap<String,String> data = new HashMap<>();
                data.put("cardid",params[0]);
                data.put("pin",params[1]);

                RequestHandler rh=new RequestHandler();

                String result=rh.sendPostRequest(Config.URL_VERIFY,data);

                return result;

            }
        }
        UserVerification uv = new UserVerification();
        uv.execute(cardid,pin);
    }

}

PayBill.java 已更新

public class PayBill extends Fragment {
    private EditText ref;
    private EditText bill;
    private TextView textView;

    private Button fetch,bt_pay;


    private ProgressDialog loading;
    Toolbar toolbar;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View v=inflater.inflate(R.layout.paybill,null);
        ref=(EditText)v.findViewById(R.id.refId);
        textView=(TextView)v.findViewById(R.id.tv_c);
        bill=(EditText) v.findViewById(R.id.tv_Bill);
        fetch=(Button)v.findViewById(R.id.bt_fetch);
        bt_pay=(Button)v.findViewById(R.id.bt_payBill);

        fetch.setOnClickListener(
                new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getBill();
            }
        });

        bt_pay.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                paybill();
            }
        });

        toolbar=(Toolbar)v.findViewById(R.id.toolbar);
        toolbar.setTitle("Pay Bill");

        Bundle bundle = this.getArguments();
        if (bundle != null) {
            String cardid = bundle.getString(Config.KEY_ACCOUNT);
            textView.setText(cardid);
        }

        return v;
    }

    private void getBill(){
        final String rid = ref.getText().toString().trim();
        if (rid.equals("")) {
            Toast.makeText(getActivity(), "Please enter an id", Toast.LENGTH_LONG).show();
            return;
        }
        loading = ProgressDialog.show(getActivity(),"Please wait ......","fetching....",false,false);
        String url = Config.URL_Get_BILL+ref.getText().toString().trim();
        StringRequest stringRequest = new StringRequest(url, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                loading.dismiss();
                showJSON(response);
            }

    },
            new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            Toast.makeText(getActivity(),error.getMessage().toString(),Toast.LENGTH_LONG).show();
        }
    });

    RequestQueue requestQueue = Volley.newRequestQueue(getActivity());
    requestQueue.add(stringRequest);
}
    private void showJSON(String response){
        String sbill="";

        try {
            JSONObject jsonObject = new JSONObject(response);
            JSONArray result = jsonObject.getJSONArray(Config.TAG_JSON_ARRAY);
            JSONObject collegeData = result.getJSONObject(0);
            sbill = collegeData.getString(Config.TAG_SHOW_BILL);

        } catch (JSONException e) {
            e.printStackTrace();
        }
        bill.setText(sbill);
    }
    private void paybill() {


        final String rid = ref.getText().toString().trim();
        final String paydue = bill.getText().toString().trim();
        final String cardid=textView.getText().toString().trim();

        loading = ProgressDialog.show(getActivity(), "Please wait ......", "Working....", false, false);

        StringRequest stringRequest = new StringRequest(Request.Method.POST, Config.URL_PAY_BILL,
                new Response.Listener<String>() {

                    @Override
                    public void onResponse(String response) {
                        loading.dismiss();
                        Toast.makeText(getActivity(), response, Toast.LENGTH_LONG).show();
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        loading.dismiss();

                        Toast.makeText(getActivity(), error.toString(), Toast.LENGTH_LONG).show();
                        Toast.makeText(getActivity(), error.toString(), Toast.LENGTH_LONG).show();
                        Toast.makeText(getActivity(), error.toString(), Toast.LENGTH_LONG).show();
                    }
                }) {
            @Override
            protected Map<String, String> getParams() {
                Map<String, String> params = new HashMap<String, String>();
                params.put(Config.KEY_ACCOUNT, cardid);
                params.put(Config.KEY_BILL_ID,rid);
                params.put(Config.KEY_BILL_DUE, paydue);
                return params;
            }

        };

        RequestQueue requestQueue = Volley.newRequestQueue(getActivity());
        requestQueue.add(stringRequest);

    }

}

答案 2 :(得分:0)

问题出现在第一个片段中,您的起始BankService片段只是创建了PayBill的对象,

代码已更新

private void verify(final String cardid, final String pin){
    class UserVerification extends AsyncTask<String,Void,String> {
        ProgressDialog loading;
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            loading = ProgressDialog.show(getActivity(),"Please Wait",null,true,true);
        }

        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
            loading.dismiss();
            if(s.equalsIgnoreCase("Welcome....")){
                Toast.makeText(getActivity(),"Successfully Verified",Toast.LENGTH_LONG).show();
                FragmentManager manager=getFragmentManager();
            FragmentTransaction transaction=manager.beginTransaction();
            Bundle bundle=new Bundle();

                bundle.putString(Config.KEY_ACCOUNT, cardid);
                PayBill payBill=new PayBill();
                payBill.setArguments(bundle);
            transaction.add(R.id.myFrame,payBill);
            transaction.commit();

            }else{
                Toast.makeText(getActivity(),s,Toast.LENGTH_LONG).show();
            }
        }

        @Override
        protected String doInBackground(String... params) {
            HashMap<String,String> data = new HashMap<>();
            data.put("cardid",params[0]);
            data.put("pin",params[1]);

            RequestHandler rh=new RequestHandler();

            String result=rh.sendPostRequest(Config.URL_VERIFY,data);

            return result;

        }
    }
    UserVerification uv = new UserVerification();
    uv.execute(cardid,pin);
}

答案 3 :(得分:0)

我希望这会对你有所帮助

在Post方法中更改片段1

Fragment PayBill = new PayBill();
                            Bundle bundle = new Bundle();
                            bundle.putString(Config.KEY_ACCOUNT, cardid);
                            PayBill.setArguments(bundle);
                            FragmentManager fragmentManager = getActivity().getSupportFragmentManager();
                            FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
                            fragmentTransaction.add(R.id.myFrame, PayBill);
                            fragmentTransaction.commit();

// -----------片段2 ---------------

public class PayBill extends Fragment {
    private EditText ref;
    private EditText bill;
    private TextView textView;
    String cardid;
    private Button fetch,bt_pay;
    private ProgressDialog loading;
    Toolbar toolbar;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Bundle bundle = this.getArguments();
        if (bundle != null) {
             cardid = getArguments().getString(Config.KEY_ACCOUNT);

        }
    }
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View v=inflater.inflate(R.layout.paybill,null);
        ref=(EditText)v.findViewById(R.id.refId);
        textView=(TextView)v.findViewById(R.id.tv_c);
        bill=(EditText) v.findViewById(R.id.tv_Bill);
        fetch=(Button)v.findViewById(R.id.bt_fetch);
        bt_pay=(Button)v.findViewById(R.id.bt_payBill);
         textView.setText(cardid);
        fetch.setOnClickListener(
                new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getBill();
            }
        });
        bt_pay.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                paybill();
            }
        });
        toolbar=(Toolbar)v.findViewById(R.id.toolbar);
        toolbar.setTitle(“Pay Bill”);
        return v;
    }
    private void getBill(){
        final String rid = ref.getText().toString().trim();
        if (rid.equals(“”)) {
            Toast.makeText(getActivity(), “Please enter an id”, Toast.LENGTH_LONG).show();
            return;
        }
        loading = ProgressDialog.show(getActivity(),“Please wait ......“,”fetching....“,false,false);
        String url = Config.URL_Get_BILL+ref.getText().toString().trim();
        StringRequest stringRequest = new StringRequest(url, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                loading.dismiss();
                showJSON(response);
            }
    },
            new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            Toast.makeText(getActivity(),error.getMessage().toString(),Toast.LENGTH_LONG).show();
        }
    });
    RequestQueue requestQueue = Volley.newRequestQueue(getActivity());
    requestQueue.add(stringRequest);
}
    private void showJSON(String response){
        String sbill=“”;
        try {
            JSONObject jsonObject = new JSONObject(response);
            JSONArray result = jsonObject.getJSONArray(Config.TAG_JSON_ARRAY);
            JSONObject collegeData = result.getJSONObject(0);
            sbill = collegeData.getString(Config.TAG_SHOW_BILL);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        bill.setText(sbill);
    }
    private void paybill() {
        final String rid = ref.getText().toString().trim();
        final String paydue = bill.getText().toString().trim();
        final String cardid=textView.getText().toString().trim();
        loading = ProgressDialog.show(getActivity(), “Please wait ......“, “Working....“, false, false);
        StringRequest stringRequest = new StringRequest(Request.Method.POST, Config.URL_PAY_BILL,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        loading.dismiss();
                        Toast.makeText(getActivity(), response, Toast.LENGTH_LONG).show();
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        loading.dismiss();
                        Toast.makeText(getActivity(), error.toString(), Toast.LENGTH_LONG).show();
                        Toast.makeText(getActivity(), error.toString(), Toast.LENGTH_LONG).show();
                        Toast.makeText(getActivity(), error.toString(), Toast.LENGTH_LONG).show();
                    }
                }) {
            @Override
            protected Map<String, String> getParams() {
                Map<String, String> params = new HashMap<String, String>();
                params.put(Config.KEY_ACCOUNT, cardid);
                params.put(Config.KEY_BILL_ID,rid);
                params.put(Config.KEY_BILL_DUE, paydue);
                return params;
            }
        };
        RequestQueue requestQueue = Volley.newRequestQueue(getActivity());
        requestQueue.add(stringRequest);
    }
}