Thursday, February 21, 2013

Take Photo from Android Activity without Click Capture Button in android


I want take photo While clicking the Html button


  manifest.xml:
---------------


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

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

    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-feature android:name="android.hardware.camera" />
 <uses-feature android:name="android.hardware.camera.autofocus" />
    <uses-permission android:name="android.permission.VIBRATE" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_LOCATION_EXTRA_COMMANDS" />
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.RECEIVE_SMS" />
    <uses-permission android:name="android.permission.RECORD_AUDIO" />
    <uses-permission android:name="android.permission.RECORD_VIDEO" />
    <uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS" />
    <uses-permission android:name="android.permission.READ_CONTACTS" />
    <uses-permission android:name="android.permission.WRITE_CONTACTS" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.WRITE_INTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.GET_ACCOUNTS" />
    <uses-permission android:name="android.permission.BROADCAST_STICKY" />
    <uses-permission android:name="android.permission.WAKE_LOCK" />
    <uses-permission android:name="android.permission.READ_PHONE_STATE" />
    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".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>
     
     
            <activity
            android:name="com.asman.imagepicker.CameraActivity"
            android:label="@string/app_name" >
       
        </activity>
    </application>

</manifest>





Our Layout XML File


main.xml:
-----------



<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:orientation="vertical" android:layout_width="fill_parent"
  android:layout_height="fill_parent" android:id="@+id/layout">
  <!-- <1> -->
  <TextView android:layout_width="fill_parent"
    android:layout_height="wrap_content" android:text="@string/app_name"
    android:textSize="24sp" />
  <!-- <2> -->

  <FrameLayout
      android:id="@+id/preview"
      android:layout_width="80dp"
      android:layout_height="80dp" >

  </FrameLayout>
  <!-- <3> -->
  <!-- <Button android:layout_width="wrap_content"
    android:layout_height="wrap_content" android:id="@+id/buttonClick"
    android:text="Click" android:layout_gravity="center" /> -->
</LinearLayout>

MainActivity.java:


package com.asman.imagepicker;

import org.apache.cordova.DroidGap;

import android.os.Bundle;

public class MainActivity  extends  DroidGap{

@Override
 public void onCreate(Bundle savedInstanceState) {
   super.onCreate(savedInstanceState);
super.loadUrl("file:///android_asset/www/SampleImage.html");

}

}


Preview.java:
---------------


package com.asman.imagepicker;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import android.content.Context;
import android.hardware.Camera;
import android.hardware.Camera.PictureCallback;
import android.hardware.Camera.PreviewCallback;
import android.hardware.Camera.ShutterCallback;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;

class Preview extends SurfaceView implements SurfaceHolder.Callback { // <1>
  private static final String TAG = "Preview";

  SurfaceHolder mHolder;  // <2>
  public Camera camera; // <3>
  static int i=5;
  Preview(Context context) {
    super(context);

    // Install a SurfaceHolder.Callback so we get notified when the
    // underlying surface is created and destroyed.
    mHolder = getHolder();  // <4>
    mHolder.addCallback(this);  // <5>
    mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS); // <6>
  }

  // Called once the holder is ready
  public void surfaceCreated(SurfaceHolder holder) {  // <7>
    // The Surface has been created, acquire the camera and tell it where
    // to draw.
 
 
    camera = Camera.open(); // <8>
    try {
      camera.setPreviewDisplay(holder);  // <9>

      camera.setPreviewCallback(new PreviewCallback() { // <10>
        // Called for each frame previewed
        public void onPreviewFrame(byte[] data, Camera camera) {  // <11>
          Log.d(TAG, "onPreviewFrame called at: " + System.currentTimeMillis());
          Preview.this.invalidate();  // <12>
        }
      });
     
      this.camera.takePicture(shutterCallback, rawCallback, jpegCallback);
 
    } catch (IOException e) { 
      e.printStackTrace();
    }
 
  }

  // Called when the holder is destroyed
  public void surfaceDestroyed(SurfaceHolder holder) {  // <14>
    camera.stopPreview();
    camera = null;
   
  }

  // Called when holder has changed
  public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) { // <15>
    camera.startPreview();
  }
  
  
  public void onClick(View v) { // <5>
  } 
  // Called when shutter is opened
  ShutterCallback shutterCallback = new ShutterCallback() { // <6>
    public void onShutter() {
      Log.d(TAG, "onShutter'd");
    }
  };

  // Handles data for raw picture
  PictureCallback rawCallback = new PictureCallback() { // <7>
    public void onPictureTaken(byte[] data, Camera camera) {
      Log.d(TAG, "onPictureTaken - raw");
    }
  };

  // Handles data for jpeg picture
  PictureCallback jpegCallback = new PictureCallback() { // <8>
    public void onPictureTaken(byte[] data, Camera camera) {
      FileOutputStream outStream = null;
      try {
        // Write to SD Card
        outStream = new FileOutputStream(String.format("/sdcard/%d.jpg",
            System.currentTimeMillis())); // <9>
        outStream.write(data);
        outStream.close();
        Log.d(TAG, "onPictureTaken - wrote bytes: " + data.length);
      } catch (FileNotFoundException e) { // <10>
        e.printStackTrace();
      } catch (IOException e) {
        e.printStackTrace();
      } finally {
      }
      Log.d(TAG, "onPictureTaken - jpeg");
      
    }
  };

}






Open java Webapplication from java standlone application



I want open my java webaaplication from mian class.
esaily we can do following code




public class openWebapplication{
 
  public static void main(String args[])
  {
 String url = "http://localhost:2020/ICD_18_02";
 String os = System.getProperty("os.name").toLowerCase();
        Runtime rt = Runtime.getRuntime();
 
 try{
 
     if (os.indexOf( "win" ) >= 0) {
 
         // this doesn't support showing urls in the form of "page.html#nameLink" 
         rt.exec( "rundll32 url.dll,FileProtocolHandler " + url);
 
     } else if (os.indexOf( "mac" ) >= 0) {
 
         rt.exec( "open " + url);
 
            } else if (os.indexOf( "nix") >=0 || os.indexOf( "nux") >=0) {
 
         // Do a best guess on unix until we get a platform independent way
         // Build a list of browsers to try, in this order.
         String[] browsers = {"epiphany", "firefox", "mozilla", "konqueror",
                        "netscape","opera","links","lynx"};
 
         // Build a command string which looks like "browser1 "url" || browser2 "url" ||..."
         StringBuffer cmd = new StringBuffer();
         for (int i=0; i<browsers.length; i++)
             cmd.append( (i==0  ? "" : " || " ) + browsers[i] +" \"" + url + "\" ");
 
         rt.exec(new String[] { "sh", "-c", cmd.toString() });
 
           } else {
                return;
           }
       }catch (Exception e){
     return;
       }
      return;  
 
}

Monday, February 18, 2013

Get spring bean objects With java code


Here My applicationContext.xml:






<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">
<beans>

<!-- ...............DATASOURCE CONFIGURATION BEGIN.............. -->
<bean id="itDataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="net.sourceforge.jtds.jdbc.Driver" />
<!-- <property name="jdbcUrl"
   value="jdbc:jtds:sqlserver://XXXXX/ICD_TOOL_SCHEMA" /> -->

<property name="jdbcUrl"
   value="jdbc:jtds:sqlserver://XXX/ICD_TOOL_SCHEMA" />

<property name="properties">
<props>
<prop key="c3p0.acquire_increment">10</prop>
<prop key="c3p0.idle_test_period">100</prop>
<prop key="c3p0.max_size">500</prop>
<prop key="c3p0.max_statements">0</prop>
<prop key="c3p0.min_size">10</prop>
<prop key="c3p0.timeout">120</prop>
<prop key="c3p0.testConnectionOnCheckout">true</prop>
<prop key="c3p0.maxConnectionAge">14400</prop>
<prop key="c3p0.maxIdleTime">10000</prop>
<prop key="c3p0.maxIdleTimeExcessConnections">120</prop>
<!-- <prop key="user">asmanicd</prop>
<prop key="password">asman.123</prop> -->
<prop key="user">icddev</prop>
<prop key="password">icddev</prop>

</props>
</property>
</bean>
<bean id="icdDatabase" class="com.asman.itrans.action.OrganizationsAction">
<property name="asmanDataSource" ref="itDataSource"/>
</bean>
<!--
  .........................DATASOURCE CONFIGURATION
  END..................
 -->

<!--
  .......................HIBERNATE CONFIGURATION BEGIN.................
 -->
<bean id="itSessionFactory"
  class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="dataSource" ref="itDataSource" />
<property name="annotatedClasses">

<list>
<value>com.asman.itrans.to.common.Users</value>
<value>com.asman.itrans.to.common.Icd10DrgMapper</value>
<value>com.asman.itrans.to.common.FinancialReport</value>
<value>com.asman.itrans.to.common.Icd10ReimbursementMap</value>
<value>com.asman.itrans.to.common.MasterNoMap</value>
<value>com.asman.itrans.to.common.UserType</value>


</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect"> org.hibernate.dialect.SQLServerDialect</prop>
<!-- <prop key="hibernate.show_sql">true</prop> -->
<!--  <prop key="hibernate.cache.provider_class"> net.sf.ehcache.hibernate.EhCacheProvider</prop>
<prop key="hibernate.cache.region.factory_class">net.sf.ehcache.hibernate.EhCacheRegionFactory</prop>
<prop key="hibernate.cache.provider_configuration_file_resource_path">/WEB-INF/classes/ehcache.xml</prop> -->
</props>
</property>
</bean>
<!-- ............. HIBERNATE CONFIGURATION END................ -->

<!-- .................. ACTION *** BEGIN....................... -->
<bean id="importAction" class="com.asman.itrans.action.ImportDataAction"
  singleton="false">
<property name="organizationService" ref="organizationService">
</property>
<property name="serviceLineService" ref="serviceLineService">
</property>  
</bean>
<bean id="loginAction" class="com.asman.itrans.action.LoginAction">

<property name="usersService" ref="usersService">
</property>

<property name="organizationService" ref="organizationService">
</property>

<property name="loginService" ref="loginService">
</property>

<property
            name="databaseService"
            ref="databaseService" >
</property>


</bean>

<
   
     
   
     


 <!--
  ................... ACTION *** END...............................
 -->

<!-- SERVICE *** BEGIN -->
<!-- <bean id="importservice" class="com.asman.itrans.service.ImportDataService"
  singleton="false">
<property name="importdao" ref="importdao"></property>
<property name="sessionFactory" ref="itSessionFactory"></property>
</bean> -->
<bean id="loginService" class="com.asman.itrans.service.LoginService">

<property name="usersHome" ref="usersHome">
</property>

<property name="sessionFactory" ref="itSessionFactory">
</property>
</bean>

<bean id="usersService" class="com.asman.itrans.service.UsersService">

<property name="usersHome" ref="usersHome">
</property>

<property name="sessionFactory" ref="itSessionFactory">
</property>
</bean>

<bean id="adminService" class="com.asman.itrans.service.AdminService">

<property name="usersHome" ref="usersHome">
</property>

<property name="sessionFactory" ref="itSessionFactory">
</property>
</bean>

<
     

     
 <!-- SERVICE *** END -->

<!-- ...........DAO *** BEGIN................................ -->
<!--  <bean id="importdao" class="com.asman.itrans.dao.ImportDataDao" /> -->

<bean id="usersHome" class="com.asman.itrans.common.dao.UsersHome" />

<bean id="organisationHome" class="com.asman.itrans.common.dao.OrganisationHome" />

<bean id="serviceLineHome" class="com.asman.itrans.common.dao.ServiceLineHome" />


<!-- ..... DAO *** END...... -->

</beans>





Now We want get any spring bean object.just integrate this code

YourJava Class:

ApplicationContext appContext = new ClassPathXmlApplicationContext();
Resource resource;
resource = appContext.getResource("classpath:/applicationContext.xml");

XmlBeanFactory factory = new XmlBeanFactory(resource);

System.out.println(factory.getBean("icdDatabase"));


Here We get OrganizationsAction object
OrganizationsAction orgaction=(OrganizationsAction)factory.getBean("icdDatabase")

Here we get OrganizationService object
OrganizationService source = (OrganizationService) factory
.getBean("organizationService");

like we will get any object from spring application context




</div>

Thursday, February 7, 2013

Call JavaScript inside WebView from Android activity, with parameter passed.




Sending Values Android Activity to Javascript have two solutiions

they are  1).Using Webview Object
              2).Using loadUrl Method



Solutions 1:

send values from Android activity to javascript function it is not difficult.just follow these steps

Step1: First create webview object in android layout
------
           
main.xml:     <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
                     xmlns:tools="http://schemas.android.com/tools"
                     android:layout_width="match_parent"
                     android:layout_height="match_parent"
                     tools:context=".BeWithMeActivity" >
<!-- Here created webview object-->
                  <WebView
                   android:id="@+id/webview"
                   android:layout_width="fill_parent"
                   android:layout_height="fill_parent" />
    
                  <TextView
                   android:layout_width="wrap_content"
                   android:layout_height="wrap_content"
                   android:layout_centerHorizontal="true"
                   android:layout_centerVertical="true"
                   android:text="@string/hello_world" />

               </RelativeLayout>


------

Step2:
                     Below code configured where we want call the javascript function

package com.asman.bwithme;
import org.apache.cordova.DroidGap;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.view.Menu;
import android.view.MenuItem;
import android.webkit.WebView;
import android.support.v4.app.NavUtils;

public class MainActivity extends DroidGap {

public WebView myWebView ;
 static String message;
 
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Intent intent = getIntent();
        message = intent.getStringExtra(GCMIntentService.EXTRA_MESSAGE);
        System.out.println("message:::"+message);
        setContentView(R.layout.activity_main);
      //This code related calling javascript function
        myWebView = (WebView) findViewById(R.id.webview);
        myWebView.getSettings().setJavaScriptEnabled(true);
        myWebView.loadUrl("file:///android_asset/www/pushnotification.html");
        final MyJavaScriptInterface myJavaScriptInterface = new MyJavaScriptInterface(this);
        
   myWebView.addJavascriptInterface(myJavaScriptInterface, "AndroidFunction");
      
    
   }
   /** Responsible to call java script method
    * 
    *
    *
    */
   public class MyJavaScriptInterface {
   Context mContext;

      MyJavaScriptInterface(Context c) {
          mContext = c;
      }
  
      public void showToast(){
       System.out.println(message);
       myWebView.loadUrl("javascript:callFromActivity('" + message + "');");
      
          
      }
     
    
  }
}



             Here created Html page and javascript function

pushnotification.html:


step3:
---------------------
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Push Notification</title>
<script type="text/javascript" src="js/cordova-2.0.0.js"></script>
<script type="text/javascript" src="jquery.mobile-1.2.0/js/jquery.js"></script>
<script type="text/javascript" src="jquery.mobile-1.2.0/js/jquery.mobile-1.2.0.js"></script>
<script type="text/javascript" src="js/push.js"></script>
<link rel="stylesheet" href="jquery.mobile-1.2.0/css/jquery.mobile.structure-1.2.0.css" />       
        <link rel="stylesheet" href="jquery.mobile-1.2.0/css/jquery.mobile-1.2.0.css" />
      <link rel="stylesheet" href="css/main.css" />  
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false&libraries=places">



function sendGcmIdToJS(){
AndroidFunction.showToast();
}

function callFromActivity(msg) {
//$("#mydiv").prepend(msg);
//document.getElementById("mydiv").value = msg;
 gcmId = id;
}




</script> 
       
</head>
<body onload="sendGcmIdToJS()">
<header class="title"> Banner </header>
<div data-role="button" data-inline="true" data-theme="b" class="role" onclick="accept()">Accept</div><br>
<!-- <p id="mydiv">data from notification::</p> -->
<input type="text" id="mydiv" style="width: 500px;height: 30px;"/>
<div data-role="button" data-inline="true" data-theme="b" class="role" onclick="denny()">Denny</div><br> 
<div id="dvTraceMap"></div>
</body>
</html>



Solution2:
-------------


Using super.loadUrl() method we can achive this functionality



My Activity.java:
----------------------


import org.apache.cordova.DroidGap;

import android.os.Bundle;

import android.view.Menu;

public class MainActivity extends DroidGap {

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

             String Data="sending values to javascript";
  super.loadUrl("file:///android_asset/www/uploadPhoto.html?param="+Data);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}


uploadPhoto.html:
--------------------------



<!DOCTYPE html>

<html>

<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Vote My Paint</title>
<script src="jquery.mobile-1.2.0/js/jquery.js"></script>
<script type="text/javascript" charset="utf-8" src="js/cordova-2.0.0.js"></script>
<!-- <script type="text/javascript" src="js/analytics.js"></script> -->

<link href="css/style_ipad.css" rel="stylesheet" type="text/css" />

<!-- <script type="text/javascript" charset="utf-8" src="js/InAppPurchaseManager.js"></script>
        <script type="text/javascript" charset="utf-8" src="js/asmanPlugin.js"></script> -->


<script type="text/javascript">
function pathInfoFromActivity()
          {
        var data=  getURLParameters("param");
alert(data);

           }


       function getURLParameters(paramName) 
{
var sURL = window.document.URL.toString();
if (sURL.indexOf("?") > 0)
{
var arrParams = sURL.split("?"); 
var arrURLParams = arrParams[1].split("&");
var arrParamNames = new Array(arrURLParams.length);
var arrParamValues = new Array(arrURLParams.length);
var i = 0;
for (i=0;i<arrURLParams.length;i++)
{
var sParam =  arrURLParams[i].split("=");
arrParamNames[i] = sParam[0];
if (sParam[1] != "")
arrParamValues[i] = unescape(sParam[1]);
else
arrParamValues[i] = "No Value";
}
for (i=0;i<arrURLParams.length;i++)
{
   if(arrParamNames[i] == paramName){
//alert("Param from activity:"+arrParamValues[i]);
return arrParamValues[i];
}
}
return "No Parameters Found";
}
}

</script>
</head>

<body onload="pathInfoFromActivity()">
</body>
</html>