Pages

Kamis, 08 September 2011

Phone internal and External storage usage

How to check Phone internal/external memory usage using programmatically in android

Android have a default API to check the phone internal and external memory usage.In My application
i used both as well as memory informations.The internal and external both are same,just to change
the Environment path.
Internal=StatFs stat=new StatFs(Environment.getDataDirectory().getPath());
External=StatFs stat=new StatFs(Environment.getExternalStorageDirectory().getPath());
The user can just hit the seek bar its show the occupied space in bytes,availabel space in MB,
Before that first to create new emulatore with size can set it in Kb or MB.I used 24MB.
public class Internal_Storage extends Activity  implements SeekBar.OnSeekBarChangeListener{
 SeekBar sb;
 int progress;
 Boolean value=false;
 Button press_btn;
 TextView availabel_in_tv,occupied_in_tv,tv;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.internal_storage);
        availabel_in_tv=(TextView)findViewById(R.id.availabel_in_tv);
        occupied_in_tv=(TextView)findViewById(R.id.occupied_in_tv);
        final TextView reading = (TextView) findViewById(R.id.textView1);
        sb = (SeekBar)findViewById(R.id.sb);
        sb.setMax(100);
    @Override
    public void onProgressChanged(SeekBar seekBar, int size, boolean fromtouch) {
        reading.setText("Loading "+size+"% ");
        method1();
       
        }
    @Override
    public void onStartTrackingTouch(SeekBar seekBar) {
       
        }
    @Override
    public void onStopTrackingTouch(SeekBar seekBar) {
    }
  });
    }
    @Override
    public void onProgressChanged(SeekBar seekBar, int progress,boolean fromUser) {
    }
 @Override
 public void onStartTrackingTouch(SeekBar seekBar) {
  // TODO Auto-generated method stub

 }
 @Override
 public void onStopTrackingTouch(SeekBar seekBar) {
  // TODO Auto-generated method stub
 }
public String method1(){
StatFs stat=new StatFs(Environment.getDataDirectory().getPath()); //**ITS show  phone internal  storage size**//
       or
StatFs stat=new StatFs(Environment.getExternalStorageDirectory().getPath());  //**ITS show  phone SD card storage size**//

    int blockSize = stat.getBlockSize();
    int availableBlocks = stat.getAvailableBlocks();     
    System.out.println("statFs:"+"=" +stat);
    System.out.println("SPACE AVAILABEL :"+"=" +availableBlocks);
     //occup_size_tv.setTextSize(availableBlocks);
     occupied_in_tv.setText(Integer.toString(availableBlocks));
     System.out.println("SIZE OCCUPY:"+"=" +blockSize);
  
     availabel_in_tv.setText((Formatter.formatFileSize(this,availableBlocks*blockSize)));
     System.out.println("FREE SPACE:="+Formatter.formatFileSize(this,availableBlocks*blockSize));
     System.out.println("FREE SPACE IN BYTES:"+availableBlocks +1042.f*1024.f);
     // bytesAvailable / (1024.f * 1024.f);
     return Formatter.formatShortFileSize(this, availableBlocks * blockSize);


 }
the same code repeated for internal and external.class
Then next class Memory_Information.class,its show total memory usage details
public class Memory_Information extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.memory_information);   
        TextView CPUinfo = (TextView) findViewById(R.id.textView1);
        CPUinfo.setText(ReadCPUinfo());    
    }
    private String ReadCPUinfo()
    {
     ProcessBuilder cmd;
   
     StringBuffer strMemory = new StringBuffer();
     //final ActivityManager activityManager =(ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
   
     ActivityManager actvityManager = (ActivityManager) this.getSystemService( ACTIVITY_SERVICE );
     ActivityManager.MemoryInfo mInfo = new ActivityManager.MemoryInfo ();
     actvityManager.getMemoryInfo( mInfo );
   
     strMemory.append("Available Memory : ");
     strMemory.append(mInfo.availMem);
     strMemory.append("\n");
     strMemory.append("\n");
   
     String result=strMemory.toString();
   
     try{
      String[] args = {"/system/bin/cat", "/proc/meminfo"};
      cmd = new ProcessBuilder(args);
   
      Process process = cmd.start();
      InputStream in = process.getInputStream();
      byte[] re = new byte[1024];
      while(in.read(re) != -1){
       System.out.println(new String(re));
       result = result + new String(re);
      }
      in.close();
     } catch(IOException ex){
      ex.printStackTrace();
     }
     return result;
    }
}
you may check in console also or u can clarify the usage in phones settings. go to settings/SD card & phone storage/


How to check Phone internal/external memory usage using programmatically in android

Android have a default API to check the phone internal and external memory usage.In My application
i used both as well as memory informations.The internal and external both are same,just to change
the Environment path.
Internal=StatFs stat=new StatFs(Environment.getDataDirectory().getPath());
External=StatFs stat=new StatFs(Environment.getExternalStorageDirectory().getPath());
The user can just hit the seek bar its show the occupied space in bytes,availabel space in MB,
Before that first to create new emulatore with size can set it in Kb or MB.I used 24MB.
public class Internal_Storage extends Activity  implements SeekBar.OnSeekBarChangeListener{
 SeekBar sb;
 int progress;
 Boolean value=false;
 Button press_btn;
 TextView availabel_in_tv,occupied_in_tv,tv;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.internal_storage);
        availabel_in_tv=(TextView)findViewById(R.id.availabel_in_tv);
        occupied_in_tv=(TextView)findViewById(R.id.occupied_in_tv);
        final TextView reading = (TextView) findViewById(R.id.textView1);
        sb = (SeekBar)findViewById(R.id.sb);
        sb.setMax(100);
    @Override
    public void onProgressChanged(SeekBar seekBar, int size, boolean fromtouch) {
        reading.setText("Loading "+size+"% ");
        method1();
       
        }
    @Override
    public void onStartTrackingTouch(SeekBar seekBar) {
       
        }
    @Override
    public void onStopTrackingTouch(SeekBar seekBar) {
    }
  });
    }
    @Override
    public void onProgressChanged(SeekBar seekBar, int progress,boolean fromUser) {
    }
 @Override
 public void onStartTrackingTouch(SeekBar seekBar) {
  // TODO Auto-generated method stub

 }
 @Override
 public void onStopTrackingTouch(SeekBar seekBar) {
  // TODO Auto-generated method stub
 }
public String method1(){
StatFs stat=new StatFs(Environment.getDataDirectory().getPath()); //**ITS show  phone internal  storage size**//
       or
StatFs stat=new StatFs(Environment.getExternalStorageDirectory().getPath());  //**ITS show  phone SD card storage size**//

    int blockSize = stat.getBlockSize();
    int availableBlocks = stat.getAvailableBlocks();     
    System.out.println("statFs:"+"=" +stat);
    System.out.println("SPACE AVAILABEL :"+"=" +availableBlocks);
     //occup_size_tv.setTextSize(availableBlocks);
     occupied_in_tv.setText(Integer.toString(availableBlocks));
     System.out.println("SIZE OCCUPY:"+"=" +blockSize);
  
     availabel_in_tv.setText((Formatter.formatFileSize(this,availableBlocks*blockSize)));
     System.out.println("FREE SPACE:="+Formatter.formatFileSize(this,availableBlocks*blockSize));
     System.out.println("FREE SPACE IN BYTES:"+availableBlocks +1042.f*1024.f);
     // bytesAvailable / (1024.f * 1024.f);
     return Formatter.formatShortFileSize(this, availableBlocks * blockSize);


 }
the same code repeated for internal and external.class
Then next class Memory_Information.class,its show total memory usage details
public class Memory_Information extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.memory_information);   
        TextView CPUinfo = (TextView) findViewById(R.id.textView1);
        CPUinfo.setText(ReadCPUinfo());    
    }
    private String ReadCPUinfo()
    {
     ProcessBuilder cmd;
   
     StringBuffer strMemory = new StringBuffer();
     //final ActivityManager activityManager =(ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
   
     ActivityManager actvityManager = (ActivityManager) this.getSystemService( ACTIVITY_SERVICE );
     ActivityManager.MemoryInfo mInfo = new ActivityManager.MemoryInfo ();
     actvityManager.getMemoryInfo( mInfo );
   
     strMemory.append("Available Memory : ");
     strMemory.append(mInfo.availMem);
     strMemory.append("\n");
     strMemory.append("\n");
   
     String result=strMemory.toString();
   
     try{
      String[] args = {"/system/bin/cat", "/proc/meminfo"};
      cmd = new ProcessBuilder(args);
   
      Process process = cmd.start();
      InputStream in = process.getInputStream();
      byte[] re = new byte[1024];
      while(in.read(re) != -1){
       System.out.println(new String(re));
       result = result + new String(re);
      }
      in.close();
     } catch(IOException ex){
      ex.printStackTrace();
     }
     return result;
    }
}
you may check in console also or u can clarify the usage in phones settings. go to settings/SD card & phone storage/
 
  



Rabu, 17 Agustus 2011

How to create contextmenu in android

creating a context menu is very simple,Here i use Textview name as press me on long,when the textview is pressed for long,its open a context menu.In that context menu i use New,edit,copy,paste and delete.
Inside of the onCreate Method,we have to registerForcontextmenu(controls name)
Example: press=(TextView)findViewById(R.id.press_tv);
               registerForContextMenu(press); 
Then we  need to override the onCreateContextMenu method to create the menu:
 @Override 
   public void onCreateContextMenu(ContextMenu menu, View v,ContextMenuInfo menuInfo) {  
  super.onCreateContextMenu(menu, v, menuInfo);  
   menu.setHeaderTitle("Context Menu");  
   menu.add(0, v.getId(), 0, "New");  
   menu.add(0, v.getId(), 0, "Edit");  
   menu.add(0, v.getId(), 0, "copy");  
   menu.add(0, v.getId(), 0, "Paste");  
   menu.add(0, v.getId(), 0, "Delete");  
when the item is selected,that items action can perform here,using onContextItemSelected method.
Here i use function for only "New" just passing the Intent,If u want some functions mean, you write a else if () and perform some more actions there.
 @Override 
  public boolean onContextItemSelected(MenuItem item) {  
   if(item.getTitle()=="New"){
    Intent np=new Intent(getApplicationContext(),NewPage.class);
    startActivity(np);
    function1(item.getItemId());}  
   else if(item.getTitle()=="Save"){
    //Some funtion perform here//
    function2(item.getItemId());}  
    else {return false;}  
  return true;  
 }
create a method for function1.... function n,
private void function2(int itemId) {
  // TODO Auto-generated method stub
 
 }
 private void function1(int itemId) {
  // TODO Auto-generated method stub
 
 } 
Result is:
           



pic1



pic2

 
  



pic3



pic4
Download full source code 

Minggu, 14 Agustus 2011

Android Interview Question Answer

1.Describe the APK format?
  The APK file is compressed the AndroidManifest.xml file,application code(.dex files),resource files &    other  files.A Project is compiled into a single.apk file.

2.what is an action?
  A description of something that an Intent sender describes.

3.what is activity?
  A single screen in an application,with supporting java code.

4.what is intent?
  A class (Intent) describes what a caller desires to do.The caller sends this intent to Android's intent resolver,which finds the most suitable activity for the intent.

5.How is nine-patch image different from a regular bitmap?
  It is a resizable bitmap resource that can be used for background or other images on the device.The Nine Patch class permits drawing in nine sections.The four corners are unscaled;the four edges are scaled in one axis,and the middle is scaled in both axes.

6.what languages does Android support for application development?
  Android applications are written using the java programming language.

7.what is resource?
  A user-supplied XML,bitmap,or other file,injected into the application build process,which can later be loaded from code.

8.How will you record a phone call in Android?How to get a handle on Audio Stream for a call in Android?
  Permissions.PROCESS_OUTGOING_CALLS:Allows an application to monitor,modify,or abort outgoing calls.

9.What's the difference between file,class and activity in android?
  File-It is a block of arbitrary information,or resource for storing information.It can be of any type.
  Class-Its a  compiled form of java file.Android finally used this.Class files to produce an executable apk.
  Activity-An Activity is the equivalent of a Frame/Window in GUI toolkits.It is not a file or a file type it is just a class that can be extended in Android for loading UI elements on view.

10.What is a Sticky Intent?
   SendStickyBroadcasr() performs a sendBroadcast(Intent)that is "sticky".i.e.,the Intent you are sending stays around after the broadcast is complete,so that others can quickly retrieve that data through
   the return value of registerReceiver(BroadcastReceiver,IntentFilter).In all other ways,this behaves the same as sendBroadcast(Intent).
   One example of a sticky broadcast sent via the operating system is ACTION_BATTERY_CHANGED.when you call registerReceiver() for that action--even with a null BroadcastReceiver--you get the intent that was last
   broadcast for that action.Hence,you can use this to find the state of the battery without necessarily registering for all future state changes in the battery.

11.Is Bionic (Google's version of libc)dynamic linked?
   yes,all libs are dynamically linked.

12.Does Android have  USB support?External Keyboard.etc?
    The Hardware should support it but its not enabled in the software.Maybe in a point release.

13.what is the next version of the SDK?
   No major surprise.We are cleaning up APIs.Making sure things are named consistently,parameters all need to be there,etc.so there's some churn.Ensuring what goes out is something
   we can support until the end of time.For example protected members might go package private so we have the option of changing later.
   On the system side,we are moving towards a tighter security policy.In M5 lots of things run as root,but in the next version almost nothing runs as root.We use the minimum privileges necessary.

14.Will there be a central registery for intents?
   That should like a period opportunity for a 3rd party developer.Intents use package naming conventions to prevent collisions,like com.google.something.

15.Have any advice on general portability strategies;Android,Brew,etc.?
   Emphasize the commanality between platforms,common proile support,separation between main logic and front end interface.Eventually somebody will add J2ME APIs
   into the Android platform.But the user interface level you will want to tie into platform-specific things(for the best user experience).Access to the web is standard
   across all platforms.

16.Can I deploy linux apps on real handsets?With a modified Qemu?
   Expect the Android framework to run on top of other mobile Linux efforts?
   Qemu depends on OEM or carrier.Its possible that upgrades may have to be signed by carrier.As far as native code goes,we dont currently have a bunch of the standard Unix X type stuff in
   there.command line stuff compiles and runs as is.Expect that once this is open sourced,people will bolt on an X sever and traditional Unix/Linux into the framework.While java is the
   primary development language for Android 1.0,the system has been designed to support multiple platforms including native.Also expect the Android framework to run on top of other
   mobile Linux efforts.
   Example:Web browser WebKit is c++ based,and there's java chrome on top of that.For debugging I use gdb server to debug native code.JNI layer talks between c++ and java.

17.Is the magnifier widget shown in the opening session specific to the browser or can i use it in my apps?
   That one is specific to browser.It's implemented in the native part of browser.  

18.Gears will eventually be supported on Android,can we expect thatin 1.0?
   It's under investigation.cant guarantee on 1.0,but we would like to have it there.

19.Do you plan to support an extension mechanism like plug-ins?for example secure web site user certificate storage is not supported,and there is no mechanism to add it?
   We dont have the full plug-in support.Partial MPPI support ...we are still working on it.Probably not finished by 1.0.
   Note:we do have the HTTPS support now.

20.Is there info on the UI toolkit,animation effects,compostion,effects,and what is it based on?
   We have a couple different approaches to drawing.We have full support for OpenGL Es,and use hardware support if its there.For more conventional UI,apps use the view system
   documented in the SDK.This site on top of graphics layer,Canvas SGL.

21.Does Android complete with JavaFX mobile?
   The world doesnt need another operating system.The world needs an open embedded web operating system,open source.(Andy:)I haven't seen anything that encompasses as much as Android.

22.We do social apps.We have javascript expertise but not java.Is there an API running on localhost to fetch geo locations?
   There's a browser and web view .If you want to write local.If  you use the embedded web view you can have Java binding.javascript calls java in embedding app.You get your own icon,your own storage,your own
   world in which to operate.

23.(From Android Software company)Will there be any Android developer events in India?
    That makes sense but I'm not sure if any are planned right now.

24.If a small device manufufacturer wants to run Android,can they just download  it and go?Once it's open source ,anyone can download and port Android without joining OHA?
   Once it's open  source,anyone can download and port Android without joining OHA.Android will be open source before the end of the year.

25.(From 7 networks mobile messaging software).Can you comment on power management features?How can developers extend battery life?
   A the kernel level,it goes into low power states even when running.Android supports wake locks.does it at the platform level so apps dont have to request that from the kernel.We are trying
   to be smart about it.for example,a network event wakes up system,but may not even wake up the screen.There are two classes of timers-real time timers that can trigger even
   when device is asleep(like alarms),and free-running timers that only run when device is awake.we are also working on some visibility to the user,so they can tell what apps are
   contributing to the device being awake.We are hoping to set some good examples with core apps,and also provide a way for the end user to see what's keeping their device awake and
   be able to uninstall badly behaved apps.similar to finding out what's storage space or CPU time.

26.We are working on seamless mobility between cell and wifi calls.Can apps trigger Wifi scanning?search for SSIDs?
   Wifi support ,we have been adding.There's the connection manager that can see SSIDs,associate,and it supports a number of authentication schemes.

27.Can a 3rd party application initiate a wifi scan?
   Yes,if it has permission.

28.I want to use native phone dialer to make voip calls,can i do that?
   We already have hooks for that.system sends an intent,which can be intercepted.

29.Can I intercept incoming calls too?
   Not sure,there are security issues.

30.A VOIP app wants to route audio to earpiece.Normally apps dont use earpiece possible?
   Post to forum or bug request.The system can do audio routing but i dont know if it's been exposed to top level APIs.

31.Will Android support data from router/wifi?
   Yes,Its not fully enabled in 1.0 but you can even use bluetooth as an interface(ethernet over bluetooth).Ethernet over USB too,on Linux it works great,but
   some driver work is needed for windows and OSX.

32.How to select more than one option from list in android xml file?Give example?
   Specify android id,layout height and width as depicted in the following example.
   <ListView android:id="@+id/ListView01" android:layout-height="wrap_content" android:layout_width="fill_parent"></ListView>

Jumat, 05 Agustus 2011

How to create FeedBack Form inside of the customDialogBox?

How to create a form in dialog box,Here i use sample feed back form inside of the custom dialogbox,First u have to create a button in main.xml file,Because when the button is press ,FeedBack Form can open in customdialogbox,so thats why i had put a Button(Press Dialog).After that you also create a new xml file name as dialog.xml,In that xml ,i use Name,Mail,Comment and two buttons like send and cancel.
code for dialog.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="match_parent"
  android:orientation="vertical" android:layout_height="wrap_content">
    <LinearLayout android:id="@+id/linearLayout1" android:layout_height="wrap_content" android:layout_width="match_parent">
        <TextView android:id="@+id/textView1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Name" android:textSize="15dp" android:layout_marginLeft="10dp" android:layout_marginTop="5dp"></TextView>
        <EditText android:id="@+id/editText1" android:layout_height="wrap_content" android:layout_marginTop="5dp" android:layout_width="200dp" android:layout_marginLeft="16dp"></EditText>
    </LinearLayout>
    <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/linearLayout2">
        <TextView android:id="@+id/textView2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Mail Id:" android:layout_marginTop="5dp" android:layout_marginLeft="5dp"></TextView>
        <EditText android:id="@+id/editText2" android:layout_height="wrap_content" android:layout_marginTop="5dp" android:layout_width="200dp" android:layout_marginLeft="16dp"></EditText>
    </LinearLayout>
    <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/linearLayout3">
        <TextView android:id="@+id/textView3" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Comment" android:layout_marginLeft="5dp" android:layout_marginTop="5dp"></TextView>
        <EditText android:id="@+id/editText3" android:layout_height="100dp" android:layout_width="200dp"></EditText>
    </LinearLayout>
    <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/linearLayout4">
        <Button android:id="@+id/button1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Send" android:layout_marginLeft="70dp"></Button>
        <Button android:id="@+id/button2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Cancel"></Button>
    </LinearLayout>
</LinearLayout>
Then i have to create a main class name as FeedbackFormusingInsideDialogBox.java
static final int CUSTOM_DIALOG_ID = 0;
Button customDialog_Dismiss;
The class have to declare as a
its a very few line code to creat a dialogbox.Just button press click listener,Dialog onCreateDialog and cancel button listener.
here i put full code .just check it

public class FeedbackFormusingInsideDialogBox extends Activity {
 static final int CUSTOM_DIALOG_ID = 0;
 Button customDialog_Dismiss;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);      
        Button buttonStartDialog = (Button)findViewById(R.id.startdialog);
        buttonStartDialog.setOnClickListener(new Button.OnClickListener(){
   @Override
   public void onClick(View arg0) {
    // TODO Auto-generated method stub
    showDialog(CUSTOM_DIALOG_ID);
   }
        });
              
    }     
    private Button.OnClickListener customDialog_DismissOnClickListener  = new Button.OnClickListener(){ 
  @Override
  public void onClick(View arg0) {
   // TODO Auto-generated method stub
   dismissDialog(CUSTOM_DIALOG_ID);
  }    
    };   
 @Override
 protected Dialog onCreateDialog(int id) {
  // TODO Auto-generated method stub
  Dialog dialog = null;;
     switch(id) {
     case CUSTOM_DIALOG_ID:
      dialog = new Dialog(this);
      dialog.setContentView(R.layout.dialogbox);
      dialog.setTitle("Feed Back Form");
             customDialog_Dismiss = (Button)dialog.findViewById(R.id.button2);
             customDialog_Dismiss.setOnClickListener(customDialog_DismissOnClickListener);
         break;
     }
     return dialog;
 } 
 }
Result :




Selasa, 02 Agustus 2011

How to use swipe in android?

Swipe is otherwise called  as a Fling. Its a touch free movement in android.
Before that we have set some SWIPE MIN,MAX Distance,Threshold_velosity and as well as path.
 private static final int SWIPE_MIN_DISTANCE = 120;
  private static final int SWIPE_MAX_OFF_PATH = 250;
 private static final int SWIPE_THRESHOLD_VELOCITY = 200;
 private GestureDetector gestureDetector;
 View.OnTouchListener gestureListener;
 private Animation slideLeftIn;
 private Animation slideLeftOut;
 private Animation slideRightIn;
        private Animation slideRightOut;
        private ViewFlipper viewFlipper;
Next step is to write a code inside of the onCreate Method
        setContentView(R.layout.main);
        viewFlipper = (ViewFlipper)findViewById(R.id.flipper);
        slideLeftIn = AnimationUtils.loadAnimation(this, R.anim.slide_left_in);
        slideLeftOut = AnimationUtils.loadAnimation(this, R.anim.slide_left_out);
        slideRightIn = AnimationUtils.loadAnimation(this, R.anim.slide_right_in);
        slideRightOut = AnimationUtils.loadAnimation(this, R.anim.slide_right_out);
       
        gestureDetector = new GestureDetector(new MyGestureDetector());
        gestureListener = new View.OnTouchListener() {
            public boolean onTouch(View v, MotionEvent event) {
                if (gestureDetector.onTouchEvent(event)) {
                    return true;
                }
                return false;
            }
        };
You will need to extend SimpleOnGestureListener to implement your own handling on swipe/fling action:

 class MyGestureDetector extends SimpleOnGestureListener {
        @Override
        public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
            try {
                if (Math.abs(e1.getY() - e2.getY()) > SWIPE_MAX_OFF_PATH)
                    return false;
                // right to left swipe
                if(e1.getX() - e2.getX() > SWIPE_MIN_DISTANCE && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
                 viewFlipper.setInAnimation(slideLeftIn);
                    viewFlipper.setOutAnimation(slideLeftOut);
                 viewFlipper.showNext();
                }  else if (e2.getX() - e1.getX() > SWIPE_MIN_DISTANCE && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
                 viewFlipper.setInAnimation(slideRightIn);
                    viewFlipper.setOutAnimation(slideRightOut);
                 viewFlipper.showPrevious();
                }
            } catch (Exception e) {
                // nothing
            }
            return false;
        }
    }
At last, you need to make sure in your activity, you catch the gesture event by overriding onTouch() method:
 
@Override
    public boolean onTouchEvent(MotionEvent event) {
        if (gestureDetector.onTouchEvent(event))
         return true;
     else
      return false;
    }
Here i use viewflipper,two LinearLayouts and two Buttons in main.xml file you have to set as <ViewFlipper xmlns:android="http://......" like this

<?xml version="1.0" encoding="utf-8"?>
<ViewFlipper xmlns:android="http://schemas.android.com/apk/res/android"
     android:id="@+id/flipper"
     android:layout_width="fill_parent"
     android:layout_height="fill_parent">
   
 <LinearLayout
  android:layout_width="fill_parent" android:layout_height="70dp" android:background="#E2A9F3">
  <TextView android:id="@+id/textView1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginLeft="30dp" android:layout_marginTop="10dp" android:text="Swipe Me" android:textSize="20dp" android:textColor="#DF0101"></TextView>
    </LinearLayout>  
    <LinearLayout
  android:layout_width="fill_parent" android:layout_height="60dp" android:background="#585858">
     <Button android:id="@+id/button1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Back"></Button>
     <Button android:id="@+id/button2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Next"></Button>
    </LinearLayout>  
</ViewFlipper>
At last thing u have to create a new folder and set name as anim or what u wish ,u give it.In that folder you have to  create a xml for Left_in,Left_out,Right_in and right_out and set the values.
name:slide_left_in.xml
<set xmlns:android="http://schemas.android.com/apk/res/android">
    <translate android:fromXDelta="100%p" android:toXDelta="0" android:duration="800"/>
</set>
name:slide_left_out.xml
<set xmlns:android="http://schemas.android.com/apk/res/android">
    <translate android:fromXDelta="0" android:toXDelta="-100%p" android:duration="800"/>
</set>
name:slide_right_in.xml
<set xmlns:android="http://schemas.android.com/apk/res/android">
    <translate android:fromXDelta="-100%p" android:toXDelta="0" android:duration="800"/>
</set>
name:slide_right_out.xml
<set xmlns:android="http://schemas.android.com/apk/res/android">
    <translate android:fromXDelta="0" android:toXDelta="100%p" android:duration="800"/>
</set>

Result:
 

Senin, 01 Agustus 2011

How to use Menu Option in Android?

Its a very simple way to use menu option in android, just only four line to write it. first u have to  create new folder and name as menu
example res/menu/sample.xml.
give some options what u want ,Here i gave file,open,save and edit

<?
<
xml version="1.0" encoding="utf-8"?>menu
xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="@+id/file" android:title="@string/file" />
<item android:id="@+id/open" android:title="@string/open"/> <item android:id="@+id/save" android:title="@string/save" />
<item android:id="@+id/edit" android:title="@string/edit"/> </menu>
after that we have to set a values in strings.xml
example:values/strings.xml
<?
<
xml version="1.0" encoding="utf-8"?>resources>
<string name="hello">Hello World, MenuScreen!</string>
<string name="app_name">SampleMenu</string>
<string name="file">File</string>
<string name="open">Open</string>
<string name="save">Save</string>
</
<string name="edit">Edit</string>resources>
now you have to write a code to show the menu options.
@Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.sample, menu);         
        return true;
    }
Result is:

Kamis, 07 Juli 2011

How to use Multi Language in android?

How to use multi language of text in android?

Its just a easy way to use it.How ? The html decimal unicode is suppoted by android os.Here i show three languages,Tamil,hindi and Telungu.First of all u should download the DLL file.For example :
"Akshar.ttf",Its a one of the Library file,It help to convert the decimal unicode format.Your Android application there is assests folder ,you just create a new folder and name as fonts,then put inside of the "Akshar.ttf" file in that folder,Now come to our Code section.

 TextView english,tamil,hin,tel;
String tam,h,t;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        tamil=(TextView)findViewById(R.id.textView2);
        hin=(TextView)findViewById(R.id.hindi);
        tel=(TextView)findViewById(R.id.telngu);
        tam="&#3000;&#2965;&#45;&#2949;&#2985;&#3021;&#2975;&#3021;&#2992;&#3018;&#2951;&#2975;&#3021; &#2949;&#2986;&#3021;&#2986;&#3021;&#2994;&#3007;&#2965;&#2975;&#3007;&#2962;&#2985;&#3021;&#46;&#2986;&#3021;&#2994;&#3018;&#2965;&#3021;&#3000;&#3021;&#2986;&#3018;&#2975;&#3021;&#46;&#2965;&#3018;&#2990;&#3021;";
        h="&#2360;&#2327;&#45;&#2309;&#2344;&#2381;&#2337;&#2381;&#2352;&#2379;&#2311;&#2337;&#2381; &#2309;&#2346;&#2381;&#2346;&#2381;&#2354;&#2367;&#99;&#2309;&#2335;&#2367;&#2323;&#2344;&#2381;&#46;&#2348;&#2381;&#2354;&#2379;&#2327;&#2381;&#2360;&#2381;&#2346;&#2379;&#2335;&#2381;&#46;&#99;&#2323;&#2350;&#2381;";
        t="&#3128;&#3095;&#45;&#3077;&#3112;&#3149;&#3105;&#3149;&#3120;&#3146;&#3079;&#3105;&#3149; &#3077;&#3114;&#3149;&#3114;&#3149;&#3122;&#3135;&#99;&#3077;&#3103;&#3135;&#3090;&#3112;&#3149;&#46;&#3116;&#3149;&#3122;&#3146;&#3095;&#3149;&#3128;&#3149;&#3114;&#3146;&#3103;&#3149;&#46;&#99;&#3090;&#3118;&#3149;        ";
       
        Typeface tf=Typeface.createFromAsset(getAssets(), "fonts/Akshar.ttf");
       
      
        tamil.setTypeface(tf,Typeface.BOLD);
        tamil.setText(Html.fromHtml(tam));
       
        hin.setTypeface(tf,Typeface.ITALIC);
        hin.setText(Html.fromHtml(h));
       
       
        tel.setTypeface(tf,Typeface.NORMAL);
        tel.setText(Html.fromHtml(t));
       
    }
}


The output is:
Download full source code

Sabtu, 02 Juli 2011

How to use Autocomplete searchbox in Database?

Autocomplete means it show the complete text automatically.It have two types
1.Single line autocomplete
2.Multi line autocomplete
what letter we type in the searchbox,that letter of the complete words  to show.Here i use autocomplete searchbox ,The select item can pass into the textview
.I use DATABASE NAME as="itemsearchsqlite.db",TABLE NAME as="itemsearch" and DB COLUMN NAME as="item_name".
I use two java classes namely Home.java and SQLiteItemsearch.java
//SQLiteItemSearch.java//
------------------------
package com.autocomplete.sample;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
public class SQLiteItemSearch extends SQLiteOpenHelper
{
    private static final String DB_NAME = "itemsearchsqlite.db";
    private static final int DB_VERSION_NUMBER = 1;
    private static final String DB_TABLE_NAME = "itemsearch";
    private static final String DB_COLUMN_1_NAME = "item_name";

    private static final String DB_CREATE_SCRIPT = "create table " + DB_TABLE_NAME +
                            " (_id integer primary key autoincrement, item_name text not null);)";

    private SQLiteDatabase sqliteDBInstance = null;

    public SQLiteItemSearch(Context context)
    {
        super(context, DB_NAME, null, DB_VERSION_NUMBER);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
    {
        // TODO: Implement onUpgrade
    }

    @Override
    public void onCreate(SQLiteDatabase sqliteDBInstance)
    {
        Log.i("onCreate", "Creating the database...");
        sqliteDBInstance.execSQL(DB_CREATE_SCRIPT);
    }

    public void openDB() throws SQLException
    {
        Log.i("openDB", "Checking sqliteDBInstance...");
        if(this.sqliteDBInstance == null)
        {
            Log.i("openDB", "Creating sqliteDBInstance...");
            this.sqliteDBInstance = this.getWritableDatabase();
        }
    }

    public void closeDB()
    {
        if(this.sqliteDBInstance != null)
        {
            if(this.sqliteDBInstance.isOpen())
                this.sqliteDBInstance.close();
        }
    }

    public long insertitmSearch(String ItemBrandName)
    {
        ContentValues contentValues = new ContentValues();
        contentValues.put(DB_COLUMN_1_NAME, ItemBrandName);
        Log.i(this.toString() + " - insertitmSearch", "Inserting: " + ItemBrandName);
        return this.sqliteDBInstance.insert(DB_TABLE_NAME, null, contentValues);
    }

    public boolean removeitmSearch(String ItemBrandName)
    {
        int result = this.sqliteDBInstance.delete(DB_TABLE_NAME, "item_name='" + ItemBrandName + "'", null);

        if(result > 0)
            return true;
        else
            return false;
    }

    public long updateitmSearch(String oldItemBrandName, String newItemBrandName)
    {
        ContentValues contentValues = new ContentValues();
        contentValues.put(DB_COLUMN_1_NAME, newItemBrandName);
        return this.sqliteDBInstance.update(DB_TABLE_NAME, contentValues, "item_name='" + oldItemBrandName + "'", null);
    }

    public String[] getAllItemFilter()
    {
        Cursor cursor = this.sqliteDBInstance.query(DB_TABLE_NAME, new String[] {DB_COLUMN_1_NAME}, null, null, null, null, null);

        if(cursor.getCount() >0)
        {
            String[] str = new String[cursor.getCount()];
            int i = 0;

            while (cursor.moveToNext())
            {
                 str[i] = cursor.getString(cursor.getColumnIndex(DB_COLUMN_1_NAME));
                 i++;
             }
            return str;
        }
        else
        {
            return new String[] {};
        }
    }
}

Then again we have to insert a rows of dataitems inside of the Home.java class
public class Home extends Activity {
 private SQLiteItemSearch sqllitebb;
 TextView tv;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.list_item);
       
        final AutoCompleteTextView actv=(AutoCompleteTextView)findViewById(R.id.autocompleteitem);
        sqllitebb=new SQLiteItemSearch(Home.this);
        sqllitebb.openDB();
     // Insert a few item list statically//
     
        sqllitebb.insertitmSearch("Color Monitor");
        sqllitebb.insertitmSearch("Compact Disk");
        sqllitebb.insertitmSearch("Computer");
       sqllitebb.insertitmSearch("Copy Righter");
       sqllitebb.insertitmSearch("Hard Disk");
       sqllitebb.insertitmSearch("HP Printer");
       sqllitebb.insertitmSearch("HP Laser Printer");
       sqllitebb.insertitmSearch("HP Injet Printer");
      //  sqllitebb.removeitmsearch("Computer");
       // sqllitebb.updateitmSearch("Computer","DELL");
     final  String[] deal = sqllitebb.getAllItemFilter();
      
       // Print out the values to the log
       for(int i = 0; i < deal.length; i++)
       {
           Log.i(this.toString(), deal[i]);
       }
       ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_dropdown_item_1line,deal);
       actv.setAdapter(adapter); 
       actv.setThreshold(1);
       actv.setOnItemClickListener(new OnItemClickListener() {
           public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
            tv=(TextView)findViewById(R.id.selecteditem_tv);
            tv.setText(deal[arg2]);
            arg0.getItemAtPosition(arg2);
                Log.i("SELECTED TEXT WAS------->",  deal[arg2]);
           }
       });
    }
    public void onDestroy()
    {
        super.onDestroy();
        sqllitebb.close();
    }
}

Have to drag and drop the autocomplete control,the two textview controls.
[code=list_item.xml]

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:padding="5dp" android:orientation="vertical">
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="ITEM_SEARCH" />
    <AutoCompleteTextView android:id="@+id/autocompleteitem"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="5dp"/>
    <TextView android:text="TextView" android:id="@+id/selecteditem_tv" android:layout_width="wrap_content" android:layout_height="wrap_content"></TextView>
</LinearLayout>
   



If u want to check the database in sqlite,no problem Go to DDMS or
Go to Window->open Perspective-> select File explorer->go to data, then->select data->inside of the data all packages are availabel,here my application
package name is com.autocomplete.sample,after select our package there is two options are availabel 1.databases,2.lib.first have to select it or open it.open
databases inside of the databases our application database name itemsearchsqlite.db had held we have to pull a file from the device.u have to choose the db
in any location,for example i select desktop and pull it .Then u go to Android-SDK,inside of the SDK u have to open Tools,because the sqlite3 has present
inside of the tools.u click the sqlite3.open our db in desktop asusal click right side ,go to open with and select SQLITE3.At the begining we have to type
DOT or .tables,In sqlite it shows our correct and current table name at the final open our table like select * from itemsearch;
finished all the things.ITS show our records.
Note:If u not understand my hints means better u see my screen schots.






Go to Android SDK




Open DB in desktop




Download full source code