Transaction ID set correctly, but displayed only a submit later
Asked Answered
G

2

9

My code gives correct response and sets transaction ID correctly. But on screen, the ID is missing the first time I submit, and when I go back and submit again, then the ID on screen is the ID of the first transaction.

On the first submit, this is rendered:

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

On the second submit, this is rendered:

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

I want to see the second screen the first time I submit.

Response to the first submit:

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

Response to the second submit:

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

The code generating the response:

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 Application

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

class Confirm_pay

This is where the ID is set.

MyApplication _Rechargedetail =(MyApplication)getApplicationContext();
    confirm_tId =(TextView)findViewById(R.id._Tid);
    String _tid =_Rechargedetail.getTId_name();
    confirm_tId.setText(_tid);
Grubb answered 18/12, 2015 at 10:7 Comment(0)
H
4

Because you have used Volley library which is already asynchronous, you don't have to use AsyncTask anymore. Your code can be updated as the following (not inside AsyncTask, direct inside onCreate for example), pay attention to // 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: since the reponse data is a JSONObject, so I suggest you use JsonObjectRequest instead of StringRequest. You can read more at Google's documentation.

Hope it helps!

Higgledypiggledy answered 21/12, 2015 at 5:59 Comment(8)
I see. What I want to say here is that you don't need AsyncTask classes anymore. You only need to define Volley requests and add them to RequestQueue, then process response data (for example update UI: textView, editText...) inside onResponse or display error inside onErrorResponseHiggledypiggledy
hey i am using this code but its given error mention in codeGrubb
Volley.newRequestQueue(getActivity()).add(postRequest); //postRequest cannot resolve symbol, since you changed to JsonObjectRequest jsObjRequest, so it must be Volley.newRequestQueue(getActivity()).add(jsObjRequest);Higgledypiggledy
its give now error org.json.JSONException: No value for tidGrubb
So check your response data to see if it has "tid" or not. You can use Log.i("Data", json_Response.toString());Higgledypiggledy
Of course, you should temporarily comment the lines 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); Bundle extra = new Bundle(); extra.putString("TransId", _TID); Log.d("UID IS", "====>" + _uid);Higgledypiggledy
Log.i("Data", json_Response.toString()); to print the actual content of the response data you gotHiggledypiggledy
One more thing, why JSONObject json_Response = new JSONObject(String.valueOf(jsonObject));? jsonObject is enough. Use Log.i("Data", jsonObject.toString()); to view the response data plsHiggledypiggledy
T
0

Your line of code should be executed after complete execution of network operation and control comes in onPostExecute(); of your AsyncTask.

confirm_tId.setText(_tid);
Teston answered 18/12, 2015 at 10:12 Comment(3)
thanks but i don't understand what you want to say, can you elaborate smiplyGrubb
onPostExecute(); is the method of asynctask where you can define what to do with data fetched over the network from doInBackground() method.Teston
how to set this id in onPostExecute();Grubb

© 2022 - 2024 — McMap. All rights reserved.