-3

I have problem with the http post. This method works for other usage in my other classes/activities but now that I am integrating with paypal, it don't seem to work. Is it because I am applying it in onActivityResult? If so, how do I rectify this?

Attention! Edit: I believe that this is NOT a duplicate. As in my codes I have already included Asynctask class call GetPayPalResult. It is just that I have implemented it wrongly.

Log: Error in http connection :android.os.NetworkOnMainThreadException

public class CheckOut extends BaseActivity  implements OnClickListener{
    TextView f;
    String min_purchase;
    String max_purchase;
    int real_max;
    int purchaserange;
    JSonNParser jsonParser = new JSonNParser();
    String paypalkeyurl = "https://svcs.sandbox.paypal.com/AdaptivePayments/PaymentDetails";
    String payKey;

    int fvalue;
    int minValue;
    double thecost;
    double specialprice;
    TextView theprice;
    TextView t_price;
    String spaceforprice = "    ";
    private PayPal mPayPal;
    String getprice;
    private CheckoutButton launchPayPalButton;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activty_checkout);
        Intent myLocalIntent = getIntent();
        Bundle myBundle = myLocalIntent.getExtras();




        theprice = (TextView) findViewById(R.id.pricetag);
        theprice.setText(option_price);

        t_price = (TextView) findViewById(R.id.totalprice);


        purchaserange = Integer.valueOf(min_purchase);


        minValue = Integer.valueOf(min_purchase);
        f = (TextView) findViewById(R.id.textView1);
        f.setText(String.valueOf(minValue));

        Log.e("OIE!!", "Min Purchase : " + minValue + " | Max Purchase : " + max_purchase);

        getprice = new BigDecimal(String.valueOf(theprice.getText())).multiply(new BigDecimal(String.valueOf(f.getText()))).toString();
        t_price.setText(String.valueOf(getprice) + spaceforprice);


        mPayPal=PayPal.initWithAppID(this,Constants.PAYPAL_APP_ID,PayPal.ENV_SANDBOX);
        mPayPal.setShippingEnabled(true);

        //mPayPal.
        initUI(Double.valueOf(String.valueOf(getprice)));

    }




     private void initUI(double theprice) {

        //launchPayPalButton = mPayPal.getCheckoutButton(this, 
        //      PayPal.BUTTON_278x43, CheckoutButton.TEXT_PAY);
        launchPayPalButton = mPayPal.getCheckoutButton(this, 
                R.drawable.paybutton, CheckoutButton.TEXT_PAY);

        //launchPayPalButton.setShippingEnabled(true);


        LinearLayout.LayoutParams params = new
                LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, 
                        LayoutParams.WRAP_CONTENT);
        params.bottomMargin = (int) theprice;

        launchPayPalButton.setLayoutParams(params);

        specialprice = theprice;
        launchPayPalButton.setOnClickListener(this);
        String srr=String.valueOf(specialprice);

        ((RadioGroup)findViewById(R.id.bottommenu)).addView(launchPayPalButton);
        LinearLayout.LayoutParams layoutParams =(LinearLayout.LayoutParams)launchPayPalButton.getLayoutParams();
    }





    public void onClick(View v) {
        payWithPaypal(Double.valueOf((String.valueOf(getprice))));
    }

    public void setCost(double cost) {
        this.thecost = cost;
    }

    public double getCost() {
        return this.thecost;
    }


    private void payWithPaypal(Double gg) {
        PayPalPayment newPayment = new PayPalPayment();
        Toast.makeText(getApplicationContext(),gg.toString(), Toast.LENGTH_LONG).show();
        BigDecimal bigDecimal=new BigDecimal(gg);
        newPayment.setSubtotal(bigDecimal);
        newPayment.setCurrencyType(Currency.getInstance(Locale.US));
        newPayment.setRecipient("whatad_1358762874_biz@hotmail.com");
        newPayment.setMerchantName("My Merchant");
        Intent paypalIntent = PayPal.getInstance().checkout(newPayment, this);
        this.startActivityForResult(paypalIntent, 1);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch(resultCode) {
        case Activity.RESULT_OK:
            payKey = data.getStringExtra(PayPalActivity.EXTRA_PAY_KEY);

            Toast.makeText(this,"Paymnet Successful : " + payKey,Toast.LENGTH_LONG).show();
            //finish();


            new GetPayPalResult().execute();
            //
            break;
        case Activity.RESULT_CANCELED:
            Toast.makeText(this,"Paymnet Cancel",Toast.LENGTH_LONG).show();
            //finish();
            break;
        case PayPalActivity.RESULT_FAILURE:
            Toast.makeText(this,"Paymnet Failed",Toast.LENGTH_LONG).show();
            String errorID = data.getStringExtra(PayPalActivity.EXTRA_ERROR_ID);
            String errorMessage = data.getStringExtra(PayPalActivity.EXTRA_ERROR_MESSAGE);
            //Toast.makeText(getApplicationContext(),errorMessage, Toast.LENGTH_LONG).show();
            //finish();
            break;
        }
    }


    public AbsListView.RecyclerListener mRecyclerListener = new RecyclerListener( ){

         public void onMovedToScrapHeap(View view) {
             ViewHolder viewHolder = (ViewHolder) view.getTag();
             DownloadImageTask imagetask = viewHolder.mTask;
             if (imagetask != null) {
                 imagetask.cancel(true);
             }
         }

     };

     public String getContentfromURL(String url, String method, List<NameValuePair> params) {
            InputStream is = null;
            String result = "";
            //Toast.makeText(CouponView.this,"running this", Toast.LENGTH_LONG).show();
            // http post
            try {

                HttpPost httppost = new HttpPost(url);
                HttpResponse response = Client.getInstance().execute(httppost);
                HttpEntity entity = response.getEntity();
                is = entity.getContent();

            } catch (Exception e) {
                Log.e("log_tag", "Error in http connection :" + e.toString());
            }

            // convert response to string
            try {
                BufferedReader reader = new BufferedReader(new InputStreamReader(
                        is, "iso-8859-1"), 8);
                StringBuilder sb = new StringBuilder();
                String line = null;
                while ((line = reader.readLine()) != null) {
                    sb.append(line + "\n");
                }
                is.close();
                result = sb.toString();
            } catch (Exception e) {
                Log.e("log_tag", "Error converting result " + e.toString());
            }
            return result;
        }















     class GetPayPalResult extends AsyncTask<String, String, String> {
        ListActivity theList = new ListActivity();
        private ListView mainListView ;  
        private ProgressDialog pDialog;



         /* *
          * Before starting background thread Show Progress Dialog
          * */
         @Override
         protected void onPreExecute() {
             super.onPreExecute();
             pDialog = new ProgressDialog(CheckOut.this);
             pDialog.setMessage("Loading Options ...");
             pDialog.setIndeterminate(false);
             pDialog.setCancelable(false);
             pDialog.show();
         }

         /* *
          * getting Inbox JSON
          * */
         protected String doInBackground(String... args) {
             // Building Parameters

             return null;
         }

         /* *
          * After completing background task Dismiss the progress dialog
          * * */
         protected void onPostExecute(String file_url) {
            mainListView = (ListView) findViewById( R.id.list);  
             // dismiss the dialog after getting all products
             pDialog.dismiss();


             List<NameValuePair> params = new ArrayList<NameValuePair>();



             params.add(new BasicNameValuePair("payKey", payKey));
             params.add(new BasicNameValuePair("requestEnvelope.errorLanguage", "en_US"));
             httppost.setHeader("X-PAYPAL-SECURITY-USERID", "66.whatever.com");
            httppost.setHeader("X-PAYPAL-SECURITY-PASSWORD", "6666666");
            httppost.setHeader("X-PAYPAL-SECURITY-SIGNATURE", "55546g");
            httppost.setHeader("X-PAYPAL-APPLICATION-ID", "APP-80W284485P519543T");
            httppost.setHeader("X-PAYPAL-REQUEST-DATA-FORMAT", "NV");
            httppost.setHeader("X-PAYPAL-RESPONSE-DATA-FORMAT", "NV");
            String result = getJSONfromURL(paypalkeyurl,params);

            Log.d("Paykey Content: ", result);


         }

         public String getJSONfromURL(String url, List<NameValuePair> params) {
            InputStream is = null;
            String result = "";
            //Toast.makeText(CouponView.this,"running this", Toast.LENGTH_LONG).show();
            // http post
            try {


                HttpPost httppost = new HttpPost(url);

                httppost.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));

                HttpResponse response = Client.getInstance().execute(httppost);

                HttpEntity entity = response.getEntity();
                is = entity.getContent();

            } catch (Exception e) {
                Log.e("log_tag", "Error in http connection :" + e.toString());
            }

            // convert response to string
            try {
                BufferedReader reader = new BufferedReader(new InputStreamReader(
                        is, "iso-8859-1"), 8);
                StringBuilder sb = new StringBuilder();
                String line = null;
                while ((line = reader.readLine()) != null) {
                    sb.append(line + "\n");
                }
                is.close();
                result = sb.toString();
            } catch (Exception e) {
                Log.e("log_tag", "Error converting result " + e.toString());
            }
            return result;
        }

     }
}
OneNation
  • 427
  • 1
  • 8
  • 22
  • 1
    as the exception says you are doing executing code that can require lot of time on the UI Thread. onPostExecute, in your code, for instance, makes an Http requeste to a webserver. Probably this is causing the error – Blackbelt May 20 '13 at 09:55
  • 1
    in addition to @blackbelt comment: you should move getJSONfromURL call into doInBackground – Selvin May 20 '13 at 09:57
  • Hey guys, this is not a duplicate. I have editted to prove my point – OneNation May 21 '13 at 01:36

1 Answers1

0

Actually I have already applied the AsyncTask but I did it wrongly. Selvin pointed out that I move 'getJSONfromURL' call into doInBackground. And it works!

class GetPayPalResult extends AsyncTask<String, String, String> {
        ListActivity theList = new ListActivity();
        private ListView mainListView ;  
        private ProgressDialog pDialog;



         /* *
          * Before starting background thread Show Progress Dialog
          * */
         @Override
         protected void onPreExecute() {
             super.onPreExecute();
             pDialog = new ProgressDialog(CheckOut.this);
             pDialog.setMessage("Loading Options ...");
             pDialog.setIndeterminate(false);
             pDialog.setCancelable(false);
             pDialog.show();
         }

         /* *
          * getting Inbox JSON
          * */
         protected String doInBackground(String... args) {
             // Building Parameters
             List<NameValuePair> params = new ArrayList<NameValuePair>();



             params.add(new BasicNameValuePair("payKey", payKey));
             params.add(new BasicNameValuePair("requestEnvelope.errorLanguage", "en_US"));
             httppost.setHeader("X-PAYPAL-SECURITY-USERID", "66.whatever.com");
            httppost.setHeader("X-PAYPAL-SECURITY-PASSWORD", "6666666");
            httppost.setHeader("X-PAYPAL-SECURITY-SIGNATURE", "55546g");
            httppost.setHeader("X-PAYPAL-APPLICATION-ID", "APP-80W284485P519543T");
            httppost.setHeader("X-PAYPAL-REQUEST-DATA-FORMAT", "NV");
            httppost.setHeader("X-PAYPAL-RESPONSE-DATA-FORMAT", "NV");
            String result = getJSONfromURL(paypalkeyurl,params);

            Log.d("Paykey Content: ", result);
             return null;
         }

         /* *
          * After completing background task Dismiss the progress dialog
          * * */
         protected void onPostExecute(String file_url) {

             pDialog.dismiss();





         }

         public String getJSONfromURL(String url, List<NameValuePair> params) {
            InputStream is = null;
            String result = "";
            //Toast.makeText(CouponView.this,"running this", Toast.LENGTH_LONG).show();
            // http post
            try {


                HttpPost httppost = new HttpPost(url);

                httppost.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));

                HttpResponse response = Client.getInstance().execute(httppost);

                HttpEntity entity = response.getEntity();
                is = entity.getContent();

            } catch (Exception e) {
                Log.e("log_tag", "Error in http connection :" + e.toString());
            }

            // convert response to string
            try {
                BufferedReader reader = new BufferedReader(new InputStreamReader(
                        is, "iso-8859-1"), 8);
                StringBuilder sb = new StringBuilder();
                String line = null;
                while ((line = reader.readLine()) != null) {
                    sb.append(line + "\n");
                }
                is.close();
                result = sb.toString();
            } catch (Exception e) {
                Log.e("log_tag", "Error converting result " + e.toString());
            }
            return result;
        }

     }
OneNation
  • 427
  • 1
  • 8
  • 22