无法在android

时间:2016-12-21 11:33:46

标签: android

public class MainActivity extends AppCompatActivity implements FragmentDrawer.FragmentDrawerListener, View.OnClickListener {
    SoapSerializationEnvelope envelope;
    private static String TAG = MainActivity.class.getSimpleName();
    TextView textView, textView9, amount;
    private Toolbar mToolbar;
    private FragmentDrawer drawerFragment;
    JSONArray _jarray;
    JSONObject _jobject;
    String userBalance;
    TextView amountTextView;
    Button addamount;
    String userId;
    String password;
    String paymentMode;
    String txnId;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        amountTextView = (TextView) findViewById(R.id.amount);
        mToolbar = (Toolbar) findViewById(R.id.toolbar);
        textView9 = (TextView) findViewById(R.id.textView9);

        addamount = (Button) findViewById(R.id.addamount);
        addamount.setOnClickListener(this);
        String rupee = MainActivity.this.getResources().getString(R.string.Rs);
        setSupportActionBar(mToolbar);
        getSupportActionBar().setDisplayShowHomeEnabled(true);
        textView = (TextView) findViewById(R.id.amount);
        textView.setText("0" + rupee);
        drawerFragment = (FragmentDrawer)
                getSupportFragmentManager().findFragmentById(R.id.fragment_navigation_drawer);
        drawerFragment.setUp(R.id.fragment_navigation_drawer, (DrawerLayout) findViewById(R.id.drawer_layout), mToolbar);
        drawerFragment.setDrawerListener(this);
        SharedPreferences prefs = getSharedPreferences(
                AppConstants.LOGIN_PREFS, Context.MODE_PRIVATE);

        userId = prefs.getString(AppConstant.USER_ID, "");
        password = prefs.getString(AppConstant.USER_PASSWORD, "");


        if (userId.equals("")) {
            amountTextView.setVisibility(View.GONE);
            textView9.setVisibility(View.GONE);
            addamount.setVisibility(View.GONE);
        } else {
            amountTextView.setVisibility(View.VISIBLE);
            textView9.setVisibility(View.VISIBLE);
            addamount.setVisibility(View.VISIBLE);
        }
        displayView(0);


    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();


        return super.onOptionsItemSelected(item);
    }




    @Override
    public void onDrawerItemSelected(View view, int position) {
        displayView(position);
    }

    private void displayView(int position) {
        Fragment fragment = null;
        String title = getString(R.string.app_name);
        switch (position) {
            case 0:
                fragment = new HomeFragment();
                title = getString(R.string.title_home);
                break;

            case 1:
                fragment = new MyProfiel();
                title = "My Profile";
                break;

            case 2:
                fragment = new RechargeHistoryFragment();
                title = "Recharge History";
                break;

            case 3:
                fragment = new MyWallet();
                title = "My Wallet";

                break;

            case 4:
                fragment = new FundTransfer();
                title = "Fund Transfer";

                break;

            case 5:
                fragment = new MyCoupan();
                title = "My Coupan";
                break;
            case 6:
                fragment = new SaerchApp();
                title = "Search Transcation";
                break;

            case 7:


                fragment = new ConcatUs();
                title = "Contact Us";
                break;
            case 8:
                LogoutAlert();
                break;
            default:
                break;
        }

        if (fragment != null) {
            FragmentManager fragmentManager = getSupportFragmentManager();
            FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
            fragmentTransaction.replace(R.id.container_body, fragment);
            fragmentTransaction.commit();

            // set the toolbar title
            getSupportActionBar().setTitle(title);
        }
    }



    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.addamount) {
            Intent myintent = new Intent(MainActivity.this, PayUActvity.class);
            startActivity(myintent);
        }
    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);


        if (requestCode == 1) {
            if (resultCode == Activity.RESULT_OK) {
                paymentMode = data.getStringExtra("PAYMENT_MODE");
                txnId = data.getStringExtra("PAYMENT_TRANSCATIONID");
                Toast.makeText(MainActivity.this, "You have Sucess Payment", Toast.LENGTH_SHORT).show();
            }
            if (resultCode == Activity.RESULT_CANCELED) {
                Toast.makeText(MainActivity.this, "You have Cancelled Payment", Toast.LENGTH_SHORT).show();
            }
        }
    }




}

这是我的活动

public class PayUActvity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        webView = new WebView(this);
        setContentView(webView);

        JSONObject productInfoObj = new JSONObject();
        JSONArray productPartsArr = new JSONArray();
        JSONObject productPartsObj1 = new JSONObject();
        JSONObject paymentIdenfierParent = new JSONObject();
        JSONArray paymentIdentifiersArr = new JSONArray();
        JSONObject paymentPartsObj1 = new JSONObject();
        JSONObject paymentPartsObj2 = new JSONObject();
        try {
            // Payment Parts
            productPartsObj1.put("name", "abc");
            productPartsObj1.put("description", "abcd");
            productPartsObj1.put("value", "1000");
            productPartsObj1.put("isRequired", "true");
            productPartsObj1.put("settlementEvent", "EmailConfirmation");
            productPartsArr.put(productPartsObj1);
            productInfoObj.put("paymentParts", productPartsArr);
            paymentPartsObj1.put("field", "CompletionDate");
            paymentPartsObj1.put("value", "31/10/2012");
            paymentIdentifiersArr.put(paymentPartsObj1);
            paymentPartsObj2.put("field", "TxnId");
            paymentPartsObj2.put("value", txnid);
            paymentIdentifiersArr.put(paymentPartsObj2);
            paymentIdenfierParent.put("paymentIdentifiers",
                    paymentIdentifiersArr);
            productInfoObj.put("", paymentIdenfierParent);
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        productInfo = productInfoObj.toString();
        Log.e("TAG", productInfoObj.toString());
        Random rand = new Random();
        String rndm = Integer.toString(rand.nextInt())
                + (System.currentTimeMillis() / 1000L);
        txnid = hashCal("SHA-256", rndm).substring(0, 20);
        hash = hashCal("SHA-512", merchant_key + "|" + txnid + "|" + amount
                + "|" + productInfo + "|" + frstName + "|" + emailId
                + "|||||||||||" + salt);

        action1 = base_url.concat("/_payment");

        webView.setWebViewClient(new WebViewClient() {

            @Override
            public void onReceivedError(WebView view, int errorCode,
                                        String description, String failingUrl) {
                // TODO Auto-generated method stub
            }

            @Override
            public void onReceivedSslError(WebView view,
                                           SslErrorHandler handler, SslError error) {
                // TODO Auto-generated method stub

            }

            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                if (url.equals(SUCCESS_URL)) {

                } else {


                }
                return super.shouldOverrideUrlLoading(view, url);
            }


            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                super.onPageStarted(view, url, favicon);
                if (url.equals(SUCCESS_URL)) {


                    Intent resultIntent = new Intent();
                    resultIntent.putExtra("PAYMENT_MODE", "OnlinePayment");
                    resultIntent.putExtra("PAYMENT_TRANSCATIONID", txnid);

                    setResult(RESULT_OK, resultIntent);
                    finish();
                } else {
                }
            }

            //
            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);

            }
        });

        webView.setVisibility(View.VISIBLE);
        webView.getSettings().setBuiltInZoomControls(true);
        webView.getSettings().setCacheMode(2);
        webView.getSettings().setDomStorageEnabled(true);
        webView.clearHistory();
        webView.clearCache(true);
        webView.getSettings().setJavaScriptEnabled(true);
        webView.getSettings().setSupportZoom(true);
        webView.getSettings().setUseWideViewPort(false);
        webView.getSettings().setLoadWithOverviewMode(false);

        webView.addJavascriptInterface(new PayUJavaScriptInterface(PayUActvity.this),
                "PayUMoney");
        Map<String, String> mapParams = new HashMap<String, String>();
        mapParams.put("key", merchant_key);
        mapParams.put("hash", hash);
        mapParams.put("txnid", txnid);
        mapParams.put("service_provider", "payu_paisa");
        mapParams.put("amount", amount);
        mapParams.put("firstname", frstName);
        mapParams.put("email", emailId);
        mapParams.put("phone", "8130513899");
        mapParams.put("productinfo", productInfo);
        mapParams.put("surl", SUCCESS_URL);
        mapParams.put("furl", FAILED_URL);
        webview_ClientPost(webView, action1, mapParams.entrySet());

    }

    public class PayUJavaScriptInterface {
        Context mContext;

        /**
         * Instantiate the interface and set the context
         */
        PayUJavaScriptInterface(Context c) {
            mContext = c;
        }

        public void success(long id, final String paymentId) {

            mHandler.post(new Runnable() {

                public void run() {
                    mHandler = null;

//                    Toast.makeText(PayUActvity.this, paymentId, Toast.LENGTH_LONG).show();


                }
            });
        }
    }

    public void webview_ClientPost(WebView webView, String url,
                                   Collection<Map.Entry<String, String>> postData) {
        StringBuilder sb = new StringBuilder();

        sb.append("<html><head></head>");
        sb.append("<body onload='form1.submit()'>");
        sb.append(String.format("<form id='form1' action='%s' method='%s'>",
                url, "post"));
        for (Map.Entry<String, String> item : postData) {
            sb.append(String.format(
                    "<input name='%s' type='hidden' value='%s' />",
                    item.getKey(), item.getValue()));
        }
        sb.append("</form></body></html>");
        Log.d("Tag", "webview_ClientPost called");
        webView.loadData(sb.toString(), "text/html", "utf-8");
    }


    public String hashCal(String type, String str) {
        byte[] hashseq = str.getBytes();
        StringBuffer hexString = new StringBuffer();
        try {
            MessageDigest algorithm = MessageDigest.getInstance(type);
            algorithm.reset();
            algorithm.update(hashseq);
            byte messageDigest[] = algorithm.digest();

            for (int i = 0; i < messageDigest.length; i++) {
                String hex = Integer.toHexString(0xFF & messageDigest[i]);
                if (hex.length() == 1)
                    hexString.append("0");
                hexString.append(hex);
            }
        } catch (NoSuchAlgorithmException nsae) {
        }
        return hexString.toString();

    }



}

这是付款成功后我的Pay类获得transactionId并且我正在完成它并且回到之前的行为我已经将代码onActvityResult编写为ge Transaction Value但是当我执行时我没有在MainActvity中回调我不知道在哪里我做错了请告诉我哪里做错了。

2 个答案:

答案 0 :(得分:3)

您需要致电startActivityForResult(myintent,1)onActivityResult只会在您使用startActivityForResult时被调用

  @Override
    public void onClick(View v) {
        if (v.getId() == R.id.addamount) {
            Intent myintent = new Intent(MainActivity.this, PayUActvity.class);
            // startActivity(myintent);
            // ^^^ remove this instead use the below call
            startActivityForResult(myintent,1);
        }
    }

答案 1 :(得分:0)

嘿,使用它来获取活动的结果。

Use startActivityForResult(intent,requestcode);

在ActivityResult上检查请求代码,您正在调整的结果来自被调用的意图