Thursday, 11 July 2013

Use jquery to prevent double submit


Recently, I was engaged in a web development project. We have encounted the very famous old problem of double submit in web application. Actually, we have many ways to solve it. We can prevent the double submit on server side. However, we do it in client side this time.

Here, I summarized two method of of preventing double submit in client side javascript.

(1) For html button, we can use jquery to disabled the button. Example code is shown here:

<input type="button" value="Click"id="subBtn"/>  
<script type="text/javascript">  

$("#subBtn").click(function(){  
   // Disabled the button
   $(this).attr("disabled","disabled");  
   
   //execute your function e.g. submit a form
   myFunc();  
});

function myFunc(){  
    // ...
    // code
    // ...
    // execute your logic here
    // remove the diabled  attribute and re-enabled the button again
    $("#subBtn").removeAttr("disabled");  
}  
  
</script> 


(2) For html anchor, we can use redirect the event handler of the anchor to another function after the first click.

<a href="javascript:;" onclick="return funcOne();">Click</a>  
<scripttypescripttype="text/javascript">  
function funcOne(){  
    alert("Clickthe button!");  

   //After the first click, funcTwo will be assined to funcOne.
    funcOne=funcTwo;  
    return false;  
}  
function funcTwo(){  
 //function two will not do anything
    return false;  
}  
</script>


Wednesday, 10 July 2013

Microsoft’s Reorganization Plan

>
Microsoft is expected to announce a major reorganization of its management structure on Thursday. The changes will shift the duties and responsibilities of many top Microsoft executives and are intended to eliminate overlap within the 98,000-employee company, AllThingsD reported on Monday, citing anonymous sources.

A new cloud computing and business-focused products unit would be headed by Satya Nadella, who currently oversees Microsoft's server business, according to a Bloomberg report last week. Julie Larson-Green, the current co-head of Microsoft's Windows operating system business, will lead the company's hardware efforts, including the Xbox video game console and the Surface tablets, Bloomberg said.

Chief Executive Steve Ballmer remains under pressure to ramp up Microsoft's presence on mobile devices as the computer industry steadily declines.

Ballmer announced in his annual letter to shareholders last October that Microsoft now sees itself as a "devices and services" company, rather than a software maker.

The company's last significant reorganization came in July 2008 when Ballmer split Microsoft's Platforms & Services Division into three units - Windows, Online Services and Server and Tools.

Microsoft's shares have gained almost 30 percent this year, helped by a rally that began in late April when the company released strong revenue and earnings in what was one of the worst quarters for PC sales on record.

But consumers are increasingly turning to mobile devices such as smartphones and tablets instead of traditional PCs and the shrink-wrapped software products that are the foundation of Microsoft's $74 billion annual revenue business.

Under the new structure, Qi Lu, the head of Microsoft's money-losing online group, would also oversee Microsoft Office as well as other apps, Bloomberg said. Tony Bates would oversee Microsoft's business development efforts, including mergers and acquisitions and corporate strategy.

"What they have has worked for the past and led to some pretty profitable businesses, but when people are aligned with certain goals they may not be thinking the right way for the future," David Smith, an analyst with industry research firm Gartner said on Monday about the widely expected reorganization.

Tuesday, 9 July 2013

Andoird Development Example: AutoCompleteTextView and MultiAutoCompleteTextView



Dynamic auto complete for input text can be archived by AutoCompleteTextView. Here's an example to illustrate the usage of AutoCompleteTextView.

(1) layout.xml
< AutoCompleteTextView  
        Android: ID = "@ + ID / Auto"  
        Android: layout_width = "wrap_content"  
        Android: layout_height = "wrap_content"  
        Android: layout_alignParentLeft = "true"  
        Android: layout_alignParentRight = "true"  
        Android: layout_below = "@ + id/textView1"  
        Android: layout_marginTop = "20DP"  
        Android: EMS = "10"  >  
  
        < requestFocus  />  
    </ AutoCompleteTextView > 

< MultiAutoCompleteTextView  
        Android: ID = "@ + ID / multiAuto"  
        Android: layout_width = "wrap_content"  
        Android: layout_height = "wrap_content"  
        Android: layout_alignParentLeft = "true"  
        Android: layout_alignRight = "@ + ID / Auto"  
        Android: layout_below = "@ + id/textView2"  
        Android: layout_marginTop = "19dp"  
        Android: EMS = "10"  />  


(2) Main activity
package com.example.autocomplete;  
  
import android.app.Activity;  
import android.os.Bundle;  
import android.view.Menu;  
import android.widget.ArrayAdapter;  
import android.widget.AutoCompleteTextView;  
import android.widget.MultiAutoCompleteTextView;  
  
public class MainActivity extends Activity {  
    private AutoCompleteTextView auto;  
    private MultiAutoCompleteTextView mulAuto;  
    @Override  
    protected void onCreate(Bundle savedInstanceState) {  
        super.onCreate(savedInstanceState);  
        setContentView(R.layout.activity_main);  
        auto=(AutoCompleteTextView) findViewById(R.id.auto);  
        mulAuto= (MultiAutoCompleteTextView) findViewById(R.id.multiAuto);  
        String[] autoStrings = new String[] { "Google Map", "Google", "Google Drive","Google Doc",  
                "java", "javaweb","javascript" };  
        
        ArrayAdapter adapter = new ArrayAdapter(MainActivity.this,  
                android.R.layout.simple_dropdown_item_1line, autoStrings);  
        auto.setAdapter(adapter);  
        mulAuto.setAdapter(adapter);  
       
        mulAuto.setTokenizer(new MultiAutoCompleteTextView.CommaTokenizer());  
    }  
  
    @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;  
    }  
  
}  

IOS7 Beta 3 version: Interface fine tuning



Apple just released iOS 7 third developer beta version. There are many small adjuestments on the system interface design.

Font redesign:

IOS beta 3 choose a new font type. It uses the "normal" Helvetica Neue font. Therefore, you will discovered the font in your SMS interface seems to be being bolded. This change is appied to in weather, nortification and settings interfaces.

Status bar:

On the lock screen, the icon size in the status bar including signal strength, WiFi, Bluetooth, batteries has been increased.

Lock screen :

When playing music, lock screen can also display the time.

Calendar :

In calendar mode, there will be gray dots when there are events on that date .

Siri :

Siri's voice sounds more natural now.

Download Animation :

When download and install the application, the progress indicator change to a clock style.

Control Center :

AirPlay can display the currently connected device.

Monday, 8 July 2013

Android Example: Creating 4 different Tween Animation effects

Android platform facilitates three different types of animation you can define in your application resources: property, tween and frame. In this example, we show you how to do 4 different tween animation effect.

(1) create activity
package com.easyinfogeek;  
import android.app.Activity;  
import android.os.Bundle;  
import android.util.Log;  
import android.view.View;  
import android.view.View.OnClickListener;  
import android.view.animation.AlphaAnimation;  
import android.view.animation.Animation;  
import android.view.animation.AnimationSet;  
import android.view.animation.AnimationUtils;  
import android.view.animation.ScaleAnimation;  
import android.view.animation.TranslateAnimation;  
import android.view.animation.Animation.AnimationListener;  
import android.view.animation.RotateAnimation;  
import android.widget.Button;  
import android.widget.ImageView;  
public class AnimationDemoActivity extends Activity {  
    private ImageView imageView;  

    // define animationType enum
    enum AnimationType{  
        Alpha,  
        Rotate,  
        Scale,  
        Translate,  
        Complex  
    } 

    /** Called when the activity is first created. */  
    @Override  
    public void onCreate(Bundle savedInstanceState) {  
        super.onCreate(savedInstanceState);  
        setContentView(R.layout.main);  

        //define 4 button for each tween animation 
        imageView = (ImageView)findViewById(R.id.imageView);  
        Button alpha = (Button)findViewById(R.id.Alpha);  
        alpha.setOnClickListener(new AnimationClickListener(AnimationType.Alpha));  
        Button rotate = (Button)findViewById(R.id.Rotate);  
        rotate.setOnClickListener(new AnimationClickListener(AnimationType.Rotate));  
        Button scale = (Button)findViewById(R.id.Scale);  
        scale.setOnClickListener(new AnimationClickListener(AnimationType.Scale));  
        Button translate = (Button)findViewById(R.id.Translate);  
        translate.setOnClickListener(new AnimationClickListener(AnimationType.Translate));  
        Button complex = (Button)findViewById(R.id.Complex);  
        complex.setOnClickListener(new AnimationClickListener(AnimationType.Complex));  
    }  
  
     

    // create a listener inner class
    class AnimationClickListener implements OnClickListener{  
        private AnimationType animationType;  
        public AnimationClickListener(AnimationType animType){  
            animationType = animType;  
        }  
        public void onClick(View v) {  
            // TODO Auto-generated method stub  
            switch (animationType) {  
            case Alpha:  

                //Alpha animation. repeat 5 times, last for 1 mins                 
                AlphaAnimation alphaAnimation = (AlphaAnimation)AnimationUtils.loadAnimation(AnimationDemoActivity.this, R.anim.alpha);  
                imageView.startAnimation(alphaAnimation);  
                break;  
            case Rotate:  
                //rotate animation
                RotateAnimation rotateAnimation = new RotateAnimation(0, 360, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);  
                rotateAnimation.setDuration(3000);  
                rotateAnimation.setRepeatCount(3);  
                //start animation 
                imageView.startAnimation(rotateAnimation);  
                break;  
            case Scale:  
                //scale animation
                ScaleAnimation scaleAnimation = new ScaleAnimation(1, 1.5f, 1, 1.5f, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);  
                scaleAnimation.setDuration(3000);  
                scaleAnimation.setRepeatCount(3);  
                //start animation 
                imageView.startAnimation(scaleAnimation);  
                break;  
            case Translate:  
                //translate animation
                TranslateAnimation translateAnimation = new TranslateAnimation(Animation.RELATIVE_TO_SELF, 0, Animation.RELATIVE_TO_SELF, 2, Animation.RELATIVE_TO_SELF, 0, Animation.RELATIVE_TO_SELF, 2);  
                translateAnimation.setDuration(3000);  
                translateAnimation.setRepeatCount(3);  
                //start animation 
                imageView.startAnimation(translateAnimation);  
                break;  
  
            case Complex:  
                //four animation overlap
                AnimationSet sets = new AnimationSet(false);  
                
                AlphaAnimation _animation1 = new AlphaAnimation(1f, 0.1f);  
                _animation1.setDuration(3000);  
                
                RotateAnimation rotateAnimation1 = new RotateAnimation(0, 360, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);  
                rotateAnimation1.setDuration(3000);  
                
                ScaleAnimation scaleAnimation1 = new ScaleAnimation(1, 1.5f, 1, 1.5f, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);  
                scaleAnimation1.setDuration(3000);  
                
                TranslateAnimation translateAnimation1 = new TranslateAnimation(Animation.RELATIVE_TO_SELF, 0, Animation.RELATIVE_TO_SELF, 2, Animation.RELATIVE_TO_SELF, 0, Animation.RELATIVE_TO_SELF, 2);  
                translateAnimation1.setDuration(3000);  
                
                sets.addAnimation(_animation1);  
                sets.addAnimation(rotateAnimation1);  
                sets.addAnimation(scaleAnimation1);  
                sets.addAnimation(translateAnimation1);  
                imageView.startAnimation(sets);  
                break;  
            default:  
                break;  
            }  
        }  
    }  
}  

(2) create layout.xml
<?xml version="1.0" encoding="utf-8"?>  
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
    android:layout_width="fill_parent"  
    android:layout_height="fill_parent"  
    android:orientation="vertical" >  
    <TextView  
        android:layout_width="fill_parent"  
        android:layout_height="wrap_content"  
        android:text="@string/hello" />  
    <ImageView  
        android:id="@+id/imageView"  
        android:layout_width="wrap_content"  
        android:layout_height="wrap_content"  
        android:src="@drawable/qa" />  
    <Button  
        android:id="@+id/Alpha"  
        android:layout_width="wrap_content"  
        android:layout_height="wrap_content"  
        android:text="Alpha" />  
    <Button  
        android:id="@+id/Rotate"  
        android:layout_width="wrap_content"  
        android:layout_height="wrap_content"  
        android:text="Rotate" />  
    <Button  
        android:id="@+id/Scale"  
        android:layout_width="wrap_content"  
        android:layout_height="wrap_content"  
        android:text="Scale" />  
    <Button  
        android:id="@+id/Translate"  
        android:layout_width="wrap_content"  
        android:layout_height="wrap_content"  
        android:text="Translate" />  
    <Button  
        android:id="@+id/Complex"  
        android:layout_width="wrap_content"  
        android:layout_height="wrap_content"  
        android:text="Complex" />  
</LinearLayout>  

(3) create alpha.xml resource file
<?xml version="1.0" encoding="utf-8"?>  
<alpha   
    xmlns:android="http://schemas.android.com/apk/res/android"  
    android:fromAlpha="1" android:toAlpha="0.3" android:duration="2000" android:repeatCount="3">  
</alpha>

SkyDrive supported Photosynth panorama view

Recently there are users find the current SkyDrive.com has full support for Photosynth interactive panorama view .

In the Windows 8.1 pre-release version, the camera application has the icon of panorama photo shoot. After taking the photo, we can synchronized the photo from Windows 8.1 to SkyDrive.

However, it currently does not support the kind of pictures like Bing smap street view.
Now, we can use the following methods for viewing Photosynth panorama shot:
1. browser version of SkyDrive
2. Windows8.1 Photo Application
3. Photosynth browser version
4. Windows Phone or iOS application of Photosynth

Nokia "Amber" Lumia update will add support for Bluetooth 4.0

According to latest leaked document, Nokia will provide Amber update for all WP8 Lumia model next month. The upcoming "Amber" update will add Bluetooth 4.0 feature support for Lumia 520,620,720 and also provide FM radio function for them.

The sources said that, after the "Amber" upgrade, Lumia models will increase support for low-power Bluetooth technology. This can be used for equipment of heart rate monitors, fitness monitors and temperature sensors.

In addition to Bluetooth 4.0 and FM radio support, Smart Camera will also be accompanied by the this upgrade. Thus, the "Amber" update improve the photo taking by the mobile phone significantly.

The leaked document show that the picture quality improve a lot by this upgrade. The picture is more clear, colors are more full.

Sunday, 7 July 2013

5.7-inch or 5.9-inch? Galaxy Note 3 Screen size remained a mystery


Recently, there are many rumors regardings the screen size of Galaxy Note 3. It is said that Galaxy Note 3 will be equipped with a 5.99-inch touch screen. But according to the Koreaherald, South Korean media, recently reported that Galaxy Note 3 screen is not so large.

Koreaherald said that, Galaxy Note 3 ,instead of 5.9-inch screen, actually use a 5.7-inch screen. The site did not disclose Note 3 of the resolution, but according to the most rencent news, it should be 1920 × 1080.

In fact, this is not the first time we heard that the Galaxy Note 3 will increase to 5.7 inch screen size. Last month , @evleaks on twitter said that Galaxy Note 3 will be equipped with a screen size of 5.7 inches. However, after the posting of koreaherald, the screen size of Galaxy Note 3 become mystery again.

Moreover, koreaherald disclosed that, Galaxy Note 3 will be officially unveiled at IFA 2013 Conference at September this year. We may know the answer at September this year.

Saturday, 6 July 2013

Moto X Phone will be released on July 11?

Today, there are a number of news said that Motorola will released the long-rumored X Phone, the Moto X, on July 11

The message came from the CNET tech news reporter Leo Laporte. He said that Google has invited 50 reporters to participate in mini-conference from the July 10 to July 11. And Leo Laporte is one of an invited reporters .

So, Leo Laporte think that the protagonist of the conference will be Moto X.

However, the CNET has updated their news, said that although they are guessing Moto conference next week will release Moto X, the focus of the conference is to emphasize that the Motorola becomes a company under Google.

Let's looking forward to the conference on July 11.

Full example of using Fragment in Android Development

Fragment in Android is very useful for responsive layout design. In the post, I will give you a full detailed example of using FramentActivity in android application development.

We will produce a demo application which have two different layouts in different device.


(1) Let's see the vertical layout first. We use FrameLayout to hold two fragment of LinearLayout container.
<FrameLayout 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" >  
      
     
    <LinearLayout   
        android:id="@+id/list_container"  
        android:layout_width="match_parent"  
        android:layout_height="match_parent">  
    </LinearLayout>  
      
      
    
    <LinearLayout   
        android:id="@+id/detail_container"  
        android:layout_width="match_parent"  
        android:layout_height="match_parent">  
    </LinearLayout>  
  
</FrameLayout>  
(2) For landscape layout, we create a layout-land folder under the res folder. Then we create the same layout.xml
<LinearLayout 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" >  
      
    
    <LinearLayout   
        android:id="@+id/list_container"  
        android:layout_width="match_parent"  
        android:layout_height="match_parent"  
        android:layout_weight="2">  
    </LinearLayout>  
      
      
    
    <LinearLayout   
        android:id="@+id/detail_container"  
        android:layout_width="match_parent"  
        android:layout_height="match_parent"  
        android:layout_weight="1">  
    </LinearLayout>  
  
</LinearLayout>  
(3) create a new fragment which contains a ListView to show the master data.
package com.easyinfogeek.fragmentExample;  
  
import java.util.ArrayList;  
import java.util.List;  
  
import android.content.res.Configuration;  
import android.os.Bundle;  
import android.support.v4.app.Fragment;  
import android.support.v4.app.FragmentManager;  
import android.support.v4.app.FragmentManager.OnBackStackChangedListener;  
import android.support.v4.app.FragmentTransaction;  
import android.view.LayoutInflater;  
import android.view.View;  
import android.view.ViewGroup;  
import android.widget.AdapterView;  
import android.widget.AdapterView.OnItemClickListener;  
import android.widget.ArrayAdapter;  
import android.widget.ListView;  
import android.widget.Toast;  
  
/** 
 * 
 * @author easinfogeek.com 
 * 
 */  
public class FragmentList extends Fragment {  
      
    private List<String> mDataSourceList = new ArrayList<String>();  
    private List<FragmentTransaction> mBackStackList = new ArrayList<FragmentTransaction>();  
  
  
    @Override  
    public View onCreateView(LayoutInflater inflater, ViewGroup container,  
            Bundle savedInstanceState) {  
        return inflater.inflate(R.layout.fragment_list_layout, container, false);  
    }  
      
      
    @Override  
    public void onActivityCreated(Bundle savedInstanceState) {  
        super.onActivityCreated(savedInstanceState);  
          
        //add data to ListView  
        for(int i=0, count=20; i<count; i++){  
            mDataSourceList.add("列表数据" + i);  
        }  
          
        
        ListView listView = (ListView) getActivity().findViewById(R.id.fragment_list);  
        listView.setAdapter(new ArrayAdapter(getActivity(), android.R.layout.simple_list_item_1, mDataSourceList));  
          
        listView.setOnItemClickListener(new OnItemClickListener() {  
  
            @Override  
            public void onItemClick(AdapterView<?> parent, View view,  
                    int position, long id) {  
                //create a Fragment  
                Fragment detailFragment = new FragmentDetail();  
                  
              
                Bundle mBundle = new Bundle();  
                mBundle.putString("arg", mDataSourceList.get(position));  
                detailFragment.setArguments(mBundle);  
                  
                final FragmentManager fragmentManager = getActivity().getSupportFragmentManager();  
                final FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();  
                  
                //check if the device is landscape or portrait 
                Configuration configuration = getActivity().getResources().getConfiguration();  
                int ori = configuration.orientation;  
                  
                fragmentTransaction.replace(R.id.detail_container, detailFragment);  
                  
                if(ori == configuration.ORIENTATION_PORTRAIT){  
                    fragmentTransaction.addToBackStack(null);  
                }  
                  
                fragmentTransaction.commit();  
                  
                  
            }  
        });  
          
    }  
      
    /** 
     *  
     * @param msg 
     */  
    private void showTost(String msg){  
        Toast.makeText(getActivity(), msg, Toast.LENGTH_LONG).show();  
    }  
  
}  
(4) Create a detail fragment which show the detail of each record
package com.easyinfogeek.fragmentExample;  
  
import java.util.ArrayList;  
import java.util.List;  
  
import android.content.res.Configuration;  
import android.os.Bundle;  
import android.support.v4.app.Fragment;  
import android.view.LayoutInflater;  
import android.view.View;  
import android.view.ViewGroup;  
import android.widget.ArrayAdapter;  
import android.widget.LinearLayout;  
import android.widget.ListView;  
  
/** 
 * 
 * @author easinfogeek.com 
 * 
 */  
public class FragmentDetail extends Fragment {  
  
    @Override  
    public View onCreateView(LayoutInflater inflater, ViewGroup container,  
            Bundle savedInstanceState) {  
        return inflater.inflate(R.layout.fragment_detail_layout, container, false);  
    }  
      
      
    @Override  
    public void onActivityCreated(Bundle savedInstanceState) {  
        super.onActivityCreated(savedInstanceState);  
          
        //get the data from the master list  
        Bundle bundle = getArguments();  
        String data = bundle.getString("arg");  
          
        List<String> list = new ArrayList<String>();  
        for(int i=0, count=20; i<count; i++){  
            list.add(data);  
        }  
          
        LinearLayout layout = (LinearLayout) getActivity().findViewById(R.id.detail_container);  
          
        ListView listView = (ListView) getActivity().findViewById(R.id.fragment_detail);  
        listView.setAdapter(new ArrayAdapter(getActivity(), android.R.layout.simple_list_item_1, list));  
          
        Configuration configuration = getActivity().getResources().getConfiguration();  
        int ori = configuration.orientation;  
      
    }  
  
}  
(5) Finally, create the activiy for the application
package com.easyinfogeek.fragmentExample;  
  
import android.os.Bundle;  
import android.support.v4.app.Fragment;  
import android.support.v4.app.FragmentActivity;  
import android.support.v4.app.FragmentManager;  
import android.support.v4.app.FragmentTransaction;  
  
public class MainActivity extends FragmentActivity {  
  
    @Override  
    protected void onCreate(Bundle savedInstanceState) {  
        super.onCreate(savedInstanceState);  
        setContentView(R.layout.activity_main);  
          
        /Master data list Fragment  
        Fragment listFragment = new FragmentList();  
          
        FragmentManager fragmentManager = getSupportFragmentManager();  
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();  
        fragmentTransaction.add(R.id.list_container, listFragment);  
          
        fragmentTransaction.commit();  
    }  
  
      
  
}  

Hibernate Many to One Mapping example

In this post, I will show you a simple example of many to one relationship in Hibernate mapping. In this example, one user is belong to a group. A group contains many user
package com.easyinfogeek.hibernate;  
public class Group {  
    private int id;  
    private  String name;  
    .....
    // setting and getter is ignore here

}  
package com.easyinfogeek.hibernate;  
public class User {  
    private int id;  
    private String name;  
    private Group group;  
    .....
    // setting and getter is ignore here
 }
 <!DOCTYPE hibernate-mapping PUBLIC   
    "-//Hibernate/Hibernate Mapping DTD 3.0//EN"  
    "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">  
<hibernate-mapping>  
    <class name="com.easyinfogeek.hibernate.Group" table="t_group">  
        <id name="id">  
            <generator class="native" />  
        </id>  
        <property name="name" />  
    </class>  
</hibernate-mapping> 
<?xml version="1.0"?>  
<!DOCTYPE hibernate-mapping PUBLIC   
    "-//Hibernate/Hibernate Mapping DTD 3.0//EN"  
    "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">  
<hibernate-mapping>  
    <class name="com.easyinfogeek.hibernate.User" table="t_user">  
        <id name="id">  
            <generator class="native" />  
        </id>  
        <property name="name" />  
                <!-- many-to-one groupid-->  
                <many-to-one name="group" column="groupid" cascade="save-update" />  
    </class>  
</hibernate-mapping> 

Using LocalBroadcastManager solve security issue of BroadcastReceiver


BroadcastReceiver in Android is designed is to facilitate comunication betweeon different applications. Therefore, secuirty issue may exists if the communication is intend for a single application only. Normally , you can solve by:

(1) Specify the permission of the receiver in sendBroadcast(Intent, String) method
(2) Use Intent.setPackage to assign the target of the broadcast

Actually, there is another method to get rid of the security issue. Android v4 compatibility package provides android.support.v4.content.LocalBroadcastManager. This helps you to perform broadcast within you own application.

LocalBroadcastManager mLocalBroadcastManager;    
  BroadcastReceiver mReceiver;    
  
  
 IntentFilter filter =  new  IntentFilter();    
 filter.addAction( "test" );    


 mReceiver =  new  BroadcastReceiver() {    
            @Override    
            public  void  onReceive(Context context, Intent intent) {    
                if  (intent.getAction().equals( "test" )) {    
                    //Do Something  
                }   
            }    
        };

mLocalBroadcastManager.registerReceiver(mReceiver, filter);          


unregistered it in the onDestroy method:
 @Override  
protected  void  onDestroy() {  
  
   super .onDestroy();  
  
   mLocalBroadcastManager.unregisterReceiver(mReceiver);  
  
}
Friday, 5 July 2013

Android ‘Master Key’ Security Hole



Mobile security startup Bluebox Security has unearthed a vulnerability in Android’s security model which it says means that the nearly 900 million Android phones released in the past four years could be exploited, or some 99% of Android devices.

This security loophole could be exploited to let an attacker do what they want to a phone including stealing data, eavesdropping or using it to send junk messages.The loophole has been present in every version of the Android operating system released since 2009.

Writing on the BlueBox blog, Jeff Forristal, said the implications of the discovery were "huge".

The bug emerges because of the way Android handles cryptographic verification of the programs installed on the phone.

Android uses the cryptographic signature as a way to check that an app or program is legitimate and to ensure it has not been tampered with. Mr Forristal and his colleagues have found a method of tricking the way Android checks these signatures so malicious changes to apps go unnoticed.

Any app or program written to exploit the bug would enjoy the same access to a phone that the legitimate version of that application enjoyed.

"It can essentially take over the normal functioning of the phone and control any function thereof," wrote Mr Forristal. BlueBox reported finding the bug to Google in February. Mr Forristal is planning to reveal more information about the problem at the Black Hat hacker conference being held in August this year.

Wednesday, 3 July 2013

Hotkey in Windows 8 - part 2


In this video, another set of keyboard shortcut in windows 8 is introduced. You can find that operation in windows 8 is not that difficult.




Java Internationalization (I18N)


The purpose of International (I18N) is to provide a more user-friendly way to change the language of label or messages in a program. The following are important class in Java Internationalization (I18N) (1) java.util.ResourceBundle (2) java.util.Locale (3) java.text.MessageFormat (A) The following code could obtain all locale supported by JAVA:
package com.easyinfo100;  
  
import java.util.Locale;  
  
public class LocaleList {  
  
    public static void main(String[] args) {  
  
        // Get All supported locale  
        Locale[] localeList = Locale.getAvailableLocales();  

        // loop throuth each locale and get language and country
        for (int i = 0; i < localeList.length; i++) {  
    
            System.out.println(localeList[i].getDisplayCountry() + "="  
                    + localeList[i].getCountry() + "  "  
                    + localeList[i].getDisplayLanguage() + "="  
                    + localeList[i].getLanguage());  
  
        }  
    }  
  
}  
(B) The following example is a simple example of Intenrationalization
import java.util.Locale;  
import java.util.ResourceBundle;  
  
public class Hello {  
  
    public static void main(String[] args) {  
        // get default locale 
        Locale myLocale = Locale.getDefault();  

        // get resource bundle of default locale

        ResourceBundle bundle1 = ResourceBundle.getBundle("mess", myLocale);  
        // get resource bundle of specific locale 
        ResourceBundle bundle2 = ResourceBundle.getBundle("mess", Locale.US);  

        // print out the resource properties  
        System.out.println(bundle1.getString("hello"));  
        System.out.println(bundle2.getString("hello"));  
    }  
  
}  

How to obtain uninstall APK Icon


The following activity is an example of showing how to fetch the uninstall APK icon. package example.uninstallAPKicon;

import android.app.Activity;  
import android.content.Context;  
import android.content.pm.ApplicationInfo;  
import android.content.pm.PackageInfo;  
import android.content.pm.PackageManager;  
import android.content.res.Resources;  
import android.graphics.drawable.Drawable;  
import android.os.Bundle;  
import android.util.DisplayMetrics;  
import android.util.Log;  
import android.view.View;  
import android.widget.ImageView;  
import java.io.File;  
import java.lang.reflect.*;  


public class FetchAPKIconActiviy extends Activity {  


   
 public void getUninatllApkInfo(Context context, String archiveFilePath) {  
  PackageManager pm = context.getPackageManager();  
  PackageInfo info = pm.getPackageArchiveInfo(archiveFilePath, PackageManager.GET_ACTIVITIES);  
  if (info != null) {  
   ApplicationInfo appInfo = info.applicationInfo;  
   Drawable icon = pm.getApplicationIcon(appInfo);  
   ImageView image = (ImageView) findViewById(R.id.apkIconByTradition);  
   image.setVisibility(View.VISIBLE);  
   image.setImageDrawable(icon);  
  }  
 }  
 
 public void onCreate(Bundle savedInstanceState) {  
  super.onCreate(savedInstanceState);  
  setContentView(R.layout.main);  
  showUninstallAPKIcon("/sdcard/APK/JarodYv.FishPool.apk");  
  getUninatllApkInfo(this, "/sdcard/APK/JarodYv.FishPool.apk");  
 }  

 private void showUninstallAPKIcon(String apkPath) {  
  String PATH_PackageParser = "android.content.pm.PackageParser";  
  String PATH_AssetManager = "android.content.res.AssetManager";  
  try {  

   Class pkgParserCls = Class.forName(PATH_PackageParser);  
   Class[] typeArgs = new Class[1];  
   typeArgs[0] = String.class;  
   Constructor pkgParserCt = pkgParserCls.getConstructor(typeArgs);  
   Object[] valueArgs = new Object[1];  
   valueArgs[0] = apkPath;  
   Object pkgParser = pkgParserCt.newInstance(valueArgs);  
   Log.d("ANDROID_LAB", "pkgParser:" + pkgParser.toString()); 

   DisplayMetrics metrics = new DisplayMetrics();  
   metrics.setToDefaults();  
 
   typeArgs = new Class[4];  
   typeArgs[0] = File.class;  
   typeArgs[1] = String.class;  
   typeArgs[2] = DisplayMetrics.class;  
   typeArgs[3] = Integer.TYPE;  
   Method pkgParser_parsePackageMtd = pkgParserCls.getDeclaredMethod("parsePackage",  
     typeArgs);  
   valueArgs = new Object[4];  
   valueArgs[0] = new File(apkPath);  
   valueArgs[1] = apkPath;  
   valueArgs[2] = metrics;  
   valueArgs[3] = 0;  
   Object pkgParserPkg = pkgParser_parsePackageMtd.invoke(pkgParser, valueArgs);  
  
   Field appInfoFld = pkgParserPkg.getClass().getDeclaredField("applicationInfo");  
   ApplicationInfo info = (ApplicationInfo) appInfoFld.get(pkgParserPkg);  
  
   Log.d("ANDROID_LAB", "pkg:" + info.packageName + " uid=" + info.uid);  
  
   Class assetMagCls = Class.forName(PATH_AssetManager);  
   Constructor assetMagCt = assetMagCls.getConstructor((Class[]) null);  
   Object assetMag = assetMagCt.newInstance((Object[]) null);  
   typeArgs = new Class[1];  
   typeArgs[0] = String.class;  
   Method assetMag_addAssetPathMtd = assetMagCls.getDeclaredMethod("addAssetPath",  
     typeArgs);  
   valueArgs = new Object[1];  
   valueArgs[0] = apkPath;  
   assetMag_addAssetPathMtd.invoke(assetMag, valueArgs);  
   Resources res = getResources();  
   typeArgs = new Class[3];  
   typeArgs[0] = assetMag.getClass();  
   typeArgs[1] = res.getDisplayMetrics().getClass();  
   typeArgs[2] = res.getConfiguration().getClass();  
   Constructor resCt = Resources.class.getConstructor(typeArgs);  
   valueArgs = new Object[3];  
   valueArgs[0] = assetMag;  
   valueArgs[1] = res.getDisplayMetrics();  
   valueArgs[2] = res.getConfiguration();  
   res = (Resources) resCt.newInstance(valueArgs);  
   CharSequence label = null;  
   if (info.labelRes != 0) {  
    label = res.getText(info.labelRes);  
   }  
   // if (label == null) {  
   // label = (info.nonLocalizedLabel != null) ? info.nonLocalizedLabel  
   // : info.packageName;  
   // }  
   Log.d("ANDROID_LAB", "label=" + label);  

   if (info.icon != 0) {  
    Drawable icon = res.getDrawable(info.icon);  
    ImageView image = (ImageView) findViewById(R.id.apkIconBySodino);  
    image.setVisibility(View.VISIBLE);  
    image.setImageDrawable(icon);  
   }  
  } catch (Exception e) {  
   e.printStackTrace();  
  }  
 }  
}  

Global object / variable in Andoird Application


When we need to define global variables or global object in Android, we can extend the base android.app.Application class. Here are the details step: (1) Define a class extending the android.app.Application class
public   class   GlobalAccess  extends  Application {  
    private  Boolean notification= false ;  
    public  Boolean getNotification() {  
        return  notification;  
    }  
    public  void  setNotification(Boolean notification) {  
        this.notification = notification;  
    }  
}  
(2) Add to AndroidManifest.xml
< application  
android:name = ".GlobalAccess"  
        ....  /> 
(3) Now, we can use Context.getApplicationContext() method to get this Global object / variable.
GlobalAccess global;  
public  void  onCreate(Bundle savedInstanceState) {  
    global=((GlobalAccess)getApplicationContext());  
    Boolean notification=global.getNotification();
}