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.
Related
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);
}
}
}
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();
}
});
}
}
}
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 :)
I am assigned a project on vehicle tracking system to be developed as an android app.
Project Brief:
A vehicle driver is been given a GPRS powered android OS installed phone so that the location is tracked. The assumption is that all route coordinates (latitude & longitude) are already stored in DB.Such that when the driver crosses a particular place, there should be an alert (change of status) in the DB.In this way, the tracking shall be made efficiently.
My Issue:
I have developed the program but unable to get it executed. I am wondering if my coding is totally wrong or I had left something in between. I have attached/pasted the program for your consideration.
I shall be too glad to receive inputs from you & see the dawn of the project's execution.
You shall reach me at inbasharu#gmail.com
Alternately, if you are magnanimous in helping me outright do buzz me # 9659709092/7305738685
My codes are:
1.proximity Alert Receiver
public class ProximityAlertReceiver extends BroadcastReceiver {
private static final String ACTIVE_TASK_LOC = "com.android.model.TaskLoc";
private static final String ACTIVE_TASK_TEXT = "com.android.model.TaskText";
private static final String ACTIVE_TASK_USER_ID = "com.android.model.TaskUserid";
private static final String ACTIVE_TASK_ROUTE_NUM = "com.android.model.TaskRoutenum";
private static final String ACTIVE_TASK_TOWARDS = "com.android.model.TaskTowards";
Ringtone r;
private static String url_create = "";
JSONParser jsonParser = new JSONParser();
private static final String TAG_SUCCESS = "success";
int id;
String taskLoc, taskText, taskRoutenum, taskUserid, taskTowards;
#Override
public void onReceive(Context context, Intent intent) {
if ("android.intent.action.BOOT_COMPLETED".equals(intent.getAction())) {
ComponentName comp = new ComponentName(context.getPackageName(),
LocationProxyService.class.getName());
ComponentName service = context.startService(new Intent()
.setComponent(comp));
if (null == service) {
} else {
}
} else {
String key = LocationManager.KEY_PROXIMITY_ENTERING;
Boolean entering = intent.getBooleanExtra(key, false);
Bundle bundle = intent.getExtras();
taskLoc = bundle.getString(ACTIVE_TASK_LOC);
String taskText = bundle.getString(ACTIVE_TASK_TEXT);
String taskRoutenum = bundle.getString(ACTIVE_TASK_VEHICLE_NUM);
String taskUserid = bundle.getString(ACTIVE_TASK_USER_ID);
String taskTowards = bundle.getString(ACTIVE_TASK_TOWARDS);
if (entering) {
try {
enterLocation(context, "Task : \"" + taskText + "\"",
"You are Near to " + taskLoc, "UserId : \""
+ taskUserid + "\"", "Vehicle_no : \""
+ taskRoutenum + "\"", "Towrads : \""
+ taskTowards);
enterLocation(context, "Task : \"" + taskText + "\"",
"You are Near to " + taskLoc, "UserId : \""
+ taskUserid + "\"", "Vehicle_no : \""
+ taskRoutenum + "\"", "Towrads : \""
+ taskTowards);
} catch (Exception e) {
}
} else {
exitLocation(context, "Task : \"" + taskText + "\"",
"You are Leaving " + taskLoc + " already!");
}
}
}
public void enterLocation(Context context, String contentText,
String contentTitle, String contentUserid, String contentVehicle_no,
String contentTowards) {
Toast.makeText(context, contentText + "" + contentTitle,
Toast.LENGTH_SHORT).show();
Intent service = new Intent(context, set_routes.class);
context.startService(service);
new Ajax().execute();
}
public void exitLocation(Context context, String contentText,
String contentTitle) {
Toast.makeText(context, contentText + "" + contentTitle,
Toast.LENGTH_SHORT).show();
}
class Ajax extends AsyncTask<String, String, String> {// JSON STARTS HERE
// new CreateNewProduct().execute();
protected ArrayList<NameValuePair> parameters;
protected String v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11;
boolean success;
String msg = "";
public Ajax() {
super();
v1 = taskUserid;
v2 = taskRoutenum;
v3 = taskLoc;
v4 = taskTowards;
parameters = new ArrayList<NameValuePair>();
NameValuePair name = new BasicNameValuePair("user_id", v1);
NameValuePair mobile_no = new BasicNameValuePair("Vehicle_no", v2);
NameValuePair email = new BasicNameValuePair("current_stop", v3);
NameValuePair password = new BasicNameValuePair("towards", v4);
// NameValuePair address = new BasicNameValuePair("address", v9);
parameters.add(name);
parameters.add(mobile_no);
parameters.add(email);
parameters.add(password);
// parameters.add(address);
success = false;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
/*
* pDialog = new ProgressDialog(Newproduct.this);
* pDialog.setMessage("Creating Product..");
* pDialog.setIndeterminate(false); pDialog.setCancelable(true);
* pDialog.show();
*/
}
/**
* Creating product
* */
protected String doInBackground(String... args) {
// getting JSON Object
// Note that create product url accepts POST method
JSONObject json = jsonParser.makeHttpRequest(url_create, "POST",
this.parameters);
// check log cat fro response
Log.d("Create Response", "asdf" + json.toString());
// check for success tag
try {
success = json.getBoolean(TAG_SUCCESS);
msg = json.getString("message");
if (success) {
id = json.getInt("id");
} else {
// failed to create product
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog once done
if (success) {
Toast.makeText(getBaseContext(), "Sucessfully inserted" + id,
Toast.LENGTH_SHORT).show();
Intent i = new Intent(getApplicationContext(), set_vehicles.class);
startActivity(i);
} else {
Toast.makeText(getBaseContext(), msg, Toast.LENGTH_LONG).show();
Intent i = new Intent(getApplicationContext(), Main.class);
startActivity(i);
}
}
private Context getBaseContext() {
// TODO Auto-generated method stub
return null;
}
private Context getApplicationContext() {
// TODO Auto-generated method stub
return null;
}
private void startActivity(Intent i) {
// TODO Auto-generated method stub
}
}
}
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)");
}
}
}
}