-3

我的http帖子有问题。此方法适用于我的其他课程/活动中的其他用途,但现在我正在与贝宝集成,它似乎不起作用。是因为我在onActivityResult中应用它吗?如果是这样,我该如何纠正这个问题?

注意力!编辑: 我相信这不是重复的。在我的代码中,我已经包含了 Asynctask 类调用 GetPayPalResult。只是我错误地执行了它。

日志:http 连接错误: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;
        }

     }
}
4

1 回答 1

0

实际上我已经应用了 AsyncTask 但我做错了。Selvin 指出我将 'getJSONfromURL' 调用移至 doInBackground。它有效!

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

     }
于 2013-05-20T10:19:53.147 回答