android - 交易ID设置正确,但稍后只显示一个提交

标签 android json android-volley

我的代码给出了正确的响应并正确设置了事务 ID。但是第一次提交时屏幕上的id不见了,等我回去再提交时,屏幕上的id就是第一次交易的id。

第一次提交时,呈现如下:

 MOBILE NUMBER: 9129992929
      OPERATOR: AIRTEL
        AMOUNT: 344
TRANSACTION ID:

第二次提交时,呈现如下:

 MOBILE NUMBER: 9129992929
      OPERATOR: AIRTEL
        AMOUNT: 344
TRANSACTION ID: NUFEC37WD537K5K2P9WX

我想在第一次提交时看到第二个屏幕。

对第一次提交的回应:

D/TID IS: ====>NUFEC37WD537K5K2P9WX D/UID IS:
====>27W3NDW71XRUR83S7RN3 D/Response-------: ------>{"tid":"NUFEC37WD537K5K2P9WX","uid":"27W3NDW71XRUR83S7RN3","status":"ok"}

对第二次提交的回应:

D/TID IS: ====>18R6YXM82345655ZL3E2 D/UID IS:
====>27W3NDW71XRUR83S7RN3 D/Response-------: ------>{"tid":"18R6YXM82345655ZL3E2","uid":"27W3NDW71XRUR83S7RN3","status":"ok"}

生成响应的代码:

public class Prepaid extends Fragment implements View.OnClickListener {

    Button submit_recharge;
    Activity context;
    RadioGroup _RadioGroup;
    public EditText number, amount;
    JSONObject jsonobject;
    JSONArray jsonarray;
    ArrayList<String> datalist, oprList;
    ArrayList<Json_Data> json_data;
    TextView output, output1;
    String loginURL = "http://www.www.example.com/operator_details.php";
    ArrayList<String> listItems = new ArrayList<>();
    ArrayAdapter<String> adapter;
    String data = "";

    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        final View rootview = inflater.inflate(R.layout.prepaid, container, false);
        submit_recharge = (Button) rootview.findViewById(R.id.prepaid_submit);
        number = (EditText) rootview.findViewById(R.id.prenumber);
        amount = (EditText) rootview.findViewById(R.id.rechergpre);
        submit_recharge.setOnClickListener(this);
        context = getActivity();
        new DownloadJSON().execute();
        return rootview;
    }

    public void onClick(View v) {
        MyApplication myRecharge = (MyApplication) getActivity().getApplicationContext();
        final String prepaid_Number = number.getText().toString();
        String number_set = myRecharge.setNumber(prepaid_Number);
        final String pre_Amount = amount.getText().toString();
        String amount_set = myRecharge.setAmount(pre_Amount);
        Log.d("amount", "is" + amount_set);
        Log.d("number", "is" + number_set);

        switch (v.getId()) {
            case R.id.prepaid_submit:
                if (prepaid_Number.equalsIgnoreCase("") || pre_Amount.equalsIgnoreCase("")) {
                    number.setError("Enter the number please");
                    amount.setError("Enter amount please");
                } else {
                    int net_amount_pre = Integer.parseInt(amount.getText().toString().trim());
                    String ph_number_pre = number.getText().toString();
                    if (ph_number_pre.length() != 10) {
                        number.setError("Please Enter valid the number");
                    } else {
                        if (net_amount_pre < 10 || net_amount_pre > 2000) {
                            amount.setError("Amount valid 10 to 2000");
                        } else {
                            AsyncTaskPost runner = new AsyncTaskPost();         // for running AsyncTaskPost class
                            runner.execute();
                            Intent intent = new Intent(getActivity(), Confirm_Payment.class);
                            startActivity(intent);
                        }

                    }
                }
        }
    }
}
/*
 *
 * http://pastie.org/10618261
 *
 */

private class DownloadJSON extends AsyncTask<Void, Void, Void> {
    MyApplication myOpt = (MyApplication) getActivity().getApplicationContext();

    protected Void doInBackground(Void... params) {
        json_data = new ArrayList<Json_Data>();
        datalist = new ArrayList<String>();
      //       made a new array to store operator ID
        oprList = new ArrayList<String>();
        jsonobject = JSONfunctions
                .getJSONfromURL(http://www.www.example.com/operator_details.php");
        Log.d("Response: ", "> " + jsonobject);
        try {
            jsonarray = jsonobject.getJSONArray("data");
            for (int i = 0; i < jsonarray.length(); i++) {
                jsonobject = jsonarray.getJSONObject(i);
                Json_Data opt_code = new Json_Data();
                opt_code.setName(jsonobject.optString("name"));
                opt_code.setId(jsonobject.optString("ID"));
                json_data.add(opt_code);
                datalist.add(jsonobject.optString("name"));
                oprList.add(jsonobject.getString("ID"));
            }
        } catch (Exception e) {
            Log.e("Error", e.getMessage());
            e.printStackTrace();
        }
        return null;
    }

    protected void onPostExecute(Void args) {
        final Spinner mySpinner = (Spinner) getView().findViewById(R.id.operator_spinner);
        mySpinner
                .setAdapter(new ArrayAdapter<String>(getActivity(),
                        android.R.layout.simple_spinner_dropdown_item,
                        datalist));
        mySpinner
                .setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                    public void onItemSelected(AdapterView<?> arg0,
                                               View arg1, int position, long arg3) {

                        String opt_code = oprList.get(position);
                        String selectedItem = arg0.getItemAtPosition(position).toString();
                        Log.d("Selected operator is==", "======>" + selectedItem);
                        Log.d("Selected Value is======", "========>" + position);
                        Log.d("Selected ID is======", "========>" + opt_code);
                        if (opt_code == "8" || opt_code == "14" || opt_code == "35" || opt_code == "36" || opt_code == "41" || opt_code == "43")  // new code
                        {
                            _RadioGroup = (RadioGroup) getView().findViewById(R.id.radioGroup);
                            _RadioGroup.setVisibility(View.VISIBLE);
                            int selectedId = _RadioGroup.getCheckedRadioButtonId();
                            // find the radiobutton by returned id
                            final RadioButton _RadioSex = (RadioButton) getView().findViewById(selectedId);

                            _RadioSex.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                                @Override
                                public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                                    if (null != _RadioSex && isChecked == false) {
                                        Toast.makeText(getActivity(), _RadioSex.getText(), Toast.LENGTH_LONG).show();
                                    }
                                    Toast.makeText(getActivity(), "Checked In button", Toast.LENGTH_LONG).show();
                                    Log.d("Checked In Button", "===>" + isChecked);
                                }
                            });
                        }
                        String user1 = myOpt.setOperator(opt_code);
                        String opt_name = myOpt.setOpt_provider(selectedItem);
                    }

                    public void onNothingSelected(AdapterView<?> arg0) {
                        // TODO Auto-generated method stub
                    }
                });
    }
}
private class AsyncTaskPost extends AsyncTask<String, Void, Void> {
    MyApplication mytid = (MyApplication)getActivity().getApplicationContext();
    String prepaid_Number = number.getText().toString();
    String pre_Amount = amount.getText().toString();
    protected Void doInBackground(String... params) {
        String url = "http://www.example.com/android-initiate-recharge.php";

        StringRequest postRequest = new StringRequest(Request.Method.POST, url,
            new Response.Listener<String>() {
                public void onResponse(String response) {
                    try {
                        JSONObject json_Response = new JSONObject(response);
                        String _TID = json_Response.getString("tid");
                        String _uid = json_Response.getString("uid");
                        String _status = json_Response.getString("status");
                        String tid_m =mytid.setTransaction(_TID);
                        Log.d("TID IS","====>"+tid_m);
                        Log.d("UID IS", "====>" + _uid);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    Log.d("Response-------", "------>" + response);
                }
            },
            new Response.ErrorListener() {
                public void onErrorResponse(VolleyError error) {
                    Log.e("Responce error==","===>"+error);
                    error.printStackTrace();
                }
            }
        ) {
            MyApplication uid = (MyApplication) getActivity().getApplicationContext();
            final String user = uid.getuser();
            MyApplication operator = (MyApplication) getActivity().getApplicationContext();
            final String optcode = operator.getOperator();

            protected Map<String, String> getParams() {
                Map<String, String> params = new HashMap<>();
                // the POST parameters:
                params.put("preNumber", prepaid_Number);
                params.put("preAmount", pre_Amount);
                params.put("key", "XXXXXXXXXX");
                params.put("whattodo", "prepaidmobile");
                params.put("userid", user);
                params.put("category", optcode);
                Log.d("Value is ----------", ">" + params);
                return params;
            }
        };
        Volley.newRequestQueue(getActivity()).add(postRequest);
        return null;
    }
    protected void onPostExecute(Void args) {
    }
}

类(class)申请

 private String _TId;
 public  String getTId_name() {
    return _TId;
 }

public String setTId_name(String myt_ID) {
    this._TId = myt_ID;
    Log.d("Application set TID", "====>" + myt_ID);
    return myt_ID;
}

类 Confirm_pay

这是设置ID的地方。

MyApplication _Rechargedetail =(MyApplication)getApplicationContext();
    confirm_tId =(TextView)findViewById(R.id._Tid);
    String _tid =_Rechargedetail.getTId_name();
    confirm_tId.setText(_tid);

最佳答案

因为您已经使用了已经是异步的Volley 库,所以您不必再使用AsyncTask。 你的代码可以更新如下(不在AsyncTask里面,比如直接在onCreate里面),注意//update TextViews here...:

...
            String url = "http://www.example.com/index.php";
            RequestQueue requestQueue = Volley.newRequestQueue(this);
            StringRequest postRequest = new StringRequest(Request.Method.POST, url,
                    new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {

                        try {
                           JSONObject json_Response = new JSONObject(response);
                            String _TID = json_Response.getString("tid");
                            String _uid = json_Response.getString("uid");
                            String _status = json_Response.getString("status");
                            String tid_m =mytid.setTId_name(_TID);
                            Log.d("TID IS","====>"+tid_m);
                            Log.d("UID IS","====>"+_uid);
                            // update TextViews here...
                            txtTransId.setText(_TID);
                            txtStatus.setText(_status);
                            ...
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                        Log.d("Response-------", "------>" + response);
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Log.e("Responce error==","===>"+error);
                        error.printStackTrace();
                    }
                }
           requestQueue.add(postRequest);
...

P/S:由于响应数据是一个JSONObject,所以我建议你使用JsonObjectRequest而不是StringRequest。您可以在 Google's documentation 阅读更多内容.

希望对您有所帮助!

关于android - 交易ID设置正确,但稍后只显示一个提交,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34353006/

相关文章:

javascript - 使用纯 JavaScript 或 Lodash 进行 JSON 数组操作

java - 使用 Volley 时后台服务出现 OutofMemory 错误

java - Android Volley 请求未更新

android - 用于后台任务的最佳做法是什么?

android - 找不到 ActionBarSherlock ForceOverflow 资源

Android.Share 到社交网络

java - 用于第 3 方库的自定义 jackson 反序列化器

java - 如何将 Spinner 插入到 ListView 的每一行

javascript - 如何通过单击我的网站页面上的按钮来调用 Crossrider "background.js"中声明的 javascript 函数?

android - 从图库中选择要上传的照片时,应用程序崩溃