Thursday, August 20, 2015

How to run/install pagseguro on android without thirdpart apps

Hi there!

Today i'm gonna show to you, how to run PagSeguro on Android Apps without any third part app from PagSeguro.

Everybody knows how important it is to offer payment methods in our apps. PagSeguro is a very common payment method in Brazil, but very tricky to get it run correctly on android apps. In fact almost every payment method is very annoying to implement! :)

For this reason I decided to implement my own PagSeguro solution and share a complete sample with the world.

First Step - Get a PagSeguro Account

To do so, register yourself on pagseguro, log in and go to: Vender > Ferramentas para desenvolvedores > Sandbox



There you'll find a automatic created test buyer (comprador de teste) and a test seller (vendedor de teste) like in the images bellow. kepp it open, then you'll need those values in the app we will see here.




Second Step - Fork or just download the sample from Github

The sample was developed using android studio and tested on my pagseguro sandbox account. It is available from here: https://github.com/treslines/pagseguro_android. The image bellow shows some transactions i made using my sandbox account:


What you'll get?

The pictures bellow show how the app looks like. It addresses already navigations issues e user notifications.
















Go download it!

Go now to github: https://github.com/treslines/pagseguro_android. download it and test it. Any feedback or contribution to make it better is welcome!

That's all! Hope you like it!

😱👇 PROMOTIONAL DISCOUNT: BOOKS AND IPODS PRO ðŸ˜±ðŸ‘‡

Be sure to read, it will change your life!
Show your work by Austin Kleonhttps://amzn.to/34NVmwx

This book is a must read - it will put you in another level! (Expert)
Agile Software Development, Principles, Patterns, and Practiceshttps://amzn.to/30WQSm2

Write cleaner code and stand out!
Clean Code - A Handbook of Agile Software Craftsmanship: https://amzn.to/33RvaSv

This book is very practical, straightforward and to the point! Worth every penny!
Kotlin for Android App Development (Developer's Library): https://amzn.to/33VZ6gp

Needless to say, these are top right?
Apple AirPods Pro: https://amzn.to/2GOICxy

😱👆 PROMOTIONAL DISCOUNT: BOOKS AND IPODS PRO ðŸ˜±ðŸ‘†

Thursday, August 13, 2015

Android AlertDialog utilities, redirect to google play store, check if third part app is istalled

Hi there!

Today i'm gonna share some utility methods i use very often while developing. Creating a popup dialog, a confirm dialog, ok-cancel-dialog, check if a third part app is installed, redirect to google play store if some app is missing and so on are common tasks in our daily business.

/**
 * Use this class to create alert dialogs on the fly, redirect to google play store and so on...< br / >
 * < br / >Author: Ricardo Ferreira, 8/13/15
 */
public final class AppUtil {

    /**
     * Shows a confirm dialog with a custom message and custom quit button text.
     * If you pass null to btnTxt, "ok" will be shown per default.
     *
     * @param context the apps context This value can't be null.
     * @param msg     the message to be shown. his value can't be null or empty.
     * @param btnTxt  the text to be shown in the quit button. For example "close"
     */
    public static void showConfirmDialog(@NonNull final Context context, @NonNull final String msg, final String btnTxt) {
        if (msg.isEmpty()) {
            throw new IllegalArgumentException("This value can't be empty!");
        }
        final AlertDialog dialog = new AlertDialog.Builder(context).setMessage(msg)
                .setPositiveButton((btnTxt == null ? "Ok" : btnTxt), new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                }).create();
        dialog.show();
    }

    /**
     * Shows a confirm dialog with a custom message, custom buttons and custom actions.
     *
     * @param ctx                the apps context. This value can't be null.
     * @param msg                the message to be shown This value can't be null or empty.
     * @param okBtn              the text to be shown in the ok button. If you pass null, ok will be shown per default
     * @param cancelBtn          the text to be shown in the cancel button. If you pass null, cancel will be shown per default
     * @param okAction           the action to be performed as soon as the user presses the ok button. if you pass null, nothing happens.
     * @param cancelAction       the action to be performed as soon as the user presses the cancel button. if you pass null, nothing happens.
     * @param backPressendAction the action to be performed as soon as the user presses the system back button. if you pass null, nothing happens.
     */
    public static void showOkCancelDialog(@NonNull final Context ctx, @NonNull final String msg, final String okBtn, final String cancelBtn, final AlertAction okAction, final AlertAction cancelAction, final AlertAction backPressendAction) {
        if (msg.isEmpty()) {
            throw new IllegalArgumentException("This value can't be empty!");
        }
        final AlertDialog dialog = new AlertDialog.Builder(ctx).setMessage(msg)
                .setPositiveButton((okBtn == null ? "Ok" : okBtn), new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        if (okAction != null) {
                            okAction.perform();
                        }
                    }
                }).setNegativeButton((cancelBtn == null ? "Cancel" : cancelBtn), new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        if (cancelAction != null) {
                            cancelAction.perform();
                        }
                    }
                }).setOnCancelListener(new DialogInterface.OnCancelListener() {
                    @Override
                    public void onCancel(DialogInterface dialog) {
                        dialog.dismiss();
                        if (backPressendAction != null) {
                            backPressendAction.perform();
                        }
                    }
                }).create();
        dialog.show();
    }

    public interface AlertAction {
        void perform();
    }

    /**
     * Use this method to check if a third part app is istalled or not
     * @param ctx the app's context
     * @param packageName the third part app's package name. something like: com.example.package
     * @return true if the app is installed.
     */
    public static boolean isAppInstalled(final Context ctx, final String packageName) {
        PackageManager pm = ctx.getPackageManager();
        boolean installed = false;
        try {
            pm.getPackageInfo(packageName, PackageManager.GET_ACTIVITIES);
            installed = true;
        } catch (PackageManager.NameNotFoundException e) {
            installed = false;
        }
        return installed;
    }

    /**
     *  Use this method to open the google play store
     * @param activity the app which wants to redirect to the google play store
     * @param googlePlayStoreId the third part app's package name. something like: com.example.package
     * @param requestCode the request code to be used in the method onActivityForResult in the app which called this method.
     */
    public static void navigateToGooglePlayStore(final Activity activity, final String googlePlayStoreId, final int requestCode) {
        try {
            activity.startActivityForResult(new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=" + googlePlayStoreId)), requestCode);
        } catch (android.content.ActivityNotFoundException anfe) {
            // last chance: try again a second time with a different approach
            activity.startActivityForResult(new Intent(Intent.ACTION_VIEW, Uri.parse("http://play.google.com/store/apps/details?id=" + googlePlayStoreId)), requestCode);
        }
    }
}

Usage Example:

//... 
// check if app is istalled
return AppUtil.isAppInstalled(context,packageName);
//... 
// redirect to google play store
AppUtil.navigateToGooglePlayStore(activity ,googlePlayStoreId, requestCode);
//... 
// create a Ok-Cancel-Dialog
final String msg = "The app will no work without PagSeguro.";
        AppUtil.showOkCancelDialog(context, msg, "Install", "Cancel",
        new AppUtil.AlertAction() {
            @Override
            public void perform() {
                navigateToGooglePlayStore(PAG_SEGURO_PACKAGE_NAME);
            }
        }, new AppUtil.AlertAction() {
            @Override
            public void perform() {
                finish();
            }
        }, new AppUtil.AlertAction() {
            @Override
            public void perform() {
                finish();
            }
        });
//... code omitted

That's all! hope you like it! :)

😱👇 PROMOTIONAL DISCOUNT: BOOKS AND IPODS PRO ðŸ˜±ðŸ‘‡

Be sure to read, it will change your life!
Show your work by Austin Kleonhttps://amzn.to/34NVmwx

This book is a must read - it will put you in another level! (Expert)
Agile Software Development, Principles, Patterns, and Practiceshttps://amzn.to/30WQSm2

Write cleaner code and stand out!
Clean Code - A Handbook of Agile Software Craftsmanship: https://amzn.to/33RvaSv

This book is very practical, straightforward and to the point! Worth every penny!
Kotlin for Android App Development (Developer's Library): https://amzn.to/33VZ6gp

Needless to say, these are top right?
Apple AirPods Pro: https://amzn.to/2GOICxy

😱👆 PROMOTIONAL DISCOUNT: BOOKS AND IPODS PRO ðŸ˜±ðŸ‘†

Tuesday, August 11, 2015

Router Design Pattern - Route messages, Objects or whatever you want!

Hi there!

Today i'm gonna show you the router pattern i wrote myself in action. The Router design pattern is a very useful programming design pattern whenever you need to be able to send objects or messages between instances over the application.

The example i will provide is a nice way to show it how it could looks like. You can always come back here, take it, adapt it and use it in your applictions as you may need. So be sure you bookmark it or join the group here on the right side of this post subscribing it. If you use it anywhere, please come back and give me a feedback. It would be nice to have more real use cases.

First of all, let's take a look at the UML diagram of it. After that we will take the analogy for our example.

The UML Diagram of the Router Pattern


Pay close attention, because once you understand that, everything will become clear and simple to understand. That's the reason I'm putting always the UML first. That way you'll get an eye for it with the time.





The example

In our example we will see, how we could create clients that listen to server responses. The servers are lazy instantiated and are created on demand.

Response and Request Interfaces

Those interfaces defines a contract to be used to design which type the client will use to send requests and receive responses. Let's take a closer look to it:
public interface Response < T >  {
  T getResponse();
  void setResponse(T value);
}

public interface Request < T >  {
  T getRequest();
  void setRequest(T value);
}

Client and Server Interfaces

Those interfaces defines a contract to be used while implementing concrete clients and servers. It uses either the Response or the Request depending on the what you are implementing:
public interface Client {
   < T extends Response < ? >  >  void onServerResponse(T response);
}

public interface Server {
  < T extends Request < ? > > void onClientRequest(T request, Client client);
}

Routable interface and Router class

The routable defines the contract for the router. The router itself is designed as a singleton and can be accessed and used everywhere in the application sending and receiving messages or objects. In this implementation the servers are lazy implemented and created on demand. For sure you may adapt it to your needs. Feel free to do it and give me feedback of the usage of it in your applications.
public interface Routable {
  public  < T extends Client >  void registerClient(T clientImpl);
  public void registerServer(Class < ? extends Server >  serverImpl);
  public  < T extends Request < ? >  >  void routeClientToServer(Class < ? extends Client >  clientImpl, Class < ? extends Server >  serverImpl, T request);
  public void removeClient(Class < ? >  serverClass);
  public void removeAllClients();
  public void removeServer(Class < ? >  clientClass);
  public void removeAllServers();
  public boolean isRegistered(Class < ? >  clazz);
}


public class Router implements Routable {

  private Map < String, Client >  clients = new HashMap < String, Client > ();
  // using sets to avoid duplicates
  public Set < Class < ? extends Client >  >  clientSet = new HashSet < Class < ? extends Client >  > ();
  public Set < Class < ? extends Server >  >  serverSet = new HashSet < Class < ? extends Server >  > ();
  private static final Router ROUTER = new Router();

  private Router() {
    // singleton - can be accessed anywhere in the application
  }

  public static Router turnOn() {
    return ROUTER;
  }

  public  < T extends Request < ? >  >  void routeClientToServer(Class < ? extends Client >  clientImpl, Class < ? extends Server >  serverImpl, T request) {
    doNotAllowNullValue(clientImpl);
    doNotAllowNullValue(serverImpl);
    doNotAllowNullValue(request);
    doNotAllowUnregisteredNullValue(isRegistered(clientImpl));
    // just to ensure that the server implementation exits already
    doNotAllowUnregisteredNullValue(isRegistered(serverImpl));
    // as we now know that the server implementation exists,
    // we just create a lazy instance over reflection on demand
    try {
      serverImpl.newInstance().onClientRequest(request, clients.get(clientImpl.getName()));
    } catch (InstantiationException e) {
      // we shall never run into this situation, except if the user does NOT define
      // a default constructor in any of the concrete implementation of Server as per
      // convention.
      e.printStackTrace();
    } catch (IllegalAccessException e) {
      e.printStackTrace();
    }
  }

  public void removeServer(Class < ? >  serverClass) {
    serverSet.remove(serverClass);
  }

  public void removeAllServers() {
    serverSet.clear();
  }

  public void removeClient(Class < ? >  clientclass) {
    clients.remove(clientclass.getName());
    clientSet.remove(clientclass);
  }

  public void removeAllClients() {
    clients.clear();
  }

  public boolean isRegistered(Class < ? >  clazz) {
    boolean result = false;
    boolean searchBreak = false;
    Iterator < Class < ? extends Client >  >  iterator = clientSet.iterator();
    while (iterator.hasNext()) {
      Class < ? extends Client >  next = iterator.next();
      // note: we can't use equalsIgnoreCase here
      if (next.getName().equals(clazz.getName())) {
        result = true;
        searchBreak = true;
        break;
      }
    }
    if (!searchBreak) {
      Iterator < Class < ? extends Server >  >  it = serverSet.iterator();
      while (it.hasNext()) {
        Class < ? extends Server >  next = it.next();
        // note: we can't use equalsIgnoreCase here
        if (next.getName().equals(clazz.getName())) {
          result = true;
          searchBreak = true;
          break;
        }
      }
    }
    return result;
  }

  public  < T extends Client >  void registerClient(T clientImpl) {
    doNotAllowNullValue(clientImpl);
    clientSet.add((Class < ? extends Client > ) clientImpl.getClass());
    clients.put(clientImpl.getClass().getName(), clientImpl);
  }

  public void registerServer(Class < ? extends Server >  serverImpl) {
    doNotAllowNullValue(serverImpl);
    serverSet.add(serverImpl);
  }

  private void doNotAllowNullValue(Object toCheck) {
    if (toCheck == null) {
      final String msg = "You can't pass null to this method!";
      throw new NullPointerException(msg);
    }
  }

  private void doNotAllowUnregisteredNullValue(boolean isRegistered) {
    if (!isRegistered) {
      final String msg = "Either the client or the server was not registered in this router. Register it first!";
      throw new IllegalArgumentException(msg);
    }
  }
}

Sample Implementation and Test

Now let's see how a real implementation could looks like and how it works in practise. First of all we are gonna define some responses and requests. Then we will create the clients and servers. Finally we will test it, by running a junit test to show it in action.
//SAMPLE CLIENT RESPONSE
public class ClientResponse implements Response < String >  {
  private String response;
  public String getResponse() {return response;}
  public void setResponse(String value) {response = value;}
}

//SAMPLE SERVER REQUEST
public class ServerRequest implements Request < String >  {
  String request;
  public String getRequest() {return request;}
  public void setRequest(String value) {request = value;}
}

// SAMPLE CLIENT IMPL
public class ClientImpl implements Client {
  public  < T extends Response < ? > > void onServerResponse(T response) {
    System.out.println(response.getResponse());
  }
}

//SAMPLE SERVER IMPL
public class ServerImpl implements Server {
  public < T extends Request < ? > >  void onClientRequest(T request, Client client) {
    // handle request and depending on it create response
    ClientResponse clientResponse = new ClientResponse();
    clientResponse.setResponse("Server is sending a response to client...");
    // route response back to client immediately or whenever you want
    client.onServerResponse(clientResponse);
  }
}

public class RouterTest {
  @Test
  public void testRouter() {
    Router.turnOn().registerClient(new ClientImpl());
    // servers would be only referenced and lazy instantiated later
    Router.turnOn().registerServer(ServerImpl.class);
    System.out.println("Client is sending a request to server...");
    ServerRequest request = new ServerRequest();
    request.setRequest("Client is sending a request to server...");
    Router.turnOn().routeClientToServer(ClientImpl.class, ServerImpl.class, request);
  }
}


That's all! hope you like it! :)


😱👇 PROMOTIONAL DISCOUNT: BOOKS AND IPODS PRO ðŸ˜±ðŸ‘‡

Be sure to read, it will change your life!
Show your work by Austin Kleonhttps://amzn.to/34NVmwx

This book is a must read - it will put you in another level! (Expert)
Agile Software Development, Principles, Patterns, and Practiceshttps://amzn.to/30WQSm2

Write cleaner code and stand out!
Clean Code - A Handbook of Agile Software Craftsmanship: https://amzn.to/33RvaSv

This book is very practical, straightforward and to the point! Worth every penny!
Kotlin for Android App Development (Developer's Library): https://amzn.to/33VZ6gp

Needless to say, these are top right?
Apple AirPods Pro: https://amzn.to/2GOICxy

😱👆 PROMOTIONAL DISCOUNT: BOOKS AND IPODS PRO ðŸ˜±ðŸ‘†