Sunday, 9 February 2014

Some Basic Knowledge on NDK

How to generate wrapper files using swig :

1)Install Swig using the following link
http://www.swig.org/download.html

2)Copy in your folder and from cmd prompt go the location and type the following command
swig -c++ -java path

Where path indicates location of .i file[which is mandatory to generate wrapper classes]

3)Corresponding wrapper classes will be generated and then build using eclipse before building in eclipse  follow the below steps

4)Set Ndk path in window--->preferences --->Android--->Ndk

5)Go to project properties c/c++ build --->Tool chain Editor and there set CurrentBuilder as Android Builder.

6)Navigate to C/C++ build there in Builder Settings following should be mentioned

Build Directory should be : ${workspace_loc:/Project Name}/
Build Command : ndk - build

7)Build will be successful refer make file for any directory mismatch


One of the reason why I faced UnsatisfiedLinkError while trying to call native function is:

I have build JNIWrapper using the followinh Swig command

C:\swig\swigwin-2.0.11\swigwin-2.0.11>swig -c++ -java -package com.sampel D:\Pro
j-workspace\All_Projects\nativecodeproject\jni\API.i

All the wrappers got generated with the above package name.

I had a file with .cxx extension[which serves as a linkage between the Java and the Cpp code]
which plays a primary  role while invoking native functions.
This .cxx file is also generated by swig when I run the above command.

As per the make file Android makefile I shoul copy it and paste it in the target folder.
I missed out the above step and this lead to Error.

Note android make file instructions should be folloed carefully and .cxx file should be placed in their appropriate positions

Monday, 3 February 2014

Battery Usage

package com.example.batteryusage;

import android.os.BatteryManager;

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.widget.TextView;

/**
 * Used for finding the battery level of an Android-based phone.
 *
 *
 *
 */
public class BatteryLevelActivity extends Activity {
    /** Called when the activity is first created. */
    private TextView batterLevel;

    @Override
    /**
     * Called when the current activity is first created.
     */
    public void onCreate(Bundle icicle) {
        super.onCreate(icicle);
        setContentView(R.layout.activity_main);
        batterLevel = (TextView) this.findViewById(R.id.batteryLevel);
        batteryLevel();
    }

    /**
     * Android 2.0 or higher
     * Computes the battery level by registering a receiver to the intent triggered
     * by a battery status/level change.
     *
     * BatteryManager.Extra_Scale
        Integer containing the maximum battery level.
        BatteryManager.Extra_Level
        Integer field containing the current battery level, from 0 to EXTRA_SCALE.
     */
    private void batteryLevel() {
        BroadcastReceiver batteryLevelReceiver = new BroadcastReceiver() {
            public void onReceive(Context context, Intent intent) {
                context.unregisterReceiver(this);
                int rawlevel = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
                int scale = intent.getIntExtra(BatteryManager.EXTRA_SCALE, -1);
                int level = -1;
                if (rawlevel >= 0 && scale > 0) {
                    level = (rawlevel * 100) / scale;
                }
                batterLevel.setText("Battery Level Remaining: " + level + "%");
            }
        };
        IntentFilter batteryLevelFilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
        registerReceiver(batteryLevelReceiver, batteryLevelFilter);
    }
   
}

Monday, 27 January 2014

Android styles

1) Fetch the theme from manifest file
     getResources().getResourceEntryName(getApplicationInfo().theme)
2)Set the theme globally in the App based on the condition
           if(getResources().getResourceEntryName(getApplicationInfo().theme).equalsIgnoreCase("Theme.One"))
        {
           int brandStyle = R.style.settingsThemeAppone;
             setBrandStyle(brandStyle);
         }
        else
        {
           int brandStyle = R.style.settingsThemeApptwo;
            setBrandStyle(brandStyle);
        }

3)Declare in styles.xml the following
   <style name="settingsThemeAppone">
      <item name="attr/settingslist_home">@drawable/icon_settingslistone_home</item>
      <item name="attr/settingslist_aboutus">@drawable/icon_settingslistone_about</item>
      <item name="attr/settingslist_click">@drawable/icon_settingslistone_click</item>
      </style>

    <style name="settingsThemeApptwo">
  <item name="attr/settingslist_home">@drawable/icon_settingslisttwo_home</item>
  <item name="attr/settingslist_aboutus">@drawable/icon_settingslisttwo_about</item>
  <item name="attr/settingslist_click">@drawable/icon_settingslisttwo_click</item>
  </style>

 <style name="colorThemeAppone">
           <item name="attr/active_color">@color/colorAppone</item>
           <item name="attr/inactive_color">@color/viewApptwo</item>
                    
        </style>

<style name="colorThemeApptwo">
           <item name="attr/active_color">@color/colorApptwo</item>
           <item name="attr/inactive_color">@color/viewApptwo</item>
                  </style>


4)Declare in attr.xml the following

<declare-styleable name="settingsTheme" >
         
            <attr name="settingslist_home" format="reference" />
            <attr name="settingslist_aboutus" format="reference" />
            <attr name="settingslist_click" format="reference" />
                
         
          </declare-styleable>

 <declare-styleable name="colorTheme" >
         
            <attr name="active_color" format="color" />
            <attr name="inactive_color" format="color" />
                
          </declare-styleable>
5) Access and place the drawables

    TypedArray a = getContext().getTheme().obtainStyledAttributes(getDataModel().getBrandStyle(), new int[] {R.attr.settingslist_home});    
                int attributeResourceId = a.getResourceId(0, 0);
                return attributeResourceId;

TypedArray templevels = getContext().getTheme().obtainStyledAttributes(getDataModel().getBrandStyle(), new int[] {R.attr.settingslist_aboutus});    
                int attributeResourceIdtemplevels = templevels.getResourceId(0, 1);
                return attributeResourceIdtemplevels;   

6)Accessing colors

TypedArray a = getContext().getTheme().obtainStyledAttributes(
                dataModel.getBrandStyleColor(),
                new int[] { R.attr.inactive_color });
  
     
        int highlight_color = a.getColor(a.getIndex(0), 0);

    TypedArray a = getContext().getTheme().obtainStyledAttributes(
                dataModel.getBrandStyleColor(),
                new int[] { R.attr.active_color });
   

       
        int highlight_color = a.getColor(a.getIndex(0), 0);
       

       

Thursday, 19 December 2013

Remove non Ascii characters from strings

public class Sample {
    public static void main(String a[]){
        String str = "GHj��PL����AM�";
        System.out.println(str);
        str = str.replaceAll("[^\\p{ASCII}]", "");
        System.out.println("After removing non ASCII chars:");
        System.out.println(str);
    }
}
 System.out.println("here dec after con is "+decryptedContent.replaceAll("[^\\p{ASCII}]", "").trim());
OUTPUT
After removing non ASCII chars:
GHjPLAM 



Remove HTML Tags

public class HtmlTagRemover {
    public static void main(String a[]){
        String text = "<B>Remove tags<\\B>";
        System.out.println(text);
        text = text.replaceAll("\\<.*?\\>", "");
        System.out.println(text);
    }
}


OUTPUT
 "<B>Remove tags<\B>
Remove tags
 

  public class multipleSpaces {
    public static void main(String[] args) {
      
                String str = "String    With Multiple      Spaces";
                StringTokenizer st = new StringTokenizer(str, " ");
                StringBuffer sb = new StringBuffer();
                while(st.hasMoreElements()){
                    sb.append(st.nextElement()).append(" ");
                }
                System.out.println(sb.toString().trim());
            }
        }

 

 

 

Tuesday, 19 November 2013

Android pushNotification badge ICON similar to IOS


1.    Create a appwidget-provider xml name it as widget_badge_icon.xml and add it in xml folder
2.    Create a widget_badge_layout .xml as per need.
3.    Create a receiver in manifest file.
4.    Create BadgeNotificationWidget Class:


package com.example.testwidget;

import java.util.Timer;

import java.util.TimerTask;

import android.app.IntentService;
import android.appwidget.AppWidgetManager;
import android.content.ComponentName;
import android.content.Intent;
import android.util.Log;
import android.view.View;
import android.widget.RemoteViews;

/**
 * BadgeService is a worker thread used to send the badge number as a broadcast
 * message to change the app icon.
 *
 *
 */
public class BadgeService extends IntentService {

    int count = 0;

    Timer timer;

    int randomNo = 10;

    public BadgeService() {
        super("BadgeService");
        timer = new Timer();
    }

    /**
     * This method is invoked on the worker thread with a request to process.
     */
    @Override
    protected void onHandleIntent(final Intent intent) {

        RemoteViews remoteView = new RemoteViews(getApplicationContext()
                .getPackageName(), R.layout.widget_badge_layout);

        ComponentName componentName = new ComponentName(
                getApplicationContext(), BadgeNotificationWidgetActivity.class);

        AppWidgetManager appWidgetManager = AppWidgetManager
                .getInstance(getApplicationContext());

        Log.d("BadgeNotificationWidgetActivity", "BadgeService randomNo"
                + randomNo);
        if (randomNo == 0) {
            remoteView.setViewVisibility(R.id.badgeNum, View.GONE);
        } else {
            remoteView.setViewVisibility(R.id.badgeNum, View.VISIBLE);
        }

        remoteView.setTextViewText(R.id.badgeNum, String.valueOf(randomNo));
        // apply changes to widget
        appWidgetManager.updateAppWidget(componentName, remoteView);

    }
}






package com.example.testwidget;




import android.os.Bundle;

import android.app.Activity;
import android.content.Intent;
import android.view.Menu;

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

   
   
    @Override
    protected void onStart() {
        super.onStart();
        startService(new Intent(this, BadgeService.class));
    }
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

}




package com.example.testwidget;

import android.appwidget.AppWidgetManager;

import android.appwidget.AppWidgetProvider;
import android.content.ComponentName;
import android.content.Context;
import android.util.Log;
import android.widget.RemoteViews;

public class BadgeNotificationWidgetActivity extends AppWidgetProvider {

   

   

   

}





<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.testwidget"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="17" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/image"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.example.testwidget.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
       
        <service android:name=".BadgeService" >
        </service>
       
       
         <receiver
            android:name="com.example.testwidget.BadgeNotificationWidgetActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.appwidget.action.APPWIDGET_UPDATE" />
            </intent-filter>

            <meta-data
                android:name="android.appwidget.provider"
                android:resource="@xml/widget_badge_icon" />
        </receiver>
    </application>

</manifest>



badge_circle.xml


<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="oval" >

    <corners android:radius="10dip" />

    <solid android:color="#F00" />

    <stroke
        android:width="5dp"
        android:color="#FFF" />

    <padding
        android:bottom="8dp"
        android:left="10dp"
        android:right="10dp"
        android:top="8dp" />

</shape>

widget_badge_icon.xml


<?xml version="1.0" encoding="utf-8"?>
<appwidget-provider xmlns:android="http://schemas.android.com/apk/res/android"
    android:initialLayout="@layout/widget_badge_layout"
    android:minHeight="40dp"
    android:minWidth="40dp"
    android:updatePeriodMillis="30000" >

</appwidget-provider>


Following link contains source code   Sample Source

HTML Report using Lint

The following command is used to generate lint error report in android

On the command prompt redirect to the android---->sdk---->tools
Then type lint --html --sample pathoftheproject

HTML report gets generated in the sdk--->tools with the name --sample



TreeMap is an example of a SortedMap, which means that the order of the keys can be sorted, and when iterating over the keys, you can expect that they will be in order.

HashMap on the other hand, makes no such guarantee. Therefore, when iterating over the keys of a HashMap, you can't be sure what order they will be in.

HashMap will be more efficient in general, so use it whenever you don't care about the order of the keys.


Daemon thread in Java are those thread which runs in background and mostly created by JVM for performing background task like Garbage collection and other house keeping tasks. Difference between Daemon and Non Daemon(User Threads)  is also an interesting multi-threading interview question, which asked mostly on fresher level java interviews. In one line main difference between daemon thread and user thread is that as soon as all user thread finish execution java program or JVM terminates itself, JVM doesn't wait for daemon thread to finish there execution. As soon as last non daemon thread finished JVM terminates no matter how many Daemon thread exists or running inside JVM.


Read more: http://javarevisited.blogspot.com/2012/03/what-is-daemon-thread-in-java-and.html#ixzz2pyQBJtx4


 1) JVM doesn't wait for any daemon thread to finish before existing.

2) Daemon Thread are treated differently than User Thread when JVM terminates, finally blocks are not called, Stacks are not unwounded and JVM just exits.

Read more: http://javarevisited.blogspot.com/2012/03/what-is-daemon-thread-in-java-and.html#ixzz2pyR6S9Kt
 

Friday, 8 November 2013

Package name and App name

System.out.println("print here "+getApplicationContext().getPackageName());
        System.out.println("print here complete name "+getApplicationContext().getPackageName().concat("."+getApplicationContext().getString(getApplicationContext().getApplicationInfo().labelRes)));

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...