Thursday, 24 July 2014

How to browse SQLLite Data in android

While Android puts a powerful built-in database at your disposal, it doesn't come with the best set of debugging tools. In fact, unless you have a rooted device, you can't even get the SQLite tables off your device without jumping through some hoops.  Fortunately, the Android emulator doesn't have this restriction.


Within Eclipse, you need to switch to DDMS mode by going to Window | Open Perspective | DDMS. If you've never used DDMS, you'll likely need to go to Window | Open Perspective | Other and then browse for DDMS within the list

Once the DDMS view is active, choose the File Explorer tab. You'll find your database in the /data/data/your.app.namespace/databases directory. There are two virtually indistinguishable icons in the upper right-hand corner of the tab that represent a pull and a push of a file, respectively. Use the pull icon (the one on the left) to save a copy of the SQLite database to your development machine and change extension of the copied file to .sqlite


 Now you have a copy of your database on your workstation, but you still need some kind of SQLite viewer to take a peek. I use SQLite Manager, because it is free and runs well

Open the SQLite Manager in the fire fox and select connect database option as shown below




Once you select browse for the file which you have saved in your workstation .

Done:)
You can browse and check your data

Monday, 21 July 2014

httpclient exception “org.apache.http.conn.ConnectionPoolTimeoutException: Timeout waiting for connection”

 The exception as following:
    org.apache.http.conn.ConnectionPoolTimeoutException: Timeout waiting for connection
    at org.apache.http.impl.conn.tsccm.ConnPoolByRoute.getEntryBlocking(ConnPoolByRoute.java:417)
    at org.apache.http.impl.conn.tsccm.ConnPoolByRoute$1.getPoolEntry(ConnPoolByRoute.java:300)
    at org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager$1.getConnection(ThreadSafeClientConnManager.java:224)
    at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:401)
    at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:820)
    at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:754)
    at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:732)
    at com.i360r.client.takeaway.network.HttpClientTest.(HttpClientTest.java:68)
    at com.i360r.client.takeaway.network.HttpClientTest.main(HttpClientTest.java:88) 
 
 
 
 
 
Fix is the following piece of code 
try {
 } catch (Exception e) {
 } finally {
  mPost.abort;
 }
 
 
This exception often occurs when first request is not executed successfully and hence
you should abort it  

Friday, 18 July 2014

Combine Two Arrays

import com.google.common.collect.ObjectArrays;
import java.util.Arrays;
import org.apache.commons.lang.ArrayUtils;
/**
 * Java program to combine two arrays in Java. In this Java example
 * first we have concatenated two int arrays and later two String arrays.
 * First array combine examples uses Apache commons ArrayUtils, second array
 * join example uses Guava's ObjectArrays and last array concatenate example uses JDK.
 *
 * @author Javin Paul
 */
public class CombineArrayJava {
    public static void main(String args[]) {
      
        int [] first = {1,2,3, 4};
        int [] second = {5,6,7,8};
      
        // combine two arrays in Java using Apache commons ArrayUtils
        int [] combined = ArrayUtils.addAll(first, second);
     
        System.out.println("First array : " + Arrays.toString(first));
        System.out.println("Second array : " + Arrays.toString(second));
        System.out.println("Combined array : " + Arrays.toString(combined));
    
        String [] one = {"a", "b", "c"};
        String [] two = {"d", "e"};
      
        //joining array in Java using Guava library
        String [] joined = ObjectArrays.concat(one, two, String.class);
        System.out.println("Joined array : " + Arrays.toString(joined));
      
        //JDK way to combine two array in Java
        int[] array1 = {101,102,103,104};
        int[] array2 = {105,106,107,108};
        int[] concatenate = combine(array1, array2);
        System.out.println("concatenated array : " + Arrays.toString(concatenate));
      
    }
  
 
    public static int[] combine(int[] a, int[] b){
        int length = a.length + b.length;
        int[] result = new int[length];
        System.arraycopy(a, 0, result, 0, a.length);
        System.arraycopy(b, 0, result, a.length, b.length);
        return result;
    }
  
}
Output:
First array : [1, 2, 3, 4]
Second array : [5, 6, 7, 8]
Combined array : [1, 2, 3, 4, 5, 6, 7, 8]
Joined array : [a, b, c, d, e]
concatenated array : [101, 102, 103, 104, 105, 106, 107, 108]

Thursday, 17 July 2014

Info on Why Push Notification gets delayed

Android push notifications works through one TCP connection on the port 5228 between the phone and google servers. This connection is established when the phone connect to a network. All android push apps (gmail, whatsapp, hangouts, etc.) use Google Cloud Messaging (GCM) to send and receive push notifications thought that connection.
 
By definition a TCP connection does not have a timeout. But in the real world, wifi routers and mobile carriers have some rules to limit the number of opened tcp connections. So they usually close/kill what they think to be an inactive connection after some times that no packets are transmitted. For example my wifi router kill connections after 300 seconds (5 minutes) of inactivity (no packets on the tcp connection).

What happens is that, when I don't have push notifications for 5 minutes, the router kill the connection because is inactive and android is not able (since the router didn't sent any ack to the phone) to intercept that the connection has been closed because of a tcp idle timeout rule. From that moment the GCM connection is a dead connection and no push notifications are received until the connection is re-established (switch wifi/mobile connection off and on, or an heartbeat is sent, see below).

Android have a mechanism to send a little network packet (called heartbeat) every x minutes to avoid the tcp connection timeout and check if the connection is alive; that is a wide common and working practice. If the connection is not alive, the GCM connection is re-established and previously  notifications and new one come again.

What is the problem? The problem is that the heartbeat is sent with the following intervals: 
- every 28 minutes on mobile connection, 2g/3g/4g;
- every 15 minutes on wifi;
(You can see those values by dialing on the phone *#*#8255#*#* (with new play services you can dial *#*#426#*#* if previous don't work) . Those values are updated remotely through Google Checking mechanism, so if google want, they can easily update those values and all android devices will have new values in about 24 hours.)

Those are to much high values for most of the users in the world. Mobile carriers close inactive tcp connections much sooner, same as wifi routers (most wifi routers kill inactive connections after 5 minutes!). This cause delayed push notifications!

Please implement a dynamic mechanism to set the right heartbeat interval value depending on the user connection, or set a low heartbeat interval like 2 minutes! I did a lot of test by changing the heartbeat intervals, battery is not impacted to much at all (if you have root search Push Notifications Fixer on play store).

Lot android users think that push notifications are broken because of this problem, please take care of this, short the heartbeat interval. It is so annoying! This problem exists since the introduction of push notifications, android 2.2, till as currently android kitkat 4.4.2.

Note that not all users are affected by this, only users with some routers or some carriers with strict policy to kill inactive tcp connections are affected. All carriers/routers kill inactive connections after some time, the problem are the carriers/routers that kills connection after so short time.

Also some of you may have a different problem, like wifi/3g completely drop while the screen is off, that's an other problem.

As last note even iPhone users have push notifications delayed in some cases as well, so people don't complain about that.

Because of this issue, some apps developer start to use their own separated connection to mitigate, or sometimes make worse, the problem (see whatsapp, they have a connection on the port 5222 that go on timeout as well..).

tag: push notification delay, push notifications delay, push notification delayed

Wednesday, 4 June 2014

check for Play Services

package com.example.testgcm;


import android.app.Activity;

import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.widget.Toast;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;

public class MainActivity extends Activity {
    static final int REQUEST_CODE_RECOVER_PLAY_SERVICES = 1001;
      static final int REQUEST_CODE_PICK_ACCOUNT = 1002;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }
   
     @Override
      protected void onResume() {
        super.onResume();
        if (checkPlayServices()) {
          // Then we're good to go!
        }
      }
   
   
     private boolean checkPlayServices() {
          //  int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
          int status = ConnectionResult.SERVICE_VERSION_UPDATE_REQUIRED;
            if (status != ConnectionResult.SUCCESS) {
              if (GooglePlayServicesUtil.isUserRecoverableError(status)) {
                showErrorDialog(status);
              } else {
                Toast.makeText(this, "This device is not supported.", Toast.LENGTH_LONG).show();
                finish();
              }
              return false;
            }
            return true;
          }
   
     void showErrorDialog(int code) {
            GooglePlayServicesUtil.getErrorDialog(code, this, REQUEST_CODE_RECOVER_PLAY_SERVICES).show();
          }
   
     @Override
      protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
          case REQUEST_CODE_RECOVER_PLAY_SERVICES:
            if (resultCode == RESULT_CANCELED) {
              Toast.makeText(this, "Google Play Services must be installed and up-to-date.",
                  Toast.LENGTH_SHORT).show();
              finish();
            }
            return;
        
        }
        super.onActivityResult(requestCode, resultCode, data);
      }
   

   

}

output
-------------------
We get an alert



Note
-----------------
Here we should add google play service library project as a dependency project and the following tag should be included in the application tag of the manifest

  <meta-data android:name="com.google.android.gms.version" android:value="@integer/google_play_services_version" />


@integer/google_play_services_version this points to GooglePlayServices library project "version.xml"

Tuesday, 27 May 2014

ScheduledThreadPoolExecutor example

package mypackage;
import java.text.DateFormat;

import java.util.Date;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class ScheduledExample {
    final static DateFormat fmt = DateFormat.getTimeInstance(DateFormat.LONG);
    public static void main(String[] args) {
        // Create a scheduled thread pool with 5 core threads
        ScheduledThreadPoolExecutor sch = (ScheduledThreadPoolExecutor)
                Executors.newScheduledThreadPool(5);
        
        // Create a task for one-shot execution using schedule()
        Runnable oneShotTask = new Runnable(){
            @Override
            public void run() {
                System.out.println("\t oneShotTask Execution Time: "
                            + fmt.format(new Date()));
            }
        };
        
        // Create another task
        Runnable delayTask = new Runnable(){
            @Override
            public void run() {
                try{
                    System.out.println("\t delayTask Execution Time: "
                            + fmt.format(new Date()));
                    Thread.sleep(10 * 1000);
                    System.out.println("\t delayTask End Time: "
                            + fmt.format(new Date()));
                }catch(Exception e){
                    
                }
            }
        };
        
        // And yet another
        Runnable periodicTask = new Runnable(){
            @Override
            public void run() {
                try{
                    System.out.println("\t periodicTask Execution Time: "
                            + fmt.format(new Date()));
                    Thread.sleep(10 * 1000);
                    System.out.println("\t periodicTask End Time: "
                            + fmt.format(new Date()));
                }catch(Exception e){
                    
                }
            }
        };
        
        System.out.println("Submission Time: " + fmt.format(new Date()));
    //  ScheduledFuture<?> oneShotFuture = sch.schedule(oneShotTask, 5, TimeUnit.SECONDS);
      ScheduledFuture<?> delayFuture = sch.scheduleWithFixedDelay(delayTask, 5, 5, TimeUnit.SECONDS);
     //   ScheduledFuture<?> periodicFuture = sch.scheduleAtFixedRate(periodicTask, 5, 5, TimeUnit.SECONDS);
    }
}

Friday, 16 May 2014

How to generate Java Doc

Java Doc can be generated using Eclipse IDE.We should have Javadoc.exe in the bin folder of the Java

Following is the step

Go to Eclipse--------->Project Menu--------->Generate Java Doc--------->Here you will be prompted with the menu which contains all the projects present in IDE , select the project for which you want JavaDoc.

Above give the following location C:\Program Files\Java\jdk1.7.0_17\bin\javadoc.exe


Click on next.Select the location where uou want the java doc's to be extracted.

Done:)

Pass a HashMap from Angular Client to Spring boot API

This example is for the case where fileData is very huge and in json format   let map = new Map<string, string>()      map.set(this.ge...