如何将onActivityResult中的String变量传递到同一.java文件中的另一个类

时间:2015-04-13 17:18:02

标签: android class android-asynctask

我需要将一个来自onActivityResult函数的String变量传递给另一个类,该类扩展了我在同一个.java文件中编写的AsyncTask(sendData)。我需要传递名为js的String变量。

这是我的代码

public class Donate extends Activity{

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == REQUEST_CODE_PAYMENT) {
        if (resultCode == Activity.RESULT_OK) {
            PaymentConfirmation confirm =
                    data.getParcelableExtra(PaymentActivity.EXTRA_RESULT_CONFIRMATION);

            if (confirm != null) {
                Log.i(TAG, confirm.toJSONObject().toString());
                Log.i(TAG, confirm.getPayment().toJSONObject().toString());
                Log.i(TAG, confirm.getProofOfPayment().toJSONObject().toString());
                String js = confirm.getProofOfPayment().toJSONObject().toString();

                new sendData().execute(js);




                Toast.makeText(
                        getApplicationContext(),
                        "PaymentConfirmation info received from PayPal", Toast.LENGTH_LONG)
                        .show();
                Intent conf = new Intent(getApplicationContext(), PayConfirm.class);
                startActivity(conf);
            }
        } else if (resultCode == Activity.RESULT_CANCELED) {
            Log.i(TAG, "The user canceled.");
        } else if (resultCode == PaymentActivity.RESULT_EXTRAS_INVALID) {
            Log.i(TAG,"An invalid Payment or PayPalConfiguration was submitted. Please see the docs.");
        }
    } 
}

public class sendData extends AsyncTask<String, String, Void> {

    @Override
    protected Void doInBackground(String... params) {


        HttpClient httpClient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost("http://10.0.2.2/shareity/paypal.php/");

        try {
            HttpEntity httpEntity = new StringEntity(js);
            httpPost.setEntity(httpEntity);
            httpClient.execute(httpPost);
            //String t = httpPost.toString();
            Log.i(TAG, "Testiing");
            Log.i(TAG, js);


        }
        catch (IOException e) {
        }

        return null;
    }
}

2 个答案:

答案 0 :(得分:1)

现在,请访问它,

HttpEntity httpEntity = new StringEntity(params[0]);

您已将String js传递给AsyncTask,

new sendData().execute(js);

您可以使用params参数在doInBackground(String... params)中访问此参数。所以它应该是params[0]

答案 1 :(得分:1)

这是因为doInBackground方法需要任意数量的字符串。

像这样更改你的doInBackround:

@Override
protected Void doInBackground(String... params) {
    String js = params[0]; // The params is an array of strings :)
    // Your code here
}

有关任意数量参数的详细信息,请参阅:http://docs.oracle.com/javase/tutorial/java/javaOO/arguments.html