Monday 17 October 2011

Horizontal View Swiping with ViewPager In Android New Compatibility


Whether you have just started out in Android app development or are a veteran of the craft, it probably won’t be too long before you’ll need to implement horizontally scrolling sets of views. Many existing Android apps already use this UI pattern, such as the new Android Market, Google Docs and Google+. ViewPager standardizes the implementation.
ViewPager was released as part of the Compatibility Package revision 3 and works with Android 1.6 upwards. After following the instructions to obtain the package you can right-click on your Android project in Eclipse, choose ‘Android Tools’ and ‘Add Compatibility Library’, making the new classes available.
You can refer this link for how to add compatibility package in to your project in eclipse 

ViewPager is a ViewGroup and works in a similar manner to AdapterViews (like ListView and Gallery) so it shouldn’t feel too foreign. Note that if you use ViewPager in an xml layout, be sure to use the full class reference, e.g.

 <android.support.v4.view.ViewPager
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        … />
ViewPagers source their views from PagerAdapters which give you have full control over the reuse and recycling of the views. A PagerAdapter implementation called FragmentPagerAdapter is provided to facilitate the use of Fragments in a ViewPager; This is immensely powerful and as simple as implementing getCount() and getItem(). There is a sample called Fragment Pager Support provided in the Support Demos to illustrate this.

    public static class MyAdapter extends FragmentPagerAdapter {
        public MyAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public int getCount() {
            return NUM_ITEMS;
        }

        @Override
        public Fragment getItem(int position) {
            return ArrayListFragment.newInstance(position);
        }
    }
FragmentPagerAdapter will detach each fragment as you swipe through the list, but keep them in memory so they can simply be reattached when the user swipes back. If you have a larger number of Fragments, the FragmentStatePagerAdapter is worth considering as it will remove them, with the downside being they need to be rebuilt as the user swipes back to them. So, if you have fewer, more complex fragments the FragmentPagerAdapter makes sense, but consider FragmentStatePagerAdapter for larger sets.
On the more simplistic side I recently wrote a ViewPager/PagerAdapter example that serves up simple TextViews. One thing to note is that if you are implementing your own PagerAdapter it is up to you, the developer, to add and remove your views to and from the ViewGroup. To facilitate this the ViewPager is passed into the PagerAdapter methods instantiateItem() and destroyItem().
    @Override
    public Object instantiateItem(View collection, int position) {
        View v = layoutInflater.inflate(...);
        ...
        ((ViewPager) collection).addView(v,0);
        return tv;
    }

    @Override
    public void destroyItem(View collection, int position, Object view) {
        ((ViewPager) collection).removeView((TextView) view);
    }
The source code for ViewPager is also included and available in <android-sdk>/extras/android/compatibility/v4/src. It is worth checking as you can generate the reference documentation from it using Javadoc. In the reference docs / source you’ll find other useful methods, for example setOnPageChangeListener(), which enables your application to track which View is currently visible.
If you are launching an app onto Android Market that uses ViewPager then please ping me on Google+ or Twitter, I’d love to see how widely it is being used and the innovative scenarios in which it appears.



Thursday 29 September 2011

Add Dynamically Rows or Linear Layout in TableView in android

Here is example that how you can add Rows or LinearLayout Dynamically in TableTayout in android.

Here is java File For My Activity to be stared in application run.


public class DynamicTable extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
      
        TableLayout mTableLayout=(TableLayout)findViewById(R.id.dynamictable);
        String Fruits[]={"apple","Banana","Mango","Coconut","Graphes","Carrot"};
        String Labels[]={"Fruitname:","Fruitname:","Fruitname:","Fruitname:","Fruitname:","Fruitname:"};
        int i=0;
       // mTableLayout.removeAllViewsInLayout();
        mTableLayout.removeAllViews();
        for(String fruits:Fruits){
         TextView label=new TextView(this);
               TextView value=new TextView(this);
         label.setTextAppearance(this, R.style.textbase);
         value.setTextAppearance(this, R.style.textbase);
         label.setText(Labels[i]);
         value.setText(fruits);
         LinearLayout mLinearLayout=new LinearLayout(this);
         mLinearLayout.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT));
         mLinearLayout.setOrientation(0);
         mLinearLayout.addView(label);
         mLinearLayout.addView(value);
         mTableLayout.addView(mLinearLayout);
        
        }
   }
}

Now we also need to known what should be in xml for layout screen :
/res/layout/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">
<TableLayout android:orientation="vertical"
android:layout_width="fill_parent" android:layout_height="fill_parent"
android:stretchColumns="1" android:id="@+id/dynamictable"
android:layout_gravity="center">
<TextView android:text="demo" android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView android:text="demo here" android:layout_width="wrap_content"
android:layout_height="wrap_content" />

</TableLayout>

</LinearLayout>


Here is my Emulator OutPut:
Enjoy.........

Wednesday 24 August 2011

How to Turn On Flash Light/LED Flash In Android Mobile?

Hello,
Here i write simple application Demo that will Turn On Your Android Mobile Flash Light i have write this Demo For Android 2.2
Please Note That I am Not Sure Weather this Demo Will Work on All Android Mobile i have just Test This In Android HTC WildFire A3333 but Same Code Will Not Work On Samsung Galaxy Ace s-5830 So please Note this.

If Any One Find Good Solution to this Than You Can Share Your Answer .

Here is my Activity Class

public class FlashLightActivity extends Activity {

    /** Called when the activity is first created. */

private Button mOnBtn;
    private Button mOffBtn;
    private Camera mCamera;
    private boolean flash_ok=false;


@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        flash_ok=getApplicationContext().getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH);
        mOnBtn = (Button) findViewById(R.id.on_btn);
        mOnBtn.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {
if(mCamera==null){
mCamera=Camera.open();
}
if(flash_ok){
processOnClick();
}else{
Toast.makeText(FlashLightActivity.this, "No Flash Light", Toast.LENGTH_SHORT).show();
}
}
});
       
        mOffBtn = (Button) findViewById(R.id.off_btn);
        mOffBtn.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {
processOffClick();

}
});
    }
private void processOffClick(){
        if( mCamera != null ){
            Parameters params = mCamera.getParameters();
            params.setFlashMode( Parameters.FLASH_MODE_OFF );
            mCamera.setParameters( params );
            mCamera.release();
            mCamera = null;

        }
    }

private void processOnClick(){
        if( mCamera != null ){
            Parameters params = mCamera.getParameters();
            params.setFlashMode( Parameters.FLASH_MODE_TORCH );
            mCamera.setParameters( params );
        }
    }
@Override
protected void onResume() {
if(mCamera==null)
mCamera=Camera.open();
super.onResume();
}
@Override
protected void onDestroy() {
if(mCamera!=null){
mCamera.release();
}

super.onDestroy();
}
@Override
public void onBackPressed() {
this.finish();
super.onBackPressed();
}
@Override
protected void onPause() {
if(mCamera!=null){
mCamera.release();
}
super.onPause();
}

}

-------------------------***************************------------------------------------------------
Here is My Manifest File You can see in that Which Permission are Require for Flash And Camera.


<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="com.android.flashlight"
      android:versionCode="1"
      android:versionName="1.0"
      android:installLocation="auto">
    <uses-sdk android:minSdkVersion="8" />
    <uses-permission android:name="android.permission.FLASHLIGHT"></uses-permission>
   
<uses-permission android:name="android.permission.CAMERA" />
  <uses-feature android:name="android.hardware.camera" />
  <uses-feature android:name="android.hardware.camera.autofocus" />
    <application android:icon="@drawable/icon" android:label="@string/app_name">
        <activity android:name=".FlashLightActivity"
                  android:label="@string/app_name" android:configChanges="orientation">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

    </application>
</manifest>


-------------------------***************************------------------------------------------------

Below is My Xml Layout 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"
    >
    <Button
        android:id="@+id/on_btn"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Flash ON" />

    <Button
        android:id="@+id/off_btn"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Flash OFF" />
</LinearLayout>


if You Find Have Much Of Android Mobile not Work You can List That Here in Comment.

Thursday 28 July 2011

How to Draw a Line In Android Using On Touch?

Here is the Way in which we can draw line in OnTouch In Android.


public class LineDrawActivity extends Activity implements OnTouchListener {
/** Called when the activity is first created. */
float x1 = 0, y1 = 0, x2 = 0, y2 = 0;
public static boolean action=false;
private Bitmap mBitmap;
private Canvas mCanvas;
private Paint mBitmapPaint;
Drawer mDrawer;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
LinearLayout mLinearLayout = (LinearLayout) findViewById(R.id.linear);
mLinearLayout.setOnTouchListener((OnTouchListener) this);
mLinearLayout.addView(new Drawer(this));

}

@Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
x1 = event.getX();
y1 = event.getY();
action=false;
//v.invalidate();
return true;
case MotionEvent.ACTION_MOVE:
x2 = event.getX();
y2 = event.getY();
v.invalidate();
return true;
case MotionEvent.ACTION_UP:
x2 = event.getX();
y2 = event.getY();
v.invalidate();
action=true;
return true;

}
return false;
}

public class Drawer extends View
{

public Drawer(Context context)
{
super(context);
mBitmap = Bitmap.createBitmap(400, 800, Bitmap.Config.ARGB_8888);
mCanvas = new Canvas(mBitmap);
mBitmapPaint = new Paint(Paint.DITHER_FLAG);
mBitmapPaint.setColor(Color.MAGENTA);
invalidate();
}

protected void onDraw(Canvas canvas)
{
Paint p = new Paint();
// Canvas mCanvas1=new Canvas(mBitmap);
p.setColor(Color.parseColor("#7CFC00"));
canvas.drawBitmap(mBitmap, 0, 0, p);
// canvas.drawLine(x1, y1, x2 , y2, p);
p.setColor(Color.RED);
// mCanvas1.drawLine(x1, y1, x2, y2,p);
mCanvas.drawLine(x1, y1, x2, y2, mBitmapPaint);
if(action)
{
x1=0;x2=0;y2=0;y1=0;
}// invalidate();
//invalidate();
}

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater=getMenuInflater();
inflater.inflate(R.menu.my_manu, menu);
return super.onCreateOptionsMenu(menu);
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId()){
case R.id.clear:
try{
mBitmap.eraseColor(android.graphics.Color.BLACK);
mDrawer=new Drawer(this);
action=true;

}catch(IllegalStateException ie){
ie.printStackTrace();
}
}
return super.onOptionsItemSelected(item);
}

}


Here is my XMl Files
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/linear"
    >
</LinearLayout>

res/menu

<?xml version="1.0" encoding="utf-8"?>
<menu
  xmlns:android="http://schemas.android.com/apk/res/android">
    <item  android:id="@+id/clear"
    android:title="Clear"
    android:icon="@android:drawable/menuitem_background"
    />
</menu>

Here is output in my  emulator:
If Any one can do more using this than you can share your idea by comments here in blog .

Here is link where you can Download Demo App
https://docs.google.com/viewer?a=v&pid=explorer&chrome=true&srcid=0B-8An4Rd1nmKZjAxZDkzYzYtNTkyNS00Mjc4LWEzMGItYWJjMTQ3NmI4NTAx&hl=en_US

Tuesday 26 July 2011

Article About Avoiding Memory Leaks in Android


Android applications are, at least on the T-Mobile G1, limited to 16 MB of heap. It's both a lot of memory for a phone and yet very little for what some developers want to achieve. Even if you do not plan on using all of this memory, you should use as little as possible to let other applications run without getting them killed. The more applications Android can keep in memory, the faster it will be for the user to switch between his apps. As part of my job, I ran into memory leaks issues in Android applications and they are most of the time due to the same mistake: keeping a long-lived reference to a Context.


On Android, a Context is used for many operations but mostly to load and access resources. This is why all the widgets receive a Context parameter in their constructor. In a regular Android application, you usually have two kinds of Context, Activity  and  Application. It's usually the first one that the developer passes to classes and methods that need a Context:
Lets’ See Some Code First:
@Override
protected void onCreate(Bundle state) {
 
super.onCreate(state);
 
 
TextView label = new TextView(this);
  label
.setText("Leaks are bad");
 
  setContentView
(label);
}
This is Simple Activity in Which we Display Text in Screen
This means that views have a reference to the entire activity and therefore to anything your activity is holding onto; usually the entire View hierarchy and all its resources. Therefore, if you leak the Context ("leak" meaning you keep a reference to it thus preventing the GC from collecting it), you leak a lot of memory. Leaking an entire activity can be really easy if you're not careful.
Now Let’s Think About Below Thing
When the screen orientation changes the system will, by default, destroy the current activity and create a new one while preserving its state. In doing so, Android will reload the application's UI from the resources. Now imagine you wrote an application with a large bitmap that you don't want to load on every rotation. The easiest way to keep it around and not having to reload it on every rotation is to keep in a static field:
private static Drawable sBackground;
 
@Override
protected void onCreate(Bundle state) {
  super.onCreate(state);
 
  TextView label = new TextView(this);
  label.setText("Leaks are bad");
 
  if (sBackground == null) {
    sBackground = getDrawable(R.drawable.large_bitmap);
  }
  label.setBackgroundDrawable(sBackground);
 
  setContentView(label);
}
This code is very fast and also very wrong; it leaks the first activity created upon the first screen orientation change. When a Drawable is attached to a view, the view is set as acallback on the drawable. In the code snippet above, this means the drawable has a reference to the TextView which itself has a reference to the activity (the Context) which in turns has references to pretty much anything (depending on your code.)
This example is one of the simplest cases of leaking the Context and you can see how we worked around it in the Home screen's source code (look for theunbindDrawables() method) by setting the stored drawables' callbacks to null when the activity is destroyed. Interestingly enough, there are cases where you can create a chain of leaked contexts, and they are bad. They make you run out of memory rather quickly.
There are two easy ways to avoid context-related memory leaks. The most obvious one is to avoid escaping the context outside of its own scope. The example above showed the case of a static reference but inner classes and their implicit reference to the outer class can be equally dangerous. The second solution is to use the Application context. This context will live as long as your application is alive and does not depend on the activities life cycle. If you plan on keeping long-lived objects that need a context, remember the application object. You can obtain it easily by calling Context.getApplicationContext() or Activity.getApplication().
In summary, to avoid context-related memory leaks, remember the following:
  • Do not keep long-lived references to a context-activity (a reference to an activity should have the same life cycle as the activity itself)
  • Try using the context-application instead of a context-activity
  • Avoid non-static inner classes in an activity if you don't control their life cycle, use a static inner class and make a weak reference to the activity inside. The solution to this issue is to use a static inner class with a WeakReference to the outer class, as done in ViewRoot and its W inner class for instance
  • A garbage collector is not an insurance against memory leaks

Wednesday 20 July 2011

Awesome Android Phone Secret Codes

DISCLAIMER: This information is intended for experienced users. It is not intended for basic users, hackers, or mobile thieves. Please do not try any of following methods if you are not familiar with mobile phones. We'll not be responsible for the use or misuse of this information, including loss of data or hardware damage. So use it at your own risk.

Awesome Android Phone Secret Codes:

had listed some secret codes of Android phone, these information will be more helpful for you, for using this you should need the Android software. The following are the secret codes...

This code can be used to get some interesting information about your phone and battery. It shows following 4 menus on screen:                                                                                                                                   

  • Phone information
  • Battery information
  • Battery history
  • Usage statistics

Android Phone Information Secret Code: *#*#4636#*#*

To get the information of your phone and battery. including Phone information, Battery information, Battery history, and Usage statistics.



Android Phone Reset Secret Code: *#*#7780#*#*


To reset your Android phone back to factory data. It will delete the things including Google account settings stored in your phone, System and application data and settings, and Downloaded applications too. I wont delete, including current system software, bundled applications, SD card files e.g. photos, music files.




This code can be used for a factory data reset. It'll remove following things:
  • Google account settings stored in your phone
  • System and application data and settings
  • Downloaded applications
It'll NOT remove:
  • Current system software and bundled applications
  • SD card files e.g. photos, music files, etc.
PS: Once you give this code, you get a prompt screen asking you to click on "Reset phone" button. So you get a chance to cancel your operation.



Android Phone Factory Format Secret Code: *2767*3855#


It is used for factory format, which will delete all files and settings, including the internal memory storage. It will also reinstall the firmware.




PS: Once you give this code, there is no way to cancel the operation unless you remove the battery from the phone. So think twice before giving this code.

Android Phone Camera Information Secret Code: *#*#34971539#*#*


It is used to get information about the camera. It includes following 4 menus: Update camera firmware in image, Update camera firmware in SD card, Get camera firmware version, and Get firmware update count. You should never use the first option otherwise your phone camera may stop working, and there is really no reason to update the camera firmware anyway.




WARNING: Never use the first option otherwise your phone camera will stop working and you'll need to take your phone to service center to reinstall camera firmware.

Android Phone Secret Code: *#*#7594#*#*


It will change the "End Call / Power" button action on your phone. By default, if you long press the button, it shows a screen asking you to select any option from Silent mode, Airplane mode and Power off. You can change this action using this code. You can enable direct power off on this button so you don't need to waste your time in selecting the option.

Android Phone Backup Secret Code: *#*#273283*255*663282*#*#*


It opens a File copy screen where you can backup your media files e.g. Images, Sound, Video and Voice memo.

Android Phone Service mode Secret Code: *#*#197328640#*#*


It can be used to enter into Service mode. You can run various tests and change settings in the service mode.

Android Phone WLAN, GPS and Bluetooth Test Secret Codes:


*#*#232339#*#* OR *#*#526#*#* OR *#*#528#*#* ¨C WLAN test (Use "Menu" button to start various tests)

*#*#232338#*#* ¨C Shows WiFi MAC address

*#*#1472365#*#* ¨C GPS test

*#*#1575#*#* ¨C Another GPS test

*#*#232331#*#* ¨C Bluetooth test

*#*#232337#*# ¨C Shows Bluetooth device address

Android Phone GTalk Secret Codes: *#*#8255#*#*


It can be used to launch GTalk Service Monitor.

Android Phone Firmware version information Secret Codes:


*#*#4986*2650468#*#* ¨C PDA, Phone, H/W, RFCallDate

*#*#1234#*#* ¨C PDA and Phone

*#*#1111#*#* ¨C FTA SW Version

*#*#2222#*#* ¨C FTA HW Version

*#*#44336#*#* - PDA, Phone, CSC, Build Time, Changelist number

Android Phone Factory Tests Secret Codes:


*#*#0283#*#* ¨C Packet Loopback

*#*#0*#*#* ¨C LCD test

*#*#0673#*#* OR *#*#0289#*#* ¨C Melody test

*#*#0842#*#* ¨C Device test (Vibration test and BackLight test)

*#*#2663#*#* ¨C Touch screen version

*#*#2664#*#* ¨C Touch screen test

*#*#0588#*#* ¨C Proximity sensor test

*#*#3264#*#* ¨C RAM version


NOTE: All above codes have been checked on Google Android phone Samsung Galaxy I7500 only but they should also work in other Google Android phones.

Wednesday 13 July 2011

How to Hide Soft Key Board Manually in Android

If you want to hide Force fully Soft Keyboard that open from any Edit Text in android than you can use following code to do .

InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
mm.hideSoftInputFromWindow(edit_text.getWindowToken(), 0);

here edit_text is EdiText object from android android.widget.EditText .