Programming

React Native List View : Pagination With FlatList

React Native List View : Pagination With FlatList

FlatList is is an interface used to render flat list, the component is provided by Facebook’s React Native Library

Handy features of FlatList are as follows

  1. It renders list of items if you just provide rendering View
  2. You can mention whether your list is horizontal or vertical, by default its vertical list view
  3. Configurable Callbacks provided 
  4. Header / Footer / Separator are supported by FlatList
  5. Pull To Refresh is made simple with React Native Flat List View
  6. Pagination is made easy using React Native Flat List view

How To Use React Native Flat List : With Loading symbol in Footer

<FlatList
          refreshing={this.state.refreshing}
          onRefresh={true}
          onEndReachedThreshold={0.5}
          onEndReached={({ distanceFromEnd }) => {
            //Call API to fetch next page of data
            console.log('on end reached ', distanceFromEnd);
          }}
          ListFooterComponent={(
            <View style={{flex: 1, justifyContent: 'center', alignItems: 'center'}}>
              <Spinner color='#6d4c41' />
              <Text>Loading please wait...</Text>
            </View>
          )}
          data={this.props.messages}
          renderItem={this.notificationContent.bind(this)}
          keyExtractor={(item) => item._id}
        />

React Native Pull To Refresh Using Flat List

Pull to refresh is made easy by just mentioning onRefresh = true and we should also mention refreshing = true while fetching new data 

Pagination Using Flat List In React Native

To achieve pagination mention onEndReachedThreshold some value between 0 – 1 and  a callback for onEndReached should be provided where we have a logic to call API to fetch next page of data

Official documentation of React Native FlatList has many more functionalities listed.

Issues with React Native FlatList or onEndReached doesn’t get fired

Some times pagination for FlatList doesn’t work as expected, onEndReached Will never get fired, or some times it will be called only first time when list is loaded. Possible reason for this behaviour would be keeping FlatList inside native base Container or Content, Keep FlatList inside View to fix the issue. 

Another possible solution to the issue of FlatList is changing onEndReachedThreshold value to a small number like 0.001.

Another Interesting solution which worked for me is giving height explicitly to the FlatList , this will call onEndReached callback

style={{ height: ( Dimensions.get(‘window’).height – 100 ) }}

Addressing The issue : React Native FlatList onEndReached called again and again

This can be addressed by ignoring the callback calls, this is can be done by using distanceFromEnd, if the value is +ve then do your pagination stuffs, if the value is    -ve then ignore the callback call. ReactNative FlatList returns +ve value when scroll reaches the end of the list. So the update code looks like below

<FlatList
          refreshing={this.state.refreshing}
          onRefresh={true}
          onEndReachedThreshold={0.5}
          onEndReached={({ distanceFromEnd }) => {
            if (distanceFromEnd >= 0) {
              //call API to get next page values
            }
            console.log('on end reached ', distanceFromEnd);
          }}
          data={this.props.messages}
          renderItem={this.notificationContent.bind(this)}
          keyExtractor={(item) => item._id}
        />


Also Explore React Native Exceptions

ReactNative Exception: TabNavigator expected a component class, got [object, object]

ReactNative Exception: TabNavigator expected a component class, got [object, object]

Possible cases to get ReactNative Error: ReactNative Exception: TabNavigator expected a component class, got [object, object] .

  1. When you are using a component with all small letters or a component that begin with small letter, Example

 

const FooterTabNavigation = TabNavigator(
  {
    Home: {
      screen: ({ screenProps, navigation }) => <homePage navigation={navigation} />
    },
 });

 

Solution : Use Capitalised class names, like HomePage navigation={navigation}

2. Another case is if by any chance you are using <div> component in ReactNative this exception might occur.
Example

const FooterTabNavigation = TabNavigator(
  {
    Home: {
      screen: ({ screenProps, navigation }) =&gt; &lt;homePage navigation={navigation} /&gt;
    },
    TestScreen: {
      screen: ({ screenProps, navigation }) =&gt; &lt;div /&gt;
    }
});

 

Solution : Do not use div tag in ReactNative instead use View

Explore More About React Native : React Native FlatList And Pagination

ReactJS : Functional or Stateless components

ReactJS : Functional or Stateless components

Many times you might come across a situation where React Component doesn’t need any state, which we call as stateless components. Thanks to React0.14 update, It introduced new types of react components with no state. 

React Stateless components are very much needed when the components is readonly doesn’t perform any operation other than just showing information.

How to Write React Functional component ?

React Functional Component Example: for stateless react component or a functional react component

const MessageBar = function(props) {
  return &lt;p&gt;Dear {props.username} you have completed the task successfully&lt;/p&gt;;
};

The same component can nicely be written in one line using ES2015 standard as follows

const MessageBar = ({ username }) =&gt; &lt;p&gt;Dear {username} user, you have successfully completed the task&lt;/p&gt;;

 

Conceptually components are like javascript functions here, they accept inputs as props, and return react elements. Functional components wherever required will also reduce load on redux since it is not required to maintain state for these components.

For more information on React functional components visit facebook react official site 

Also Check How to integrated Google Maps in reactJS : http://knowledge-cess.com/reactjs-google-map-component/

 

Java Springs SEVERE Exception : javax.servlet.ServletException: Circular view path

Java Springs SEVERE  Exception : javax.servlet.ServletException: Circular view path

Exception : occurred while calling REST API in Springs

 org.apache.catalina.core.StandardWrapperValve invoke SEVERE:

Servlet.service() for servlet [Spring] in context with path [/app] threw exception

[Circular view path [events]: would dispatch back to the current handler URL [/app/service/events] again. Check your ViewResolver setup! (Hint: This may be the result of an unspecified view, due to default view name generation.)] with root cause javax.servlet.ServletException: Circular view path [events]: would dispatch back to the current handler URL [/app/service/events] again. Check your ViewResolver setup! (Hint: This may be the result of an unspecified view, due to default view name generation.) at org.springframework.web.servlet.view.InternalResourceView.prepareForRendering(InternalResourceView.java:209) at org.springframework.web.servlet.view.InternalResourceView.renderMergedOutputModel(InternalResourceView.java:149) at org.springframework.web.servlet.view.AbstractView.render(AbstractView.java:303) at org.springframework.web.servlet.DispatcherServlet.render(DispatcherServlet.java:1228) at org.springframework.web.servlet.DispatcherServlet.processDispatchResult(DispatcherServlet.java:1011) at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:955) at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:877) at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:961) at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:852) at javax.servlet.http.HttpServlet.service(HttpServlet.java:622) at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:837) at javax.servlet.http.HttpServlet.service(HttpServlet.java:729) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:291) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206) at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:219) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106) at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:142) at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79) at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:616) at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:518) at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1091) at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:673) at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1526) at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1482) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) at java.lang.Thread.run(Thread.java:745)

Solution :

Change your controller API signature from

public EventListResponse fetchEvents() 

To

public @ResponseBody EventListResponse fetchEvents

javax.persistence.PersistenceException : NonUniqueDiscoveredSqlAliasException

javax.persistence.PersistenceException : NonUniqueDiscoveredSqlAliasException

Exception javax.persistence.PersistenceException: org.hibernate.loader.custom.NonUniqueDiscoveredSqlAliasException: Encountered a duplicated sql alias [id] during auto-discovery of a native-sql query at org.hibernate.jpa.spi.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1763) at org.hibernate.jpa.spi.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1677) at org.hibernate.jpa.internal.QueryImpl.getResultList(QueryImpl.java:458) $$FastClassBySpringCGLIB$$ad104aa9.invoke( <generated>) at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:204) at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:717) at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157) at org.springframework.aop.framework.adapter.AfterReturningAdviceInterceptor.invoke(AfterReturningAdviceInterceptor.java:52) at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) at org.springframework.aop.aspectj.AspectJAfterThrowingAdvice.invoke(AspectJAfterThrowingAdvice.java:58) at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) at 

Solution : 

Give different alias to each column you are selecting. This happens mainly due to same column names in different tables.

Something like this “select u.id as userid, adm.id as adminId from user as u, admin as adm”

Caused by: java.lang.ClassNotFoundException: org.hibernate.cache.EntityRegion

Caused by: java.lang.ClassNotFoundException: org.hibernate.cache.EntityRegion

Caused by: java.lang.ClassNotFoundException: org.hibernate.cache.EntityRegion

OR

Caused by: org.hibernate.cache.NoCacheRegionFactoryAvailableException: Second-level cache is used in the application, but property hibernate.cache.region.factory_class is not given; please either disable second level cache or set correct region factory using the hibernate.cache.region.factory_class setting and make sure the second level cache provider (hibernate-infinispan, e.g.) is available on the classpath.

 

Solution

  1.  Replace POM dependency for net.sf.ehcache : ehcache-core

  Replace below lines

                
		dependency
			net.sf.ehcache
			ehcache-core
			2.6.11
		/dependency
		

From below lines

		
		dependency
			org.hibernate
			hibernate-ehcache
			4.3.5.Final
		/dependency
		

2. set Factory_class in spring.xml file as given below

Replace below lines

				prop key="hibernate.cache.region.factory_class" net.sf.ehcache.hibernate.EhCacheRegionFactory/prop
				prop key="hibernate.cache.use_query_cache"&gt; true/prop

With below lines

				prop key="hibernate.cache.region.factory_class"&gt; org.hibernate.cache.ehcache.EhCacheRegionFactory /prop
				prop key="hibernate.cache.use_query_cache"&gt;true /prop

3.  Then use setCacheable(true); for your queries in hibernate criteria

 

How Longitude, Latitude and GPS location services works

How Longitude, Latitude and GPS location services works

This article is to understand the mathematics behind GPS location services, how exactly google maps calculates the distance, how basic mathematics being used behind the screen.

Before going directly to mathematical part of it, let us understand the theory part 🙂 . how it is possible to locate places on the planet earth and calculate the distance? Mathematics has changed the world and is the base for everything. We all know that earth is like sphere, its not exact sphere because earth is spinning on its axis and the equator is flat compared to poles of the earth.

earth as sphere

earthLongitudeLatitude

Earth Longitude Latitude

The image above clearly shows how exactly the earth is, since its flat along the equator the radius at equator is more compared to radius along the poles.

But considering the mean radius of earth we shall assume earth as a perfect sphere. So the radius of the earth is 6371Kms.

Let us consider two locations JP Nagar, and Jayanagar in Bangalore India. If I locate these places on the sphere It looks as below.

Mathematics behind Distance calculation using Locations points

Earth Locations Sphere Calculations

Earth Locations Sphere Calculations

 

Earth Locations Sphere Calculations

Earth Locations Sphere Calculations

There are many methods to calculate the distance between two points, many will prefer the below logic. Note here the first image show all Latitude values vary between [-90,+90] and longitude varies between [-180,+180]

Also Read : An Interesting article one how Facebook trying to connect the world

Calculating Distance between two locations using Longitude and Latitude

                 
                //Earth radius is 
                static final double earthRadius = 6371; //Kilometers
                double dLat = Math.toRadians(lat2 - lat1);
		double dLng = Math.toRadians(lng2 - lng1);
		double sindLat = Math.sin(dLat / 2);
		double sindLng = Math.sin(dLng / 2);
		double a = Math.pow(sindLat, 2)
				+ Math.pow(sindLng, 2) * Math.cos(Math.toRadians(lat1)) *  Math.cos(Math.toRadians(lat2));
		double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
		double dist = earthRadius * c;

		return dist;

The above code gives you the distance between two locations on a sphere.

Also Read : How exactly regular expressions works ?

Also Read :  How animations works internally ?

Selecting certain fields in Hibernate Criteria using Projections

Selecting certain fields in Hibernate Criteria using Projections

This is not a great post but many people will face this issue and the solution is very simple for which many will spend hours of time to find it.

Issue faced by many are selecting certain fields of the table using hibernate criteria, converting array of Objects (Object[]) to respective custom class object, Even after converting the values for the fields will be set to default rather than actual values of the fields.

Take an example :

  Class Person {
    private Integer personid;
    private String personname;
    private String mobilenumber;
    private String permanentaddress;
    private String localaddress;

    public Integer getPersonid(){ }

    public void setPersonid(Integer personid){ }

    public String getPersonname(){ }

    public void setPersonname(String personname){ }

    //Other fields getter/Setter
    
  }

In this example assume that you wish to fetch only personid and personname using hibernate criteria

Fetching only selected fields using Hibernate Criteria







  List persons = null;
  Criteria criteria = sessionObject.createCriteria(Person.class);
		 criteria.setProjection(Projections.projectionList().add(Projections.property("personid")).add(Projections.property("personname")));

 criteria.setResultTransformer(Transformers.aliasToBean(Person.class));
 persons = criteria.list();

Issue : All fields are getting empty/default values after using hibernate projections

This issue is a very difficult to tackle, because hibernate doesn’t through any exception for this but it returns objects filled with default values of fields.

Solution: The solutions is really simple, just use an alias to each field in projections

//See alias personid and personname for both the fields
//Projections.property(“personid”),”personid”) and Projections.property(“personname”),”personname”)

 criteria.setProjection(Projections.projectionList().add(Projections.property("personid"),"personid").add( Projections.property("personname"),"personname"));

 

The above solution doesn’t work for One-To-Many relationship also when there is an aggregation, has-a relationship.

A Wrapper to fetch selected fields using hibernate Projections for One-To-Many relationship

Download the library given below and import it in your project, then define a Response Class like PersonResponse.java, which should be exact replica of Person.java , where it holds all details of a person fetched from database person table.

then just use the below code 

personCriteria.setResultTransformer(new AliasToBeanNestedResultTransformer(PersonResponse.class));

Source Code : AliasToBeanNestedResultTransformer

Thanks to : http://stackoverflow.com/a/25770708/526438

Regular Expressions : How Exactly they work internally ?

Regular Expressions : How Exactly they work internally ?

Regular expressions were playing major role in computers from several decades, they are not as simple as we think. They are need extensive computational power, a decade before regular expressions were a big headache for computer programmers and scientists because they were consuming lot of time to complete the task.

History behind Regular Expressions :

A neuroscientist  who tried to understand how the human brain could produce complex patterns using simple cells that are bound together. In 1943, Warren McCulloch and Walter Pitts published “A logical calculus of the ideas immanent in nervous activity”.  this paper had a great influence on computer science during that time. In 1956, mathematician Stephen Kleene developed this model one step further. In the paper “Representation of events in nerve nets and finite automata” he presents a simple algebra. The terms Regular Sets and Regular Expressions were born from then. As mentioned above, Kleene’s algebra had only two operations and one function. In 1968, the Unix pioneer Ken Thompson published the article “Regular Expression Search Algorithm” in Communications.

A Pattern in regular expression :

How to learn regular expressions ? How to understand regular expressions?. They look confusing to understand regular expression but regular expressions are an elegant way to do some string manipulations.

We have studied finite automata and the regular expressions all just works on this theory, but Most modern programming languages (Perl, Python, Ruby, Java (and JVM based languages), C#) do not use this approach rather they use recursive backtracking approach. But finite automata is really good to understand regular expressions with its state diagrams and not a bad idea to implement in this approach may be recursive backtracking is better. So do you need a help to understand regular expression? here it is…

Let us take one example, Validating an email address

If this is your regular expression

[a-z][a-z|0-9|]*([_][a-z|0-9]+)*([.][a-z|0-9]+([_][a-z|0-9]+)*)

The respective state diagram might look like below

Regular expression state diagram

Regular expression state diagram

 

Regular expression parser Source Code

If you want to try out with your own regular expression code you can better go through here 

http://www.codeproject.com/Articles/5412/Writing-own-regular-expression-parser