Friday, 7 December 2018

PAYTM SDK Installation and Setup for Android App

Paytm Integration in Android App: https://developer.paytm.com/docs/v1/android-sdk

Server side integration 
https://github.com/Paytm-Payments

Create a developer account here:
https://developer.paytm.com/

Get api key from your account (There are Test api detail and production api detail)
https://dashboard.paytm.com/next/apikeys



Below is for during implementation......Android

1. Dependency

dependencies {
compile('com.paytm:pgplussdk:1.2.3') {
transitive = true;
}
}


2. Permissions
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.READ_SMS"/>
<uses-permission android:name="android.permission.RECEIVE_SMS"/>


3. Service
For Staging environment:
PaytmPGService service = PaytmPGService.getStagingService();

For Production environment:
PaytmPGService service = PaytmPGService.getProductionService();


4. Order
Note:- before call below code you have to call api to your server for get checksum.
(https://github.com/Paytm-Payments/Paytm_App_Checksum_Kit_PHP)

// First Get Checksum from Server for security purpose & pass that checksum to paytm params
// Checksum Generating code kit is available on GitHub for all server-side languages (like php, java etc.)

Map<String, String> paramMap = new HashMap<String,String>();
paramMap.put( "MID" , "rxazcv89315285244163");  // Key in your staging and production MID available in your dashboard
paramMap.put( "ORDER_ID" , "order1");
paramMap.put( "CUST_ID" , "cust123");
paramMap.put( "MOBILE_NO" , "7777777777");
paramMap.put( "EMAIL" , "username@emailprovider.com");
paramMap.put( "CHANNEL_ID" , "WAP");
paramMap.put( "TXN_AMOUNT" , "100.12");
paramMap.put( "WEBSITE" , "WEBSTAGING"); // This is the staging value. Production value is available in your dashboard
paramMap.put( "INDUSTRY_TYPE_ID" , "Retail"); // This is the staging value. Production value is available in your dashboard
paramMap.put( "CALLBACK_URL", "https://securegw-stage.paytm.in/theia/paytmCallback?ORDER_ID=order1");
paramMap.put( "CHECKSUMHASH" , "w2QDRMgp1234567JEAPCIOmNgQvsi+BhpqijfM9KvFfRiPmGSt3Ddzw+oTaGCLneJwxFFq5mqTMwJXdQE2EzK4px2xruDqKZjHupz9yXev4=")

PaytmOrder Order = new PaytmOrder(paramMap);



5. Certificate (optional)

Certificate object stores client-side SSL certificate related information and ensures secured handshake between your app and Paytm. Use this code snippet to create a certificate object:

PaytmClientCertificate Certificate = new PaytmClientCertificate(String inPassword, String inFileName);
// inPassword is the password for client side certificate
//inFileName is the file name of client side certificate

Note:
Client certificate must be present in “raw” folder
Pass filename without extension. For e.g if filename is “clientCert.cert” then pass only “clientCert”.

Parameters required to invoke the initialize method are Order and Certificate objects:
service.initialize(Order, Certificate);

In case you do not wish to pass the certificate, pass NULL:
service.initialize(Order, null);




6. Initiate Payment

Service.startPaymentTransaction(this, true, true, new PaytmPaymentTransactionCallback() {
/*Call Backs*/
                       public void someUIErrorOccurred(String inErrorMessage) {}
                       public void onTransactionResponse(Bundle inResponse) {}
                       public void networkNotAvailable() {}
                       public void clientAuthenticationFailed(String inErrorMessage) {}
                       public void onErrorLoadingWebPage(int iniErrorCode, String inErrorMessage, String inFailingUrl) {}
                       public void onBackPressedCancelTransaction() {}
                       public void onTransactionCancel(String inErrorMessage, Bundle inResponse) {}
     });

Monday, 3 December 2018

In-App Purchases - Android Developers


 Use In-app Billing with AIDL / Google Play Billing

1) Create product and configure it in Developer account.
    Need to create a product here Non-sunscription or subscription
    https://medium.com/@KarthikPonnam/inapp-purchase-subscription-android-8fff52fa4d3b

2) Download demo for inapp purchase for Android
Download link: https://drive.google.com/open?id=1-sqg2dBAC7PJTESsMjP1nq9vuyE_6w8m

Note:-
1) Please test in signed apk.
2) change SKU key according to configure in the developer account

Wednesday, 31 October 2018

Utilities

public class Utilities {

    public void showToast(Context context, String message) {
        Toast toast = Toast.makeText(context, message, Toast.LENGTH_LONG);
        View toastView = toast.getView(); // This'll return the default View of the Toast.        /* And now you can get the TextView of the default View of the Toast. */        TextView toastMessage = (TextView) toastView.findViewById(android.R.id.message);
        toastMessage.setTextSize(25);
        toastMessage.setTextColor(Color.WHITE);
        toastMessage.setGravity(Gravity.CENTER);
        toastMessage.setCompoundDrawablePadding(16);
        toastView.setBackgroundColor(Color.CYAN);
        toast.show();
    }

    public void hideSoftKeyboard(Context mContext, View view) {
        if (view != null) {
            InputMethodManager inputMethodManager = (InputMethodManager) mContext.getSystemService(INPUT_METHOD_SERVICE);
            inputMethodManager.hideSoftInputFromWindow(view.getWindowToken(), 0);
        }
    }

    /**     * Shows the soft keyboard     */    
    public void showSoftKeyboard(Context mContext, View view) {
        if (view != null) {
            InputMethodManager inputMethodManager = (InputMethodManager) mContext.getSystemService(INPUT_METHOD_SERVICE);
            view.requestFocus();
            inputMethodManager.showSoftInput(view, 0);
        }
    }

public static void showAlertDialog(Context context, String message) {

    AlertDialog.Builder builder = new AlertDialog.Builder(context);
    builder.setTitle("Title");
    builder.setMessage(message);
    builder.setCancelable(false);

    builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {

        @Override        public void onClick(DialogInterface dialog, int which) {
            dialog.dismiss();
        }
    });
    builder.show();

}

public void showToastColor(Context context, String message) {
    Toast toast = Toast.makeText(context, message, Toast.LENGTH_LONG);
    View toastView = toast.getView(); 
    TextView toastMessage = (TextView) toastView.findViewById(android.R.id.message);
    toastMessage.setTextSize(25);
    toastMessage.setTextColor(Color.WHITE);
    toastMessage.setGravity(Gravity.CENTER);
    toastMessage.setCompoundDrawablePadding(16);
    toastView.setBackgroundColor(Color.CYAN);
    toast.show();
}

public static String ordinal(int i) {
    String[] sufixes = new String[] { "th", "st", "nd", "rd", "th", "th", "th", "th", "th", "th" };
    switch (i % 100) {
        case 11:
        case 12:
        case 13:
            return i + "th";
        default:
            return i + sufixes[i % 10];

    }
}

public static String getCertificateSHA1Fingerprint(Context context) {
    PackageManager pm = context.getPackageManager();
    String packageName = context.getPackageName();
    int flags = PackageManager.GET_SIGNATURES;
    PackageInfo packageInfo = null;
    try {
        packageInfo = pm.getPackageInfo(packageName, flags);
    } catch (PackageManager.NameNotFoundException e) {
        e.printStackTrace();
    }
    Signature[] signatures = packageInfo.signatures;
    byte[] cert = signatures[0].toByteArray();
    InputStream input = new ByteArrayInputStream(cert);
    CertificateFactory cf = null;
    try {
        cf = CertificateFactory.getInstance("X509");
    } catch (CertificateException e) {
        e.printStackTrace();
    }
    X509Certificate c = null;
    try {
        c = (X509Certificate) cf.generateCertificate(input);
    } catch (CertificateException e) {
        e.printStackTrace();
    }
    String hexString = null;
    try {
        MessageDigest md = MessageDigest.getInstance("SHA1");
        byte[] publicKey = md.digest(c.getEncoded());
        hexString = byte2HexFormatted(publicKey);
    } catch (NoSuchAlgorithmException e1) {
        e1.printStackTrace();
    } catch (CertificateEncodingException e) {
        e.printStackTrace();
    }
    return hexString;
}

public static String byte2HexFormatted(byte[] arr) {
    StringBuilder str = new StringBuilder(arr.length * 2);
    for (int i = 0; i < arr.length; i++) {
        String h = Integer.toHexString(arr[i]);
        int l = h.length();
        if (l == 1) h = "0" + h;
        if (l > 2) h = h.substring(l - 2, l);
        str.append(h.toUpperCase());
        if (i < (arr.length - 1)) str.append(':');
    }
    return str.toString();
}
}

Saturday, 8 September 2018

Drag-Drop-Swipebutton Recyclerview


DragDropSwipebuttonRecyclerview

Download from here:-
https://drive.google.com/open?id=1MY1aqa6tObpsKoaAbiZ0EfZl0Nx26O0g

Wednesday, 25 July 2018

Thursday, 14 June 2018

View- Lifecycle


How view placed or draw in parent layout or itself.

https://stackoverflow.com/questions/13856180/usage-of-forcelayout-requestlayout-and-invalidate?utm_medium=organic&utm_source=google_rich_qa&utm_campaign=google_rich_qa

Thursday, 24 May 2018

Monday, 14 May 2018

Broadcast Receiver in Android (kotlin)


Broadcast Receiver in Android (kotlin)


//desing intentfilter name

var intentfilterSetList = "set_list"

Define variable

lateinit var brSetList: BroadcastReceiver
var ifSetList: IntentFilter = IntentFilter(AppConstant.intentfilterSetList)


Declare brodcast in activity

brSetList = object : BroadcastReceiver() {
    override fun onReceive(context: Context, intent: Intent) {

         // do your stuff
 
    }
}
// register broadcast in activity

activity.registerReceiver(brSetList, ifSetList)


// send broadcast from anywhere

sendBroadcast(Intent(AppConstant.intentfilterSetList))

Interface in Android (kotlin)


RecyclerViewClick.kt
interface RecyclerViewClick {
    fun onItemClick(position: Int)

}



// declare interface in activity

internal var recyclerListener: RecyclerViewClick = object : RecyclerViewClick {

    override fun onItemClick(position: Int) {

         // do you stuff

    }
}


// connection between two class using interface

// first place
adapter = ArtistSelectListAdapter(context, artistList, recyclerListener, true)


// for call interface
holder.rlTop.setOnClickListener(View.OnClickListener {
    recyclerListener.onItemClick(position) // this line call interfacewhere declare

})



Validation in Android


useful validation for android

Email:- 

1) // default validation funtionality
if (!Patterns.EMAIL_ADDRESS.matcher(edt_email.getText().toString()).matches()) {
 
}


2) First charactor dont allow to "."(dot) or " "space.

edt_email.addTextChangedListener(new TextWatcher() {
    @Override    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override    public void onTextChanged(CharSequence s, int start, int before, int count) {

    }

    @Override    public void afterTextChanged(Editable s) {

        try {

            String inputChar = edt_email.getText().toString();

            if (edt_email.getText().length() == 1) {

                if (inputChar.equalsIgnoreCase(".") || inputChar.equalsIgnoreCase(" ")) {
                    edt_email.setText("");
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
});


Mobile No.

1) First character allow only "+" sign.

edt_mobile.addTextChangedListener(new TextWatcher() {
    @Override    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override    public void onTextChanged(CharSequence s, int start, int before, int count) {

    }

    @Override    public void afterTextChanged(Editable s) {

        try {

            String last = edt_mobile.getText().toString();
            String inputChar = last.substring(last.length() - 1);


            if (edt_mobile.getText().length() > 1) {

                if (inputChar.equalsIgnoreCase("+")) {
                    edt_mobile.setText(edt_mobile.getText().toString().substring(0, edt_mobile.getText().length() - 1));
                    edt_mobile.setSelection(edt_mobile.getText().length());
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

    }
});

2) Only allow particular digits (only allow declared digit or characters)

<string name="mobile_digits">+9876543210</string>

in xml

android:digits="@string/mobile_digits"



Wednesday, 9 May 2018

Get Online Time from Google Server




public static void getTimeFromGoogleServerNoAsync(final Context context) {


    try {

        HttpClient httpclient = new DefaultHttpClient();
        HttpResponse response = httpclient.execute(new HttpGet("https://google.com/"));
        StatusLine statusLine = response.getStatusLine();
        if (statusLine.getStatusCode() == HttpStatus.SC_OK) {
            String dateStr = response.getFirstHeader("Date").getValue();
            //Here I do something with the Date String            //System.out.println("Google Time "+dateStr);
            PreferencesHelper preferencesHelper = new PreferencesHelper(context);
            preferencesHelper.setGoogleTime(dateStr);

            SimpleDateFormat sdf3 = new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss Z", Locale.ENGLISH);
            Date d1 = null;
            try {
                d1 = sdf3.parse(dateStr);
            } catch (Exception e) {
                e.printStackTrace();
            }

            System.out.println("OTP Google Time" + d1);
            Calendar calendar = Calendar.getInstance();
            System.out.println("OTP Device Time" + calendar.getTime());

        } else {
            //Closes the connection.            response.getEntity().getContent().close();
            throw new IOException(statusLine.getReasonPhrase());
        }
    } catch (ClientProtocolException e) {
        Log.d("Response", e.getMessage());
    } catch (IOException e) {
        Log.d("Response", e.getMessage());
    }

}



Encrypt/Decrypt string in Android (using your own secret key)

   
 // create secrete key of sting token/key    String keystr = "hkjhgsdghhg";
    byte[] bytearr = new Base32().decode(keystr);
    SecretKey secret = new SecretKeySpec(bytearr, 0, bytearr.length, "AES");

    String password = "123456";

    //Encrept    byte[] cipherText = encryptMsg(password, secret))
    

    public static byte[] encryptMsg(String message, SecretKey secret)
            throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, InvalidParameterSpecException, IllegalBlockSizeException, BadPaddingException, UnsupportedEncodingException
    {
        /* Encrypt the message. */        Cipher cipher = null;
        cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
        cipher.init(Cipher.ENCRYPT_MODE, secret);
        byte[] cipherText = cipher.doFinal(message.getBytes("UTF-8"));
        return cipherText;
    }

    //Decrept
    password =  decryptMsg(cipherText, secret))

    public static String decryptMsg(byte[] cipherText, SecretKey secret)
            throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidParameterSpecException, InvalidAlgorithmParameterException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException, UnsupportedEncodingException
    {
        /* Decrypt the message, given derived encContentValues and initialization vector. */        Cipher cipher = null;
        cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
        cipher.init(Cipher.DECRYPT_MODE, secret);
        String decryptString = new String(cipher.doFinal(cipherText), "UTF-8");
        return decryptString;
    }


Friday, 27 April 2018

Generate OTP - TimeBasedOneTimePasswordGenerator (like Google Authentication)


Generate OTP - TimeBasedOneTimePasswordGenerator (like Google Authentication)



code for generate OTP:-
------------------------------------------------------------------------------------------------------

String currentOTP;

public void genereateOTP(String key) {

    try {

        byte[] secret1 = new Base32().decode(key);

        //Key key = new SecretKeySpec(secret1,0,secret1.length, "DES");
        SecretKey key = new SecretKeySpec(secret1, 0, secret1.length, "AES");

        TimeBasedOneTimePasswordGenerator totp = new TimeBasedOneTimePasswordGenerator();
        Date now = new Date();
        Date later = new Date(now.getTime() + TimeUnit.SECONDS.toMillis(timeslice));

        System.out.format("Current password: %06d\n", totp.generateOneTimePassword(key, now));
        System.out.format("Future password:  %06d\n", totp.generateOneTimePassword(key, later));

       int generatedOTP = totp.generateOneTimePassword(key, now);

        currentOTP = String.format("%06d", generatedOTP);

    } catch (Exception e) {
        e.printStackTrace();
    }

}





Download Classes Here:-
https://drive.google.com/open?id=13Bw7F2ZaOv0y-IkSgqfD9N_FGfRKECaZ

Thursday, 19 April 2018

Chat Heads Demo, chat heads lik FB.

Chat Head Demos like FB.
User can access from whole device. we can access from any windows.


Donwload Demo from Here:-
https://drive.google.com/open?id=1Her67AbMUoXwAgKBXJ0JY36DIn9qlACj

Manage Universal layouts for Mobile device and Teblets also Portrait and Landscape.


Layouts for Mobile Devices and Teblet Devices
Layouts for Portrait and Landscape screens

Download demo from here:-
https://drive.google.com/open?id=1scBkC1A9u-K9umcuQBrjZj_To0vACk-8

Tuesday, 17 April 2018

Tab layout with fragment stack



Tab layout with fragment stack.

- Manage stack tab wise.


Download demo from here:-
https://drive.google.com/open?id=1dLEbCxukHz_CJaNqt01NBO7xEBFfGIbR

Tuesday, 6 March 2018

Google Analytics integrate in Android

Google Analytics Demo


Update your analytic id at:- res/xml/app_tracker.xml
<string name="ga_trackingId">analytics id</string>


Change activity name to your cutome Name:-
<screenName name="mp3song.sudokutech.com.googleanalytics.MainActivity">Main Activity</screenName>



Track Custome Event:- 

AppController.getInstance().trackScreenView("Home Screen");



Download Demo from Here:- 
https://drive.google.com/open?id=18qxpZ4yOyrKHPYubqXjWphgcoOcgkRWf

Friday, 12 January 2018

Using shared element transitions in activities and fragments- Animation



Example Demo

https://www.androidauthority.com/using-shared-element-transitions-activities-fragments-631996/

Run/install/debug Android applications over Wi-Fi ?

Open Teminal/cmd --------------- Below steps is for Android 10 or lower Step 1 - Connect the device via USB and make sure debugging is work...