Payumoney Integration Error - android

In this code when I run it is redirecting to payu and displaying Some error Occurred message
public class PayMentGateWay extends ActionBarActivity {
/**
* Adding WebView as setContentView
*/
WebView webView;
/**
* Context for Activity
*/
Context activity;
/**
* Order Id
* To Request for Updating Payment Status if Payment Successfully Done
*/
int mId; //Getting from Previous Activity
/**
* Required Fields
*/
// Test Variables
/*
private String mMerchantKey = "FCyqqZ";
private String mSalt = "sfBpGA8E";
private String mBaseURL = "https://test.payu.in";
*/
// Final Variables
private String mMerchantKey = "9HwJ5t";
private String mSalt = "2JIfn3ez";
private String mBaseURL = "https://test.payu.in";
private String mAction = ""; // For Final URL
private String mTXNId; // This will create below randomly
private String mHash; // This will create below randomly
private String mProductInfo = "Recharge"; //Passing String only
private String mFirstName; // From Previous Activity
private String mEmailId; // From Previous Activity
private double mAmount; // From Previous Activity
private String mPhone; // From Previous Activity
private String mServiceProvider = "payu_paisa";
private String mSuccessUrl = "www.google.com";
private String mFailedUrl = "www.facebook.com";
boolean isFromOrder;
/**
* Handler
*/
Handler mHandler = new Handler();
/**
* #param savedInstanceState
*/
#SuppressLint({"AddJavascriptInterface", "SetJavaScriptEnabled", "JavascriptInterface"})
#Override
protected void onCreate(Bundle savedInstanceState) {
getWindow().requestFeature(Window.FEATURE_PROGRESS);
super.onCreate(savedInstanceState);
/**
* Setting WebView to Screen
*/
setContentView(R.layout.webview);
/**
* Creating WebView
*/
webView = (WebView) findViewById(R.id.webview);
/**
* Context Variable
*/
activity = getApplicationContext();
/**
* Actionbar Settings
*/
/*Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
ActionBar ab = getSupportActionBar();
ab.setDisplayHomeAsUpEnabled(true);
// enabling action bar app icon and behaving it as toggle button
ab.setHomeButtonEnabled(true);
ab.setTitle(getString(R.string.paymentgateway));*/
/**
* Getting Intent Variables...
*/
Bundle bundle = getIntent().getExtras();
if (bundle != null) {
mFirstName = bundle.getString("name");
mEmailId = bundle.getString("email");
mAmount = bundle.getInt("amount");
mPhone = bundle.getString("phone");
mId = bundle.getInt("id");
isFromOrder = bundle.getBoolean("isFromOrder");
/**
* Creating Transaction Id
*/
Random rand = new Random();
String randomString = Integer.toString(rand.nextInt()) + (System.currentTimeMillis() / 1000L);
mTXNId = hashCal("SHA-256", randomString).substring(0, 20);
//mAmount = new BigDecimal(mAmount).setScale(0, RoundingMode.UP).intValue();
/**
* Creating Hash Key
*/
mHash = hashCal("SHA-512", mMerchantKey + "|" +
mTXNId + "|" +
mAmount + "|" +
mProductInfo + "|" +
mFirstName + "|" +
mEmailId + "|||||||||||" +
mSalt);
/**
* Final Action URL...
*/
mAction = mBaseURL.concat("/_payment");
/**
* WebView Client
*/
webView.setWebViewClient(new WebViewClient() {
#Override
public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
super.onReceivedError(view, request, error);
Toast.makeText(activity, "Oh no! " + error, Toast.LENGTH_SHORT).show();
}
#Override
public void onReceivedSslError(WebView view,
SslErrorHandler handler, SslError error) {
Toast.makeText(activity, "SSL Error! " + error, Toast.LENGTH_SHORT).show();
handler.proceed();
}
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
return super.shouldOverrideUrlLoading(view, url);
}
#Override
public void onPageFinished(WebView view, String url) {
if (url.equals(mSuccessUrl)) {
Intent intent = new Intent(PayMentGateWay.this, MainActivity.class);
intent.putExtra("status", true);
intent.putExtra("transaction_id", mTXNId);
intent.putExtra("id", mId);
intent.putExtra("isFromOrder", isFromOrder);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
} else if (url.equals(mFailedUrl)) {
Intent intent = new Intent(PayMentGateWay.this, MainActivity.class);
intent.putExtra("status", false);
intent.putExtra("transaction_id", mTXNId);
intent.putExtra("id", mId);
intent.putExtra("isFromOrder", isFromOrder);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
}
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(PayMentGateWay.this), "PayUMoney");
/**
* Mapping Compulsory Key Value Pairs
*/
Map<String, String> mapParams = new HashMap<>();
mapParams.put("key", mMerchantKey);
mapParams.put("txnid", mTXNId);
mapParams.put("amount", String.valueOf(mAmount));
mapParams.put("productinfo", mProductInfo);
mapParams.put("firstname", mFirstName);
mapParams.put("email", mEmailId);
mapParams.put("phone", mPhone);
mapParams.put("surl", mSuccessUrl);
mapParams.put("furl", mFailedUrl);
mapParams.put("hash", mHash);
mapParams.put("service_provider", mServiceProvider);
String postData = "hash="+ mHash + "&key="+ mMerchantKey+"&txnid=01237&amount=10&productinfo=p111&firstname=navraj&email=navraj#navraj.net&" + "phone=9991940305&salt="+ mSalt+"&surl="+"www.facebook.com"+"&furl="+"www.google.com";
// webView.postUrl(mAction, EncodingUtils.getBytes(postData, "base64"));
// In case of using PayU PG //url = payuConfig.getEnvironment() == PayuConstants.PRODUCTION_ENV? PayuConstants.PRODUCTION_PAYMENT_URL : //PayuConstants.MOBILE_TEST_PAYMENT_URL ; //webView.postUrl(url, EncodingUtils.getBytes(payuConfig.getData(), "base64"));
webViewClientPost(webView, mAction, mapParams.entrySet());
} else {
Toast.makeText(activity, "Something went wrong, Try again.", Toast.LENGTH_LONG).show();
}
}
/**
* Posting Data on PayUMoney Site with Form
*
* #param webView
* #param url
* #param postData
*/
public void webViewClientPost(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", "webViewClientPost called: " + sb.toString());
webView.loadData(sb.toString(), "text/html", "utf-8");
}
/**
* Hash Key Calculation
*
* #param type
* #param str
* #return
*/
public String hashCal(String type, String str) {
byte[] hashSequence = str.getBytes();
StringBuffer hexString = new StringBuffer();
try {
MessageDigest algorithm = MessageDigest.getInstance(type);
algorithm.reset();
algorithm.update(hashSequence);
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();
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if(item.getItemId() == android.R.id.home) {
onPressingBack();
}
return super.onOptionsItemSelected(item);
}
#Override
public void onBackPressed() {
onPressingBack();
}
/**
* On Pressing Back
* Giving Alert...
*/
private void onPressingBack() {
final Intent intent;
if(isFromOrder)
intent = new Intent(PayMentGateWay.this, MainActivity.class);
else
intent = new Intent(PayMentGateWay.this, MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
AlertDialog.Builder alertDialog = new AlertDialog.Builder(PayMentGateWay.this);
// Setting Dialog Title
alertDialog.setTitle("Warning");
// Setting Dialog Message
alertDialog.setMessage("Do you cancel this transaction?");
// On pressing Settings button
alertDialog.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
finish();
startActivity(intent);
}
});
// on pressing cancel button
alertDialog.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
// Showing Alert Message
alertDialog.show();
}
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(PayMentGateWay.this, "Payment Successfully.", Toast.LENGTH_SHORT).show();
}
});
}
}
}

Related

PayUmoney seamless Integration

experts
can you help me in seemless integration with PayUmoney payment Gateway in android
also if you have any sample of seemless integration please share
i have tried like this but showing me error of Marchentkey and salt is incorrect but i copied both from my account
below is code detail
MainActivity extends AppCompatActivity {
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Payu.setInstance(this);
proceedtopay();
}
public void proceedtopay(){
PaymentParams mPaymentParams = new PaymentParams();
String merchant_key="rjQUPktU"; // test gtkFFx XmOFYRT3
String salt="e5iIg1jwi8"; // test eCwWELxi aTZEImxcYO
mPaymentParams.setKey(merchant_key);
mPaymentParams.setAmount("15.0");
mPaymentParams.setProductInfo("Tshirt");
mPaymentParams.setFirstName("Waseem");
mPaymentParams.setEmail("waseemahmad241#gmail.com");
mPaymentParams.setTxnId("0123479543689");
mPaymentParams.setSurl("https://www.payumoney.com/mobileapp/payumoney/success.php");
mPaymentParams.setFurl("https://www.payumoney.com/mobileapp/payumoney/failure.php");
mPaymentParams.setUdf1("udf1l");
mPaymentParams.setUdf2("udf2");
mPaymentParams.setUdf3("udf3");
mPaymentParams.setUdf4("udf4");
mPaymentParams.setUdf5("udf5");
String hashSequence = merchant_key+"|0123479543689|15.0|productinfo|Waseem|waseemahmad241#gmail.com|udf1|udf2|udf3|udf4|udf5||||||"+salt;
String serverCalculatedHash= hashCal("SHA-512", hashSequence);
mPaymentParams.setHash(serverCalculatedHash);
mPaymentParams.setCardNumber("4012001037141112");
mPaymentParams.setCardName("test");
mPaymentParams.setNameOnCard("test");
mPaymentParams.setExpiryMonth("05");// MM
mPaymentParams.setExpiryYear("2020");// YYYY
mPaymentParams.setCvv("123");
mPaymentParams.setEnableOneClickPayment(1);
PostData postData = null;
try {
postData = new PaymentPostParams(mPaymentParams, PayuConstants.CC).getPaymentPostParams();
} catch (Exception e) {
e.printStackTrace();
}
if (postData.getCode() == PayuErrors.NO_ERROR) {
// launch webview
PayuConfig payuConfig = new PayuConfig();
payuConfig.setEnvironment(PayuConstants.STAGING_ENV);
payuConfig.setData(postData.getResult());
Intent intent = new Intent(this,PaymentsActivity.class);
intent.putExtra(PayuConstants.PAYU_CONFIG,payuConfig);
startActivityForResult(intent, PayuConstants.PAYU_REQUEST_CODE);
} else {
// something went wrong
Toast.makeText(this,postData.getResult(), Toast.LENGTH_LONG).show();
}
}
public static String hashCal(String type, String hashString) {
StringBuilder hash = new StringBuilder();
MessageDigest messageDigest = null;
try {
messageDigest = MessageDigest.getInstance(type);
messageDigest.update(hashString.getBytes());
byte[] mdbytes = messageDigest.digest();
for (byte hashByte : mdbytes) {
hash.append(Integer.toString((hashByte & 0xff) + 0x100, 16).substring(1));
}
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
return hash.toString();
}
and MyWebview Activity is
PaymentsActivity extends AppCompatActivity {
//String base_url="https://test.payumoney.in/_payment";
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.web_view);
Bundle bundle =getIntent().getExtras();
PayuConfig payuConfig =bundle.getParcelable(PayuConstants.PAYU_CONFIG);
WebView mWebView =(WebView) findViewById(R.id.webview);
// String url =//payuConfig.getEnvironment() == PayuConstants.PRODUCTION_ENV ? PayuConstants.PRODUCTION_PAYMENT_URL :PayuConstants.MOBILE_TEST_PAYMENT_URL;
byte[] encodedData = EncodingUtils.getBytes(payuConfig.getData(), "base64");
mWebView.postUrl(PayuConstants.TEST_PAYMENT_URL,encodedData);
mWebView.getSettings().setSupportMultipleWindows(true);
mWebView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
mWebView.getSettings().setJavaScriptEnabled(true);
mWebView.getSettings().setDomStorageEnabled(true);
mWebView.setWebChromeClient(new WebChromeClient() {});
mWebView.setWebViewClient(new WebViewClient() {});
#SuppressLint("SetJavaScriptEnabled")
public class Payment extends AppCompatActivity {
WebView webView;
Context activity;
int mId;
/*private String mMerchantKey ="your marchant key"
private String mSalt = "your salt key"*/
private String mBaseURL = "https://test.payu.in";
private String mAction = ""; // For Final URL
private String mTXNId; // This will create below randomly
private String mHash; // This will create below randomly
private String mProductInfo = "product name"; //Passing String only
private String mFirstName; // From Previous Activity
private String mEmailId; // From Previous Activity
private double mAmount; // From Previous Activity
private String mPhone; // From Previous Activity
private String mServiceProvider = "";// "payu_paisa";
private String mSuccessUrl = "success url";
private String mFailedUrl = "failure url";
String MAM_ID = "mem_id";
String EMAIL = "email";
String ADD1 = "address_line1";
String ADD2 = "address_line2";
String REGION_ID = "region_id";
String CITY_ID = "city_id";
String PROMOCODE = "promocode";
String PIN_CODE = "pin_code";
String ADD_DATE = "add_date";
String PRICE = "price";
String CARD_DISCOUNT = "card_discount";
String PROMOCODE_DISCOUNT = "promocode_discount";
String TXNID = "tnx_id";
String DEVICE_ID = "device_id";
String PRODUCT_ID = "product_id";
boolean isFromOrder;
/*
Handler
*/
Handler mHandler = new Handler();
Bundle bundle;
SharedPreferences spfs;
/**
* ATTENTION: This was auto-generated to implement the App Indexing API.
* See https://g.co/AppIndexing/AndroidStudio for more information.
*/
private GoogleApiClient client;
/**
* #param savedInstanceState
*/
#SuppressLint({"AddJavascriptInterface", "SetJavaScriptEnabled", "JavascriptInterface"})
#Override
protected void onCreate(Bundle savedInstanceState) {
getWindow().requestFeature(Window.FEATURE_PROGRESS);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_webview_for_payumoney);
spfs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
webView = (WebView) findViewById(R.id.payumoney_webview);
activity = getApplicationContext();
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
ActionBar ab = getSupportActionBar();
ab.setDisplayHomeAsUpEnabled(true);
// enabling action bar app icon and behaving it as toggle button
ab.setHomeButtonEnabled(true);
ab.setTitle("Payment Gateaway");
bundle = getIntent().getExtras();
if (bundle != null) {
Log.e("Bndle Data:- ", bundle.toString());
mFirstName = bundle.getString("Name");//NAME
mEmailId = bundle.getString("Email");// lOGIN IN PAYUMONEY ID
mAmount = 1.0;//bundle.getDouble("Price");// AMOUNT
mPhone = bundle.getString("Mobile"); // MOBILE ! REQUIRED
mId = 1;//bundle.getInt("id");
isFromOrder = true;// bundle.getBoolean("isFromOrder");
Log.e("Tag payment ", "" + mFirstName + " : " + mEmailId + " : " + mAmount + " : " + mPhone);
Random rand = new Random();
String randomString = Integer.toString(rand.nextInt()) + (System.currentTimeMillis() / 1000L);
mTXNId = hashCal("SHA-256", randomString).substring(0, 20);
mAmount = new BigDecimal(mAmount).setScale(0, RoundingMode.UP).intValue();
mHash = hashCal("SHA-512", mMerchantKey + "|" +
mTXNId + "|" +
mAmount + "|" +
mProductInfo + "|" +
mFirstName + "|" +
mEmailId + "|||||||||||" +
mSalt);
mAction = mBaseURL.concat("/_payment");
try {
Class.forName("com.payu.custombrowser.Bank");
} catch (Exception e) {
}
webView.setWebViewClient(new WebViewClient() {
#SuppressWarnings("deprecation")
#Override
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
// Handle the error
Log.e("WEB_VIEW_TEST", "error code:" + errorCode);
super.onReceivedError(view, errorCode, description, failingUrl);
}
#TargetApi(Build.VERSION_CODES.M)
#Override
public void onReceivedError(WebView view, WebResourceRequest req, WebResourceError rerr) {
// Redirect to deprecated method, so you can use it in all SDK versions
onReceivedError(view, rerr.getErrorCode(), rerr.getDescription().toString(), req.getUrl().toString());
Log.e("onReceivedError", "error code:" + rerr);
Toast.makeText(activity, "Oh no! " + rerr.getDescription().toString(), Toast.LENGTH_SHORT).show();
}
/*#Override
public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
super.onReceivedError(view, request, error);
Toast.makeText(activity, "Oh no! " + error, Toast.LENGTH_SHORT).show();
}*/
#Override
public void onReceivedSslError(WebView view,
SslErrorHandler handler, SslError error) {
Toast.makeText(activity, "SSL Error! " + error, Toast.LENGTH_SHORT).show();
handler.proceed();
}
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
return super.shouldOverrideUrlLoading(view, url);
}
#Override
public void onPageFinished(WebView view, String url) {
if (url.equals(mSuccessUrl)) {
RecepetUpload();
} else if (url.equals(mFailedUrl)) {
Log.e("Payment STatus", "failure");
Custom_Toast.show(getApplication(), "Payment Transcation Failed");
Intent intent = new Intent(Payment.this, MainActivity.class);
intent.putExtra("status", false);
intent.putExtra("transaction_id", mTXNId);
intent.putExtra("id", mId);
intent.putExtra("isFromOrder", isFromOrder);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
}
super.onPageFinished(view, url);
}
});
webView.setVisibility(View.VISIBLE);
webView.getSettings().setBuiltInZoomControls(true);
webView.getSettings().setCacheMode(2);
webView.getSettings().setDomStorageEnabled(true);
webView.clearHistory();
webView.getSettings().setDefaultZoom(WebSettings.ZoomDensity.FAR);
webView.getSettings().setLoadWithOverviewMode(true);
webView.getSettings().setUseWideViewPort(true);
webView.clearCache(true);
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setSupportZoom(true);
webView.getSettings().setUserAgentString("Mozilla/5.0 (iPhone; U; CPU like Mac OS X; en) AppleWebKit/420+ (KHTML, like Gecko) Version/3.0 Mobile/1A543a Safari/419.3");
webView.setInitialScale(1);
webView.addJavascriptInterface(new PayUJavaScriptInterface(Payment.this), "PayUMoney");
/**
* Mapping Compulsory Key Value Pairs
*/
Map<String, String> mapParams = new HashMap<>();
mapParams.put("key", mMerchantKey);
mapParams.put("txnid", mTXNId);
mapParams.put("amount", String.valueOf(mAmount));
mapParams.put("productinfo", mProductInfo);
mapParams.put("firstname", mFirstName);
mapParams.put("email", mEmailId);
mapParams.put("phone", mPhone);
mapParams.put("surl", mSuccessUrl);
mapParams.put("furl", mFailedUrl);
mapParams.put("hash", mHash);
mapParams.put("service_provider", mServiceProvider);
Log.e("Url WEb View", mAction);
webViewClientPost(webView, mAction, mapParams.entrySet());
} else {
Toast.makeText(activity, "Something went wrong, Try again.", Toast.LENGTH_LONG).show();
}
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();
}
/**
* Posting Data on PayUMoney Site with Form
*
* #param webView
* #param url
* #param postData
*/
public void webViewClientPost(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", "webViewClientPost called: " + sb.toString());
webView.loadData(sb.toString(), "text/html", "utf-8");
}
/**
* Hash Key Calculation
*
* #param type
* #param str
* #return
*/
public String hashCal(String type, String str) {
byte[] hashSequence = str.getBytes();
StringBuffer hexString = new StringBuffer();
try {
MessageDigest algorithm = MessageDigest.getInstance(type);
algorithm.reset();
algorithm.update(hashSequence);
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) {
}
Log.e("Hex String", "" + hexString);
return hexString.toString();
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == android.R.id.home) {
onPressingBack();
}
return super.onOptionsItemSelected(item);
}
#Override
public void onBackPressed() {
onPressingBack();
}
/**
* On Pressing Back
* Giving Alert...
*/
private void onPressingBack() {
final Intent intent;
if (isFromOrder)
intent = new Intent(Payment.this, MainActivity.class);
else
intent = new Intent(Payment.this, MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
AlertDialog.Builder alertDialog = new AlertDialog.Builder(Payment.this);
// Setting Dialog Title
alertDialog.setTitle("Warning");
// Setting Dialog Message
alertDialog.setMessage("Do you cancel this transaction?");
// On pressing Settings button
alertDialog.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
finish();
startActivity(intent);
}
});
// on pressing cancel button
alertDialog.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
// Showing Alert Message
alertDialog.show();
}
#Override
public void onStart() {
super.onStart();
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
client.connect();
Action viewAction = Action.newAction(
Action.TYPE_VIEW, // TODO: choose an action type.
"Payment Page", // TODO: Define a title for the content shown.
// TODO: If you have web page content that matches this app activity's content,
// make sure this auto-generated web page URL is correct.
// Otherwise, set the URL to null.
Uri.parse("http://https://secure.payu.in"),
// TODO: Make sure this auto-generated app URL is correct.
Uri.parse("android-app://com.local/https/https://secure.payu.in")
);
AppIndex.AppIndexApi.start(client, viewAction);
}
#Override
public void onStop() {
super.onStop();
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
Action viewAction = Action.newAction(
Action.TYPE_VIEW, // TODO: choose an action type.
"Payment Page", // TODO: Define a title for the content shown.
// TODO: If you have web page content that matches this app activity's content,
// make sure this auto-generated web page URL is correct.
// Otherwise, set the URL to null.
Uri.parse("http://https://secure.payu.in"),
// TODO: Make sure this auto-generated app URL is correct.
Uri.parse("android-app://com.local/https/https://secure.payu.in")
);
AppIndex.AppIndexApi.end(client, viewAction);
client.disconnect();
}
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(Payment.this, "Payment Successfully.", Toast.LENGTH_SHORT).show();
}
});
}
}
private void RecepetUpload() {
final ProgressDialog progDialog;
progDialog = ProgressDialog.show(Payment.this, "", "waiting");
try {
if (!progDialog.isShowing()) {
progDialog.show();
}
StringRequest postRequest = new StringRequest(Request.Method.POST,
"http://www.local.com/club-app/api-order-details", new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.e("Payment Status:--", "Success , " + mTXNId);
Custom_Toast.show(getApplication(), "Payment Transcation Success");
Intent intent = new Intent(Payment.this, MainActivity.class);
intent.putExtra("status", true);
intent.putExtra("transaction_id", mTXNId);
intent.putExtra("id", mId);
intent.putExtra("isFromOrder", isFromOrder);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
try {
if (progDialog.isShowing()) {
progDialog.dismiss();
}
Log.e("res Payment", "" + response);
} catch (Exception e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
if (progDialog.isShowing()) {
progDialog.dismiss();
}
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<>();
params.put(MAM_ID, "" + spfs.getString("mem_id", ""));
params.put(EMAIL, "" + mEmailId);
params.put(ADD1, "" + bundle.getString(ADD1));
params.put(ADD2, "" + bundle.getString(ADD2));
params.put(REGION_ID, "" + bundle.getString(REGION_ID));
params.put(CITY_ID, "" + bundle.getString(CITY_ID));
params.put(PIN_CODE, "" + bundle.getString(PIN_CODE));
params.put(ADD_DATE, "" + bundle.getString(ADD_DATE));
params.put(PRICE, "" + mAmount);
params.put(CARD_DISCOUNT, "" + bundle.getString(CARD_DISCOUNT));
params.put(PROMOCODE_DISCOUNT, "" + bundle.getString(PROMOCODE_DISCOUNT));
params.put(PROMOCODE, "" + bundle.getString(PROMOCODE));
params.put(TXNID, "" + mTXNId);
params.put(DEVICE_ID, "" + Settings.Secure.getString(getApplicationContext().getContentResolver(),
Settings.Secure.ANDROID_ID));
params.put(PRODUCT_ID, "" + bundle.getString(PRODUCT_ID));
Log.e("Bndle Params:- ", params.toString());
return params;
}
};
int socketTimeout = 60000;// 30 seconds - change to what you want
RetryPolicy policy = new DefaultRetryPolicy(socketTimeout,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
postRequest.setRetryPolicy(policy);
Volley.newRequestQueue(this).add(postRequest);
} catch (Exception e) {
if (progDialog.isShowing()) {
progDialog.dismiss();
}
Log.e("", " Exception Occurs - " + e);
}
}
}

How to insert to db in payumoney android integration?

This is my code :
public class PayUMoneyActivity extends AppCompatActivity {
/**
* Adding WebView as setContentView
*/
WebView webView;
/**
* Context for Activity
*/
Context activity;
/**
* Order Id
* To Request for Updating Payment Status if Payment Successfully Done
*/
int mId; //Getting from Previous Activity
/**
* Required Fields
*/
// Test Variables
/*
private String mMerchantKey = "FCyqqZ";
private String mSalt = "sfBpGA8E";
private String mBaseURL = "https://test.payu.in";
*/
// Final Variables
private String mMerchantKey = "Your Merchant Key";
private String mSalt = "Salt";
private String mBaseURL = "https://secure.payu.in";
private String mAction = ""; // For Final URL
private String mTXNId; // This will create below randomly
private String mHash; // This will create below randomly
private String mProductInfo = "Food Items"; //Passing String only
private String mFirstName; // From Previous Activity
private String mEmailId; // From Previous Activity
private double mAmount; // From Previous Activity
private String mPhone; // From Previous Activity
private String mServiceProvider = "payu_paisa";
private String mSuccessUrl = "your success URL";
private String mFailedUrl = "Your Failure URL";
boolean isFromOrder;
/**
* Handler
*/
Handler mHandler = new Handler();
/**
* #param savedInstanceState
*/
#SuppressLint({"AddJavascriptInterface", "SetJavaScriptEnabled"})
#Override
protected void onCreate(Bundle savedInstanceState) {
getWindow().requestFeature(Window.FEATURE_PROGRESS);
super.onCreate(savedInstanceState);
/**
* Setting WebView to Screen
*/
setContentView(R.layout.activity_webview_for_payumoney);
/**
* Creating WebView
*/
webView = (WebView) findViewById(R.id.payumoney_webview);
/**
* Context Variable
*/
activity = getApplicationContext();
/**
* Actionbar Settings
*/
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
ActionBar ab = getSupportActionBar();
ab.setDisplayHomeAsUpEnabled(true);
// enabling action bar app icon and behaving it as toggle button
ab.setHomeButtonEnabled(true);
ab.setTitle(getString(R.string.title_activity_online_payment));
/**
* Getting Intent Variables...
*/
Bundle bundle = getIntent().getExtras();
if (bundle != null) {
mFirstName = bundle.getString("name");
mEmailId = bundle.getString("email");
mAmount = bundle.getDouble("amount");
mPhone = bundle.getString("phone");
mId = bundle.getInt("id");
isFromOrder = bundle.getBoolean("isFromOrder");
Log.i(TAG, "" + mFirstName + " : " + mEmailId + " : " + mAmount + " : " + mPhone);
/**
* Creating Transaction Id
*/
Random rand = new Random();
String randomString = Integer.toString(rand.nextInt()) + (System.currentTimeMillis() / 1000L);
mTXNId = hashCal("SHA-256", randomString).substring(0, 20);
mAmount = new BigDecimal(mAmount).setScale(0, RoundingMode.UP).intValue();
/**
* Creating Hash Key
*/
mHash = hashCal("SHA-512", mMerchantKey + "|" +
mTXNId + "|" +
mAmount + "|" +
mProductInfo + "|" +
mFirstName + "|" +
mEmailId + "|||||||||||" +
mSalt);
/**
* Final Action URL...
*/
mAction = mBaseURL.concat("/_payment");
/**
* WebView Client
*/
webView.setWebViewClient(new WebViewClient() {
#Override
public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
super.onReceivedError(view, request, error);
Toast.makeText(activity, "Oh no! " + error, Toast.LENGTH_SHORT).show();
}
#Override
public void onReceivedSslError(WebView view,
SslErrorHandler handler, SslError error) {
Toast.makeText(activity, "SSL Error! " + error, Toast.LENGTH_SHORT).show();
handler.proceed();
}
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
return super.shouldOverrideUrlLoading(view, url);
}
#Override
public void onPageFinished(WebView view, String url) {
if (url.equals(mSuccessUrl)) {
Intent intent = new Intent(PayUMoneyActivity.this, PaymentStatusActivity.class);
intent.putExtra("status", true);
intent.putExtra("transaction_id", mTXNId);
intent.putExtra("id", mId);
intent.putExtra("isFromOrder", isFromOrder);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
} else if (url.equals(mFailedUrl)) {
Intent intent = new Intent(PayUMoneyActivity.this, PaymentStatusActivity.class);
intent.putExtra("status", false);
intent.putExtra("transaction_id", mTXNId);
intent.putExtra("id", mId);
intent.putExtra("isFromOrder", isFromOrder);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
}
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(PayUMoneyActivity.this), "PayUMoney");
/**
* Mapping Compulsory Key Value Pairs
*/
Map<String, String> mapParams = new HashMap<>();
mapParams.put("key", mMerchantKey);
mapParams.put("txnid", mTXNId);
mapParams.put("amount", String.valueOf(mAmount));
mapParams.put("productinfo", mProductInfo);
mapParams.put("firstname", mFirstName);
mapParams.put("email", mEmailId);
mapParams.put("phone", mPhone);
mapParams.put("surl", mSuccessUrl);
mapParams.put("furl", mFailedUrl);
mapParams.put("hash", mHash);
mapParams.put("service_provider", mServiceProvider);
webViewClientPost(webView, mAction, mapParams.entrySet());
} else {
Toast.makeText(activity, "Something went wrong, Try again.", Toast.LENGTH_LONG).show();
}
}
/**
* Posting Data on PayUMoney Site with Form
*
* #param webView
* #param url
* #param postData
*/
public void webViewClientPost(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", "webViewClientPost called: " + sb.toString());
webView.loadData(sb.toString(), "text/html", "utf-8");
}
/**
* Hash Key Calculation
*
* #param type
* #param str
* #return
*/
public String hashCal(String type, String str) {
byte[] hashSequence = str.getBytes();
StringBuffer hexString = new StringBuffer();
try {
MessageDigest algorithm = MessageDigest.getInstance(type);
algorithm.reset();
algorithm.update(hashSequence);
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();
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if(item.getItemId() == android.R.id.home) {
onPressingBack();
}
return super.onOptionsItemSelected(item);
}
#Override
public void onBackPressed() {
onPressingBack();
}
/**
* On Pressing Back
* Giving Alert...
*/
private void onPressingBack() {
final Intent intent;
if(isFromOrder)
intent = new Intent(PayUMoneyActivity.this, ProductInCartList.class);
else
intent = new Intent(PayUMoneyActivity.this, MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
AlertDialog.Builder alertDialog = new AlertDialog.Builder(PayUMoneyActivity.this);
// Setting Dialog Title
alertDialog.setTitle("Warning");
// Setting Dialog Message
alertDialog.setMessage("Do you cancel this transaction?");
// On pressing Settings button
alertDialog.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
finish();
startActivity(intent);
}
});
// on pressing cancel button
alertDialog.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
// Showing Alert Message
alertDialog.show();
}
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(PayUMoneyActivity.this, "Payment Successfully.", Toast.LENGTH_SHORT).show();
}
});
}
}
}
The function onPageFinished() does not get invoked. The respective intent is not being called, when the payment succeeds. The webview just redirects to the success page. Can anyone help me in resolving this error? I also need to add the bundle variables to the db, on redirecting to success page.

Document Missing - Google Cloud Print

I am trying to use google cloud print with my project on android studio to print out a pdf file. I am storing the file in the assets folder of the project and when I go to print it say "Document Missing". this is my java code:
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void onPrintClick(View v) {
String path = Environment.getExternalStorageDirectory().getAbsolutePath()
+ "/monsoon.pdf";
File file = new File(path);
if (file.exists()) {
Uri uri = Uri.fromFile(file);
Intent printIntent = new Intent(this, PrintDialogActivity.class);
printIntent.setDataAndType(uri, "application/pdf");
printIntent.putExtra("title", "Gaurang");
startActivity(printIntent);
} else {
Toast.makeText(getApplicationContext(), "No file",
Toast.LENGTH_SHORT).show();
}
}
}
and Here is Android Code for Google Cloud Print with some modification on class PrintDialogJavaScriptInterface...ie. applying annotations #JavascriptInterface
public class PrintDialogActivity extends Activity {
private static final String PRINT_DIALOG_URL = "https://www.google.com/cloudprint/dialog.html";
private static final String JS_INTERFACE = "AndroidPrintDialog";
private static final String CONTENT_TRANSFER_ENCODING = "base64";
private static final String ZXING_URL = "http://zxing.appspot.com";
private static final int ZXING_SCAN_REQUEST = 65743;
/**
* Post message that is sent by Print Dialog web page when the printing
* dialog needs to be closed.
*/
private static final String CLOSE_POST_MESSAGE_NAME = "cp-dialog-on-close";
/**
* Web view element to show the printing dialog in.
*/
private WebView dialogWebView;
/**
* Intent that started the action.
*/
Intent cloudPrintIntent;
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.activity_print_dialog);
dialogWebView = (WebView) findViewById(R.id.webview);
cloudPrintIntent = this.getIntent();
WebSettings settings = dialogWebView.getSettings();
settings.setJavaScriptEnabled(true);
dialogWebView.setWebViewClient(new PrintDialogWebClient());
dialogWebView.addJavascriptInterface(
new PrintDialogJavaScriptInterface(), JS_INTERFACE);
dialogWebView.loadUrl(PRINT_DIALOG_URL);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
if (requestCode == ZXING_SCAN_REQUEST && resultCode == RESULT_OK) {
dialogWebView.loadUrl(intent.getStringExtra("SCAN_RESULT"));
}
}
final class PrintDialogJavaScriptInterface {
#JavascriptInterface
public String getType() {
return cloudPrintIntent.getType();
}
#JavascriptInterface
public String getTitle() {
return cloudPrintIntent.getExtras().getString("title");
}
#JavascriptInterface
public String getContent() {
try {
ContentResolver contentResolver = getContentResolver();
InputStream is = contentResolver
.openInputStream(cloudPrintIntent.getData());
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buffer = new byte[4096];
int n = is.read(buffer);
while (n >= 0) {
baos.write(buffer, 0, n);
n = is.read(buffer);
}
is.close();
baos.flush();
return Base64
.encodeToString(baos.toByteArray(), Base64.DEFAULT);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return "";
}
#JavascriptInterface
public String getEncoding() {
return CONTENT_TRANSFER_ENCODING;
}
#JavascriptInterface
public void onPostMessage(String message) {
if (message.startsWith(CLOSE_POST_MESSAGE_NAME)) {
finish();
}
}
}
private final class PrintDialogWebClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (url.startsWith(ZXING_URL)) {
Intent intentScan = new Intent(
"com.google.zxing.client.android.SCAN");
intentScan.putExtra("SCAN_MODE", "QR_CODE_MODE");
try {
startActivityForResult(intentScan, ZXING_SCAN_REQUEST);
} catch (ActivityNotFoundException error) {
view.loadUrl(url);
}
} else {
view.loadUrl(url);
}
return false;
}
#Override
public void onPageFinished(WebView view, String url) {
if (PRINT_DIALOG_URL.equals(url)) {
// Submit print document.
view.loadUrl("javascript:printDialog.setPrintDocument(printDialog.createPrintDocument("
+ "window."
+ JS_INTERFACE
+ ".getType(),window."
+ JS_INTERFACE
+ ".getTitle(),"
+ "window."
+ JS_INTERFACE
+ ".getContent(),window."
+ JS_INTERFACE
+ ".getEncoding()))");
// Add post messages listener.
view.loadUrl("javascript:window.addEventListener('message',"
+ "function(evt){window." + JS_INTERFACE
+ ".onPostMessage(evt.data)}, false)");
}
}
}
}
I see two things that might be wrong.
In the getContent method you have return "";
when you send the PDF in the onPrintClick method, you are not converting the PDF to base64.
I hope I spotted something interesting :)

Barcode scanning issue

I am working on barcode scanning on button click to increment the quantity counted field by one of a table when the scanning result matches with the item number field of the table. If the scan result matches item number it should update the quantity counted of that row. I am unable to get the scan result itself. Getting NullPointerException.
This is my code.
These are two Java files from zxing.
IntentIntegrator.java
package com.example.mis;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.ActivityNotFoundException;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
public class IntentIntegrator {
public static final int REQUEST_CODE = 0x0000c0de; // Only use bottom 16
// bits
private static final String TAG = IntentIntegrator.class.getSimpleName();
public static final String DEFAULT_TITLE = "Install Barcode Scanner?";
public static final String DEFAULT_MESSAGE = "This application requires Barcode Scanner. Would you like to install it?";
public static final String DEFAULT_YES = "Yes";
public static final String DEFAULT_NO = "No";
private static final String BS_PACKAGE = "com.google.zxing.client.android";
private static final String BSPLUS_PACKAGE = "com.srowen.bs.android";
// supported barcode formats
public static final Collection<String> PRODUCT_CODE_TYPES = list("UPC_A",
"UPC_E", "EAN_8", "EAN_13", "RSS_14");
public static final Collection<String> ONE_D_CODE_TYPES = list("UPC_A",
"UPC_E", "EAN_8", "EAN_13", "CODE_39", "CODE_93", "CODE_128",
"ITF", "RSS_14", "RSS_EXPANDED");
public static final Collection<String> QR_CODE_TYPES = Collections
.singleton("QR_CODE");
public static final Collection<String> DATA_MATRIX_TYPES = Collections
.singleton("DATA_MATRIX");
public static final Collection<String> ALL_CODE_TYPES = null;
public static final List<String> TARGET_BARCODE_SCANNER_ONLY = Collections
.singletonList(BS_PACKAGE);
public static final List<String> TARGET_ALL_KNOWN = list(BSPLUS_PACKAGE, // Barcode
// Scanner+
BSPLUS_PACKAGE + ".simple", // Barcode Scanner+ Simple
BS_PACKAGE // Barcode Scanner
// What else supports this intent?
);
private final Activity activity;
private String title;
private String message;
private String buttonYes;
private String buttonNo;
private List<String> targetApplications;
private final Map<String, Object> moreExtras;
public IntentIntegrator(Activity activity) {
this.activity = activity;
title = DEFAULT_TITLE;
message = DEFAULT_MESSAGE;
buttonYes = DEFAULT_YES;
buttonNo = DEFAULT_NO;
targetApplications = TARGET_ALL_KNOWN;
moreExtras = new HashMap<String, Object>(3);
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public void setTitleByID(int titleID) {
title = activity.getString(titleID);
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public void setMessageByID(int messageID) {
message = activity.getString(messageID);
}
public String getButtonYes() {
return buttonYes;
}
public void setButtonYes(String buttonYes) {
this.buttonYes = buttonYes;
}
public void setButtonYesByID(int buttonYesID) {
buttonYes = activity.getString(buttonYesID);
}
public String getButtonNo() {
return buttonNo;
}
public void setButtonNo(String buttonNo) {
this.buttonNo = buttonNo;
}
public void setButtonNoByID(int buttonNoID) {
buttonNo = activity.getString(buttonNoID);
}
public Collection<String> getTargetApplications() {
return targetApplications;
}
public final void setTargetApplications(List<String> targetApplications) {
if (targetApplications.isEmpty()) {
throw new IllegalArgumentException("No target applications");
}
this.targetApplications = targetApplications;
}
public void setSingleTargetApplication(String targetApplication) {
this.targetApplications = Collections.singletonList(targetApplication);
}
public Map<String, ?> getMoreExtras() {
return moreExtras;
}
public final void addExtra(String key, Object value) {
moreExtras.put(key, value);
}
/**
* Initiates a scan for all known barcode types.
*/
public final AlertDialog initiateScan() {
return initiateScan(ALL_CODE_TYPES);
}
/**
* Initiates a scan only for a certain set of barcode types, given as
* strings corresponding to their names in ZXing's {#code BarcodeFormat}
* class like "UPC_A". You can supply constants like
* {#link #PRODUCT_CODE_TYPES} for example.
*
* #return the {#link AlertDialog} that was shown to the user prompting them
* to download the app if a prompt was needed, or null otherwise
*/
public final AlertDialog initiateScan(
Collection<String> desiredBarcodeFormats) {
Intent intentScan = new Intent(BS_PACKAGE + ".SCAN");
intentScan.addCategory(Intent.CATEGORY_DEFAULT);
// check which types of codes to scan for
if (desiredBarcodeFormats != null) {
// set the desired barcode types
StringBuilder joinedByComma = new StringBuilder();
for (String format : desiredBarcodeFormats) {
if (joinedByComma.length() > 0) {
joinedByComma.append(',');
}
joinedByComma.append(format);
}
intentScan.putExtra("SCAN_FORMATS", joinedByComma.toString());
}
String targetAppPackage = findTargetAppPackage(intentScan);
if (targetAppPackage == null) {
return showDownloadDialog();
}
intentScan.setPackage(targetAppPackage);
intentScan.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intentScan.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
attachMoreExtras(intentScan);
startActivityForResult(intentScan, REQUEST_CODE);
return null;
}
/**
* Start an activity. This method is defined to allow different methods of
* activity starting for newer versions of Android and for compatibility
* library.
*
* #param intent
* Intent to start.
* #param code
* Request code for the activity
* #see android.app.Activity#startActivityForResult(Intent, int)
* #see android.app.Fragment#startActivityForResult(Intent, int)
*/
protected void startActivityForResult(Intent intent, int code) {
activity.startActivityForResult(intent, code);
}
private String findTargetAppPackage(Intent intent) {
PackageManager pm = activity.getPackageManager();
List<ResolveInfo> availableApps = pm.queryIntentActivities(intent,
PackageManager.MATCH_DEFAULT_ONLY);
if (availableApps != null) {
for (String targetApp : targetApplications) {
if (contains(availableApps, targetApp)) {
return targetApp;
}
}
}
return null;
}
private static boolean contains(Iterable<ResolveInfo> availableApps,
String targetApp) {
for (ResolveInfo availableApp : availableApps) {
String packageName = availableApp.activityInfo.packageName;
if (targetApp.equals(packageName)) {
return true;
}
}
return false;
}
private AlertDialog showDownloadDialog() {
AlertDialog.Builder downloadDialog = new AlertDialog.Builder(activity);
downloadDialog.setTitle(title);
downloadDialog.setMessage(message);
downloadDialog.setPositiveButton(buttonYes,
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
String packageName = targetApplications.get(0);
Uri uri = Uri.parse("market://details?id="
+ packageName);
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
try {
activity.startActivity(intent);
} catch (ActivityNotFoundException anfe) {
// Hmm, market is not installed
Log.w(TAG,
"Google Play is not installed; cannot install "
+ packageName);
}
}
});
downloadDialog.setNegativeButton(buttonNo,
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
}
});
return downloadDialog.show();
}
/**
* <p>
* Call this from your {#link Activity}'s
* {#link Activity#onActivityResult(int, int, Intent)} method.
* </p>
*
* #return null if the event handled here was not related to this class, or
* else an {#link IntentResult} containing the result of the scan.
* If the user cancelled scanning, the fields will be null.
*/
public static IntentResult parseActivityResult(int requestCode,
int resultCode, Intent intent) {
if (requestCode == REQUEST_CODE) {
if (resultCode == Activity.RESULT_OK) {
String contents = intent.getStringExtra("SCAN_RESULT");
String formatName = intent.getStringExtra("SCAN_RESULT_FORMAT");
byte[] rawBytes = intent.getByteArrayExtra("SCAN_RESULT_BYTES");
int intentOrientation = intent.getIntExtra(
"SCAN_RESULT_ORIENTATION", Integer.MIN_VALUE);
Integer orientation = intentOrientation == Integer.MIN_VALUE ? null
: intentOrientation;
String errorCorrectionLevel = intent
.getStringExtra("SCAN_RESULT_ERROR_CORRECTION_LEVEL");
return new IntentResult(contents, formatName, rawBytes,
orientation, errorCorrectionLevel);
}
return new IntentResult();
}
return null;
}
/**
* Defaults to type "TEXT_TYPE".
*
* #see #shareText(CharSequence, CharSequence)
*/
public final AlertDialog shareText(CharSequence text) {
return shareText(text, "TEXT_TYPE");
}
/**
* Shares the given text by encoding it as a barcode, such that another user
* can scan the text off the screen of the device.
*
* #param text
* the text string to encode as a barcode
* #param type
* type of data to encode. See
* {#code com.google.zxing.client.android.Contents.Type}
* constants.
* #return the {#link AlertDialog} that was shown to the user prompting them
* to download the app if a prompt was needed, or null otherwise
*/
public final AlertDialog shareText(CharSequence text, CharSequence type) {
Intent intent = new Intent();
intent.addCategory(Intent.CATEGORY_DEFAULT);
intent.setAction(BS_PACKAGE + ".ENCODE");
intent.putExtra("ENCODE_TYPE", type);
intent.putExtra("ENCODE_DATA", text);
String targetAppPackage = findTargetAppPackage(intent);
if (targetAppPackage == null) {
return showDownloadDialog();
}
intent.setPackage(targetAppPackage);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
attachMoreExtras(intent);
activity.startActivity(intent);
return null;
}
private static List<String> list(String... values) {
return Collections.unmodifiableList(Arrays.asList(values));
}
private void attachMoreExtras(Intent intent) {
for (Map.Entry<String, Object> entry : moreExtras.entrySet()) {
String key = entry.getKey();
Object value = entry.getValue();
// Kind of hacky
if (value instanceof Integer) {
intent.putExtra(key, (Integer) value);
} else if (value instanceof Long) {
intent.putExtra(key, (Long) value);
} else if (value instanceof Boolean) {
intent.putExtra(key, (Boolean) value);
} else if (value instanceof Double) {
intent.putExtra(key, (Double) value);
} else if (value instanceof Float) {
intent.putExtra(key, (Float) value);
} else if (value instanceof Bundle) {
intent.putExtra(key, (Bundle) value);
} else {
intent.putExtra(key, value.toString());
}
}
}
}
IntentResult.java
package com.example.mis;
public class IntentResult {
private final String contents;
private final String formatName;
private final byte[] rawBytes;
private final Integer orientation;
private final String errorCorrectionLevel;
IntentResult() {
this(null, null, null, null, null);
}
IntentResult(String contents,
String formatName,
byte[] rawBytes,
Integer orientation,
String errorCorrectionLevel) {
this.contents = contents;
this.formatName = formatName;
this.rawBytes = rawBytes;
this.orientation = orientation;
this.errorCorrectionLevel = errorCorrectionLevel;
}
/**
* #return raw content of barcode
*/
public String getContents() {
return contents;
}
/**
* #return name of format, like "QR_CODE", "UPC_A". See {#code BarcodeFormat} for more format names.
*/
public String getFormatName() {
return formatName;
}
/**
* #return raw bytes of the barcode content, if applicable, or null otherwise
*/
public byte[] getRawBytes() {
return rawBytes;
}
/**
* #return rotation of the image, in degrees, which resulted in a successful scan. May be null.
*/
public Integer getOrientation() {
return orientation;
}
/**
* #return name of the error correction level used in the barcode, if applicable
*/
public String getErrorCorrectionLevel() {
return errorCorrectionLevel;
}
#Override
public String toString() {
StringBuilder dialogText = new StringBuilder(100);
dialogText.append("Format: ").append(formatName).append('\n');
dialogText.append("Contents: ").append(contents).append('\n');
int rawBytesLength = rawBytes == null ? 0 : rawBytes.length;
dialogText.append("Raw bytes: (").append(rawBytesLength).append(" bytes)\n");
dialogText.append("Orientation: ").append(orientation).append('\n');
dialogText.append("EC level: ").append(errorCorrectionLevel).append('\n');
return dialogText.toString();
}
}
This is the activity in which i am implementing barcode scanning
public class InventoryCount extends Activity {
private Button mbtn_scan;
mbtn_scan.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
IntentIntegrator integrator = new IntentIntegrator(
InventoryCount.this);
integrator.initiateScan();
}
});
}
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
// retrieve result of scanning - instantiate ZXing object
IntentResult scanningResult = IntentIntegrator.parseActivityResult(
requestCode, resultCode, intent);
// check we have a valid result
try {
if (resultCode == RESULT_OK) {
Log.i("Scanning Result ", "" + scanningResult);
Toast.makeText(
InventoryCount.this,
"Scanning success the content is : "
+ scanningResult.getContents(),
Toast.LENGTH_SHORT).show();
String sr = scanningResult.getContents();
getBarCodeData(sr);
} else if (resultCode == RESULT_CANCELED) {
Toast toast = Toast.makeText(InventoryCount.this,
"Scanning Cancelled!", Toast.LENGTH_SHORT);
toast.show();
}
} catch (Exception e) {
System.out.println("Error on scanning: "+e);
}
}
public void getBarCodeData(String itmNumber) {
Cursor c;
try {
String qtyCountQry = "SELECT " + DatabaseHandler.KEY_QTYCOUNTED
+ " FROM " + DatabaseHandler.TABLE_MIC2 + " WHERE "
+ DatabaseHandler.KEY_ITEMNUMBER + "='" + itmNumber + "'";
SQLiteDatabase sq = db.getReadableDatabase();
c = sq.rawQuery(qtyCountQry, null);
c.moveToFirst();
String q2 = c.getString(c
.getColumnIndex(DatabaseHandler.KEY_QTYCOUNTED));
Toast.makeText(InventoryCount.this, "Quantity Count is " + q2,
Toast.LENGTH_SHORT).show();
} catch (Exception e) {
Toast.makeText(InventoryCount.this, "Exception " + e,
Toast.LENGTH_SHORT).show();
}
}
I have just tried to display scan result and if it matches itemnumber it will display the corresponding quantity in that row as shown in code above. But as of now not even scan result is displaying. Help me.. Also say how to increment the quantity by one and update it in db.
Try to use the zxing library by extending the CaptureActivity Class.
public class ScannerData extends CaptureActivity {
Handler handler = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_scanner);
}
#Override
public void handleDecode(final Result rawResult, Bitmap barcode,
float scaleFactor) {
// TODO Auto-generated method stub
handler = getHandler();
handler.sendEmptyMessageDelayed(R.id.restart_preview,
CaptureActivity.BULK_MODE_SCAN_DELAY_MS);
String mQrcode = rawResult.getText().toString();
}
}
Use the code like this.
You can get the qr-code here
String mQrcode = rawResult.getText().toString();
In Xml you need to include capture.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent">
<RelativeLayout
android:id="#+id/frameLayout1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_gravity="center_horizontal"
android:layout_marginRight="25dp">
<FrameLayout
android:layout_width="510dp"
android:layout_height="310dp"
android:background="#drawable/scanner_box"
android:layout_gravity="center" >
<include
android:layout_width="750dp"
android:layout_height="450dp"
android:layout_gravity="center"
android:layout_marginBottom="50dp"
android:layout_marginRight="110dp"
layout="#layout/capture" />
</FrameLayout>
</RelativeLayout>
</RelativeLayout>

How to use google cloud printer to print text file in android

I implemented Google cloud printing in my project but when i attach text file in Google cloud then it show that 1 page to print but not show its content.
So how do I show the content of text file when file attach to google cloud and how to get existing google account from the user phone and how to make setting of google chrome to print from my code so that user easily print the doc from my app.so please provide me the code or some good tutorial to deal with google cloud in my requirement way.
Intent printIntent = new Intent(ExportActivity.this, PrintDialogActivity.class);
printIntent.setDataAndType(Uri.fromFile(file), "text/*");
printIntent.putExtra("title", "Dictionary");
public class PrintDialogActivity extends Activity {
private static final String PRINT_DIALOG_URL = "https://www.google.com/cloudprint/dialog.html";
private static final String JS_INTERFACE = "AndroidPrintDialog";
private static final String CONTENT_TRANSFER_ENCODING = "base64";
private static final String ZXING_URL = "http://zxing.appspot.com";
private static final int ZXING_SCAN_REQUEST = 65743;
/**
* Post message that is sent by Print Dialog web page when the printing dialog needs to be closed.
*/
private static final String CLOSE_POST_MESSAGE_NAME = "cp-dialog-on-close";
/**
* Web view element to show the printing dialog in.
*/
private WebView dialogWebView;
/**
* Intent that started the action.
*/
Intent cloudPrintIntent;
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.print_dialog);
dialogWebView = (WebView) findViewById(R.id.webview);
cloudPrintIntent = this.getIntent();
WebSettings settings = dialogWebView.getSettings();
settings.setJavaScriptEnabled(true);
dialogWebView.setWebViewClient(new PrintDialogWebClient());
dialogWebView.addJavascriptInterface(new PrintDialogJavaScriptInterface(), JS_INTERFACE);
dialogWebView.loadUrl(PRINT_DIALOG_URL);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
if (requestCode == ZXING_SCAN_REQUEST && resultCode == RESULT_OK) {
dialogWebView.loadUrl(intent.getStringExtra("SCAN_RESULT"));
}
}
final class PrintDialogJavaScriptInterface {
public String getType() {
return cloudPrintIntent.getType();
}
public String getTitle() {
return cloudPrintIntent.getExtras().getString("title");
}
public String getContent() {
try {
ContentResolver contentResolver = getContentResolver();
InputStream is = contentResolver.openInputStream(cloudPrintIntent.getData());
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buffer = new byte[4096];
int n = is.read(buffer);
while (n >= 0) {
baos.write(buffer, 0, n);
n = is.read(buffer);
}
is.close();
baos.flush();
return Base64.encodeToString(baos.toByteArray(), Base64.DEFAULT);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return "";
}
public String getEncoding() {
return CONTENT_TRANSFER_ENCODING;
}
public void onPostMessage(String message) {
if (message.startsWith(CLOSE_POST_MESSAGE_NAME)) {
finish();
}
}
}
private final class PrintDialogWebClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (url.startsWith(ZXING_URL)) {
Intent intentScan = new Intent("com.google.zxing.client.android.SCAN");
intentScan.putExtra("SCAN_MODE", "QR_CODE_MODE");
try {
startActivityForResult(intentScan, ZXING_SCAN_REQUEST);
} catch (ActivityNotFoundException error) {
view.loadUrl(url);
}
} else {
view.loadUrl(url);
}
return false;
}
#Override
public void onPageFinished(WebView view, String url) {
if (PRINT_DIALOG_URL.equals(url)) {
// Submit print document.
view.loadUrl("javascript:printDialog.setPrintDocument(printDialog.createPrintDocument(" + "window." + JS_INTERFACE + ".getType(),window." + JS_INTERFACE + ".getTitle()," + "window." + JS_INTERFACE + ".getContent(),window." + JS_INTERFACE + ".getEncoding()))");
// Add post messages listener.
view.loadUrl("javascript:window.addEventListener('message'," + "function(evt){window." + JS_INTERFACE + ".onPostMessage(evt.data)}, false)");
}
}
}
}

Categories

Resources