Java Functional Programming: Understanding Predicates

As java 8 introduces the predicate functions, but we may wonder where to use those true/false returning function in our daily programming life. The answer is we can use this in the following scenario:
1. when we have to evaluate the objects from the same class which will result in the true or false.
2. to filter the objects by using some of its variables etc.

lets hack Predicate with some examples:

A. Examining if the object is the intance of the particular class or not: 

/** * Created by yubraj on 1/26/16. */

public class MyClass {
    Predicate<MyClass> predicate1 = (MyClass myclass) -> this.equals(myclass);
    Predicate<MyClass> predicate2 =  this::equals;
    String text1 = "yubraj", text2 = "pokharel";
    public MyClass(String text1, String text2) {
        this.text1 = text1;        this.text2 = text2;    }

    @Override    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        MyClass myClass = (MyClass) o;
        if (!text1.equals(myClass.text1)) return false;
        return text2.equals(myClass.text2);
    }

    @Override    public int hashCode() {
        int result = text1.hashCode();    
        result = 31 * result + text2.hashCode();
        return result;    }

    public void myMethod(MyClass cl){
        System.out.println("Intance equals : " + predicate2.test(cl));    }

    public static void main(String[] args) {
        MyClass mc = new MyClass("sudhan", "pokharel");
        MyClass mc2 = new MyClass("yubraj", "pokharel");
        mc.myMethod(mc);
        System.out.println("-----------------------------------");
        mc2.myMethod(mc2);
    }

}

Output:
true
true
//because both are the intance of the similar object.



B. Filtering the objects

for male employee who are older then 21 years

lets add this in the Employee Class

public static Predicate<Employee> isAdultMale() {
    return p -> p.getAge() > 21 && p.getGender().equalsIgnoreCase("M");
}

then we can access all the employee who are Male and also more then 21 years by passing method as the variable eg:
public static void main(String[] args){
        Employee e1 = new Employee(1,23,"M","Rick","Beethovan");
        Employee e2 = new Employee(2,13,"F","Martina","Hengis");
        Employee e3 = new Employee(3,43,"M","Ricky","Martin");
        Employee e4 = new Employee(4,26,"M","Jon","Lowman");
        Employee e5 = new Employee(5,19,"F","Cristine","Maria");
        Employee e6 = new Employee(6,15,"M","David","Feezor");
        Employee e7 = new Employee(7,68,"F","Melissa","Roy");
        Employee e8 = new Employee(8,79,"M","Alex","Gussin");
        Employee e9 = new Employee(9,15,"F","Neetu","Singh");
        Employee e10 = new Employee(10,45,"M","Naveen","Jain");
         
        List<Employee> employees = new ArrayList<Employee>();
        employees.addAll(Arrays.asList(new Employee[]{e1,e2,e3,e4,e5,e6,e7,e8,e9,e10}));
                
        System.out.println(filterEmployees(employees, isAdultMale()));
}

Happy Coding :)

References: howtodoinjava, oracle

1. For this example I am using php server side code to gather the data from the data base and return it as a Json format. For this we can use the buid in code for php i.e.
json_encode($data);

for eg: (using Codeigniter model)

                $check_sql = "Select * from user where about_status = 1"; //status is flag for the active user
$check = $ci->db->query($check_sql);
$row = $check->result();

echo json_encode($row);

which gives output as:

{
"records": [
  {
    "Name" : "Yubraj Pokharel",
    "City" : "Kathmandu",
    "Country" : "NP"
  },
  {
    "Name" : "Chitra Shrestha",
    "City" : "Pokhara",
    "Country" : "NP"
  },
  {
    "Name" : "Prayag Upd",
    "City" : "California",
    "Country" : "US"
  },
  {
    "Name" : "Sudhan Pokharel",
    "City" : "Nepalgunj",
    "Country" : "NP"
  },
  {
    "Name" : "Mr Tom Cruise",
    "City" : "California",
    "Country" : "US"
  }
]
}

2. calling it from the angular page:

<html>
<head>
<title>Json Data</title>
        call angular js here
</head>
<body>
<div class="container">
<div class="row">
<div class="col-lg-12" ng-app="myApp" ng-controller="customersCtrl"> 
<table class="table">
<tr>
<th>Name</th>
<th>country</th>
</tr>
<tr  ng-repeat="x in names">
     <td>{{ x.Name }} </td>
     <td>{{ x.Country }}</td>
   </tr>
</table>
</div>
</div>
</div>

<script>
var app = angular.module('myApp', []);
app.controller('customersCtrl', function($scope, $http) {
    $http.get("http://localhost/angular/news.php")
    .success(function(response) {$scope.names = response.records;});
});
</script>
</body>
</html>

3. Here it is done enjoy happy coding :)

Single page Web App using Angular JS

Single page Web App using Angular JS



index.html
This is the simple part. We’re using Bootstrap and Font Awesome. Open up your index.html file and we’ll add a simple layout with a navigation bar.

<!doctype html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Single page web app using Angularjs</title>


<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.3/angular.min.js"></script>
 <script src="//cdnjs.cloudflare.com/ajax/libs/angular.js/1.3.3/angular-route.min.js"></script>
  <script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
  <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css">
  <script src="//maxcdn.bootstrapcdn.com/bootstrap/3.3.1/js/bootstrap.min.js"></script>
  <script src="script.js"></script>


</head>
<body ng-app="shaharma">

  <div>
      <div>
          <nav class="navbar navbar-inverse" role="navigation" style="padding-left:130px;">
             <ul class="nav navbar-nav">
                <li class="active"><a href="#/">Home<span class="sr-only">(current)</span></a></li>
                <li><a href="#/about">About us</a></li>
                <li><a href="#/about">Read tutorial</a></li>
              </ul>
          </nav>
      </div>

      <br/>

      <div ng-view class="jumbotron"></div> <!-- div where the dynamic page view will be loaded -->

  </div>
</body>

</html>

Injecting Pages into the Main Layout

ng-view is an Angular directive that will include the template of the current route (/home, /about, or /contact) in the main layout file. In plain words, it takes the file we want based on the route and injects it into our main layout (index.html).
We will add the ng-view code to our site in the div#maito tell Angular where to place our rendered pages.

Configure Routes and Views

Since we are making a single page application and we don’t want any page refreshes, we’ll use Angular’s routing capabilities.
Let’s look in our Angular file and add to our application. We will be using $routeProvider in Angular to handle our routing. This way, Angular will handle all of the magic required to go get a new file and inject it into our layout.
For linking to pages, we’ll use the #. We don’t want the browser to think we are actually travelling to about.html or home.html
First, we have to create our module and controller in javascript. We will do that now in script.js.

script.js.
var app = angular.module('shaharma',['ngRoute']);

app.config(function($routeProvider){

      $routeProvider
          .when('/',{
                templateUrl: 'home.html'
          })
          .when('/about',{
                templateUrl: 'about.html',
                controller:'yubrajcontroller'
          });


});

app.controller('yubrajcontroller', ['$scope', '$http', function($scope, $http){   ---[A]
   $scope.message = 'Welcome to Inspire';
   $http.get("http://www.w3schools.com/website/Customers_JSON.php")
.success(function(response) {$scope.names = response;});
}]);


--[A]- description
here we are fetching the json data from the http server which will be shown in the about.html file



about.html.

<div style="padding-left:130px;padding-right:200px;">

<h1>About us page2. {{message}} </h1>

 <p><input type="text" ng-model="searchresult"></p>
<table class="table">
<tr>
<th>Name</th>
<th>City</th>
<th>Country</th>
</tr>
<tr ng-repeat="x in names | filter:searchresult">

<!-- here names comes from the yubrajcontroller which is returning the json data to the about us page -->

<td>{{ x.Name | uppercase }}</td>
<td>{{ x.City | uppercase }}</td>
<td>{{ x.Country | uppercase }}</td>
</tr>

   </table>

 </div>


home.html

 <div style="padding-left:130px;padding-right:200px;">
   <h1>Hello, world!</h1>
  <p>This is simple angular ng-view and ng-route tutorial to demonstrate single page web app development.</p>
  <p>
    This is executed because of this code.
    <pre>
      <code>
        .when('/',{
              templateURl: 'home.html'
        })
      </code>
    </pre>
  </p>
  <p><a class="btn btn-primary btn-lg" href="#" role="button">Read tutorial</a></p>
</div>

--Enjoy

Intregating Polymer With Angular JS Routing

Step 1:
install polymer form its official site polymer-project.org, best way to download polymer is by using
bower : bower install --save Polymer/polymer#^1.0.0

Step 2:
set up your site's main page i.e index.html using the components what you like. You can see the code of my index.html file here

Step 3:
Now add the angular js plugins in the end of header in index page as below
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.3/angular.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/angular.js/1.3.3/angular-route.min.js"></script>

Step 4:
Now create angular app by initiating it by using ng-app="shaharma"in the body tag
<body  unresolved class="fullbleed layout vertical" ng-app="shaharma">

Step 5:
We are going to do route by using the hash(#) routing technique. Now update the link tag with # link tag as below:

     <paper-menu class="list" >
          <a href="#/">
            <iron-icon icon="home"></iron-icon>
            <span>Home</span>
          </a>
          <a href="#/about">
            <iron-icon icon="info"></iron-icon>
            <span>Users</span>
          </a>
          <a href="#/contact">
            <iron-icon icon="mail"></iron-icon>
            <span>Contact</span>
          </a>
        </paper-menu>
Now create a file named angular.js where we are going to add the route technique for our website. The final code is here

Step 6:
define a content area where the view are tobe loaded by using  ng-view
<div class="content" ng-view></div>

Step 7:
Now lets create a webelements which are going to be displayed inthe content section during the routing:
inside the elements folder we can see the web components for the different view which can be view here
example : for contact-form view

<dom-module id="contact-form">
  <style is="custom-style">
      paper-card {width: 100%-20px;margin: 10px;}
      #heading{color: #313131;font-size: 16px;font-weight: bold;
      .content.paper-button {padding: 0; }
  </style>
  <template is="dom-bind">
    <h4>Character counter</h4>
    <div class="vertical-section">
      <paper-input label="label" char-counter></paper-input>
      <paper-input label="at most 10 letters" char-counter auto-validate pattern="[a-zA-Z]*" maxlength="10" error-message="letters only!"></paper-input>
      <paper-textarea label="textarea" char-counter></paper-textarea>
      <paper-textarea label="textarea with maxlength" char-counter maxlength="10"></paper-textarea>
      <paper-textarea label="text area with rows and max-rows" rows="3" max-rows="4"><paper-textarea>
    </div>
  </template>

<script>
(function() {
  Polymer({
    is: 'contact-form'
  });
})();
</script>
</dom-module>

Step 8: register all the elements in the single elements.html page
 elements/elements.html
Full working code can be found here and demo can be viewd here

Most Important things you need to know about Mobile Apps

Before getting start to develop or marketing mobile application, you should know about this most important things, which may helpful further.


  1.  An app may be overkill, In some cases, a mobile-optimized website will do the job just fine.
  2. You can't go it alone ! It's only by cultivating partnerships and alliances that you can effectively  create a network of support to help market you app.
  3. Make your device platform choice carefully.
  4. Build relationships , not just apps.
  5. App marketing must be a constant focus, so keep your eye on the prize - always.
  6. Know you audience. Mobile devices are fiercely personal and people expect customized experiences.
  7. Personal privacy is paramount. You must tell your users up front what kind of data about them is being collected.
  8. Be aware of billing solutions,You should choose your payment methods and mechanisms wisely.
  9. Post lunch problems abound, and a multitude of variables can affect how your app performs.
  10. Think big and be useful. Apps server people, so expect the next wave of innovation to focus on utility, not novelty.
Credit: Book "Everything guide to mobile Apps" by Peggy Anne salz and Jennifer moranz

                                               By Online from Amazon


How to open PDF file in Android or Android Studio

Are you making app open pdf file ,here is the sample code that you can integrate in your app make great.

First create PDFTools.java file in Src folder, and paste this code

public class PDFTools {
private static final String GOOGLE_DRIVE_PDF_READER_PREFIX = "http://drive.google.com/viewer?url=";
private static final String PDF_MIME_TYPE = "application/pdf";
private static final String HTML_MIME_TYPE = "text/html";
static Context mcontext;

/**
* If a PDF reader is installed, download the PDF file and open it in a
* reader. Otherwise ask the user if he/she wants to view it in the Google
* Drive online PDF reader.<br />
* <br />
* <b>BEWARE:</b> This method
* @param context
* @param pdfUrl
* @return
*/
public static void showPDFUrl(final Context context, final String pdfUrl) {
mcontext=context;
if (isPDFSupported(mcontext)) {
downloadAndOpenPDF(mcontext, pdfUrl);
} else {
askToOpenPDFThroughGoogleDrive(mcontext, pdfUrl);
}
}

/**
* Downloads a PDF with the Android DownloadManager and opens it with an
* installed PDF reader app.
* @param context
* @param pdfUrl
*/
@TargetApi(Build.VERSION_CODES.GINGERBREAD)
public static void downloadAndOpenPDF(final Context context, final String pdfUrl) {
// Get filename
final String filename = pdfUrl.substring(pdfUrl.lastIndexOf("/") + 1);
// The place where the downloaded PDF file will be put
final File tempFile = new File(context.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS), filename);
if (tempFile.exists()) {
// If we have downloaded the file before, just go ahead and show it.
openPDF(context, Uri.fromFile(tempFile));
return;
}

// Show progress dialog while downloading
final ProgressDialog progress = ProgressDialog.show(context, context.getString(R.string.pdf_show_local_progress_title),
context.getString(R.string.pdf_show_local_progress_content), true);

// Create the download request
DownloadManager.Request r = new DownloadManager.Request(Uri.parse(pdfUrl));
r.setDestinationInExternalFilesDir(context, Environment.DIRECTORY_DOWNLOADS, filename);
final DownloadManager dm = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
BroadcastReceiver onComplete = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
if (!progress.isShowing()) {
return;
}
context.unregisterReceiver(this);

progress.dismiss();
long downloadId = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1);
Cursor c = dm.query(new DownloadManager.Query().setFilterById(downloadId));

if (c.moveToFirst()) {
int status = c.getInt(c.getColumnIndex(DownloadManager.COLUMN_STATUS));
if (status == DownloadManager.STATUS_SUCCESSFUL) {
openPDF(context, Uri.fromFile(tempFile));
}
}
c.close();
}
};
context.registerReceiver(onComplete, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));

// Enqueue the request
dm.enqueue(r);
}

/**
* Show a dialog asking the user if he wants to open the PDF through Google
* Drive
* @param context
* @param pdfUrl
*/
public static void askToOpenPDFThroughGoogleDrive(final Context context, final String pdfUrl) {
new AlertDialog.Builder(context).setTitle(R.string.pdf_show_online_dialog_title).setMessage(R.string.pdf_show_online_dialog_question)
.setNegativeButton(R.string.pdf_show_online_dialog_button_no, null).setPositiveButton(R.string.pdf_show_online_dialog_button_yes, new OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
openPDFThroughGoogleDrive(context, pdfUrl);
}
}).show();
}

/**
* Launches a browser to view the PDF through Google Drive
* @param context
* @param pdfUrl
*/
public static void openPDFThroughGoogleDrive(final Context context, final String pdfUrl) {
Intent i = new Intent(Intent.ACTION_VIEW);
i.setDataAndType(Uri.parse(GOOGLE_DRIVE_PDF_READER_PREFIX + pdfUrl), HTML_MIME_TYPE);
context.startActivity(i);
}

/**
* Open a local PDF file with an installed reader
* @param context
* @param localUri
*/
public static final void openPDF(Context context, Uri localUri) {
Intent i = new Intent(Intent.ACTION_VIEW);
i.setDataAndType(localUri, PDF_MIME_TYPE);
context.startActivity(i);
}

/**
* Checks if any apps are installed that supports reading of PDF files.
* @param context
* @return
*/
public static boolean isPDFSupported(Context context) {
Intent i = new Intent(Intent.ACTION_VIEW);
final File tempFile = new File(context.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS), "test.pdf");
i.setDataAndType(Uri.fromFile(tempFile), PDF_MIME_TYPE);
return context.getPackageManager().queryIntentActivities(i, PackageManager.MATCH_DEFAULT_ONLY).size() > 0;
}

}

Now, wherever you want to open pdf file onclick of button or images, make like this


btnPDF.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {

String pdfUrl = "pdfurl";
if (PDFTools.isPDFSupported(context)) {
PDFTools.showPDFUrl(context, pdfUrl);
} else {
                                  Toast.makeText(context, "Please Download PDF Reader",Toast.LENGTH_SHORT).show();

}

}
});

Finally, your pdf will be open.