Search This Blog

Tuesday 30 October 2012

final keyword in java and android

final is very common keyword to discussion in Java. final used in different places with different meanings. but its inherit meaning remains same. Let discuss some case where we need to use final.

1) To prevent the inheritance  : Let have two class A and B. A extends by B. and it worked fine

 public class A {
  public void prind() {
   System.out.print("You can inherit me");
  }
 }
 public class B extends A{
  @Override
  public void prind() {
   super.prind();
  }
 }

But if you changes prind() method to final then you can not override this method in B class

 public class A {
  public final void prind() {
   System.out.print("You can not inherit me");
  }
 }
 public class B extends A{
  @Override
  public void prind() {  //   Cannot override the final method from A
  super.prind();                //   Quick fix -> remove final 
  }
 } 
 
2) Using as constant : a variable followed by final keyword works as a constant. you can not re assigned values inside this variable
                        private final int m = 10;
but now you can not re assign value inside m.if you do this, it will show compile time error
                  m = 10;         // Compile error ->The final field m cannot be assigned
         
But it will be exceptional when we talk about one Array followed by keyword final
            private final int[] a = new int[5];
assigning values to index of a is valid and works well
            this.a[0] = 30; // Successfully worked


Wait wait........Explain a bit - while creating private final int[] a = new int[5], we assign array a to size of 5. So its final now. we can not changes size of array. But the memory slot we assign for each element of array is not constant we can changes its values
so this.a[0] = 30; is valid but
        this.a=new int[10];          is invalid

Finally it works same for array also

Friday 26 October 2012

Difference between Weak reference and Soft reference in android and Java as well

In java as well as android, two concept are highly important but people are not much aware about these concept. These are weak reference and soft reference. They ensure to avoid memory over flow error and ensure fast caching of images. By name, They both seems similar but had lots of difference  If i say they are just opposite to each other , then its true.

Weak references : Weak reference is reference to an object that does not put strong force to remain object in memory. It allow garbage collector to collect object that it pointing. Take an example of creating Weakreference

      HashMap<String, WeakReference<Bitmap>> cache = new HashMap<String, WeakReference<Bitmap>>();

 cache.get(key) will return a Bitmap object that is pointed by Weakreference . As we know it does not put much force to keep this reference So you never know when this Bitmap will garbage collected and it starts returning null. Weak reference avoid memory overflow error by allowing garbage collector to collect its object without any algorithm

Where its Useful ?

Now the question arise when to use Weakreference,where memory reclaim highly needed. In simple case,avoiding Weakreference is recommended.

Soft Reference : Soft reference provide a strong reference to an object so that i will garbage collected as late as possible . Lets create one example
  
               private HashMap<String, SoftReference<Bitmap>> cache = new HashMap<String, SoftReference<Bitmap>>();

Soft Reference is helpful while you want to cache images to avoid time frame that consume in loading from Disk every time. It will make navigation fast and interactive. cache.get(key) will not return null as late as possible. It will garbage collected when VM running out memory.

Mechanism for garbage collection of soft reference from android developer official site

The system may delay clearing and en-queue soft references, yet all SoftReferences pointing to softly reachable objects will be cleared before the run time throws an   OutOfMemoryError.

Unlike a WeakReference, a SoftReference will not be cleared and en-queue until the run time must reclaim memory to satisfy an allocation.

From Oracle About Soft reference-

All soft references to softly-reachable objects are guaranteed to have been cleared before the virtual machine throws an OutOfMemoryError. Otherwise no constraints are placed upon the time at which a soft reference will be cleared or the order in which a set of such references to different objects will be cleared. Virtual machine implementations are, however, encouraged to bias against clearing recently-created or recently-used soft references.

Conclusion

  •     SoftReference should be cleared and en-queue as late as possible, that is, in case the VM is in danger of running out of memory.

  •    WeakReference may be cleared and en-queue as soon as is known to be weakly-referenced. WeakReference garbage collected as soon as possible when VM needed memory

Monday 22 October 2012

Advance Java : Inner Classes Concept in Java

Inner classes was introduces in JDK 1.1. And Inner class refer to a class appear with in

• class declarations
• method bodies
• expressions

Reason To Use Nested Classes From docs.oracle.com

Logical grouping of classes—If a class is useful to only one other class, then it is logical to embed it in that class and keep the two together. Nesting such "helper classes" makes their package more streamlined.

Increased encapsulation—Consider two top-level classes, A and B, where B needs access to members of A that would otherwise be declared private. By hiding class B within class A, A's members can be declared private and B can access them. In addition, B itself can be hidden from the outside world.

More readable, maintainable code—Nesting small classes within top-level classes places the code closer to where it is used.

Scope of an Inner class differ according to which type of Inner class you are using. We have four type in Inner Class

  •   Member Inner (MI) Classes
  •   Local Inner (LI) Classes
  •   Anonymous Inner (AI) Classes
  •   Static Inner (SI) Classes


  Let see one Example of Member Inner Class

public class A {

 public static void main(String[] args) {
  /**
   * Accessing Member Inner Classes
   */
  MemberInnerClass member = new A().new MemberInnerClass();
  member.printMessage();
 }

 public class MemberInnerClass {

  public void printMessage() {
   System.out.print("I am inside Member Inner Claas");
  }
 }
} 
  
 To accessing MI you have to create Object of Parent class(outer class). You can make MI Read Only by creating on private constructor

Local Inner Class is created inside a Method and its scope remains same method Member Variables


public class A {

 public static void main(String[] args) {
  /**
   * Accessing Local Inner Classes
   */
  new A().LocalLimit("I am inside Local Inner Class");
 }

 public void LocalLimit(final String message) {
  
  class LocalInnerCalss {
   public void printMessage() {
    System.out.print(message);
   }
  }
  new LocalInnerCalss().printMessage();
 }
}

Static Inner Class-- Its useful when modeling tightly coupled entities.Static class also provide Providing meaningful namespaces


public class StaticInner {
 public static void main(String[] args) {
  /**
   * Accessing Static Inner Classes
   */
  StaticInner.MemberInnerClass member = new StaticInner.MemberInnerClass();
  member.printMessage();
 }

 public static class MemberInnerClass {

  public void printMessage() {
   System.out.print("I am inside Static Inner Claas");
  }
 }
}

About Anonymous Inner Class, I will explain in a separate article as its need more explanation.

Now At the End some Use full tips to remember

Remember while declaring an inner class
• MI and SI appear within the body of a class
• LI and AI appear within the body of a method

Remember while accessing outer fields
• Both MI, LI and AI can refer to fields of their enclosing scope
• A SI can’t, since it doesn’t have an enclosing instance!

Article You May Like

Synchronization Of thread in Java, Anonymous Inner Class Explanation

Saturday 20 October 2012

Creating DatePicker using DialogFragment in android

Android has transform its UI after 3.1. They had deprecated Activity Group and so many other thing and introduce Fragment. Maintaining Fragment is comparatively easy. Just few month back they they introduce DialogFragment and deprecated showDialog(id) method. it affects creating DatePicker and TimePicker also.so today we will discuss about creating DatePicker using brand new concept DialogFragment.

For More Information on  Fragment Visit Integration Of Action Bar And Fragment

Creating DatePicker using DialogFragment is quite easy. Lets divide it in step and make it more easy :)

Step 1) Repeated step create a new Project

Step 2) Add one button to your main xml. So that on click this button we can show Date Picker

<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"
    android:orientation="vertical" >

    <Button
        android:id="@+id/date"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:layout_marginTop="50dp"
        android:text="@string/show_date_picker_fragment" />

</LinearLayout>  
View Of XML

Step 3) Change your activity to a Fragment Activity and replace with below code

package com.home;

import java.util.Calendar;

import android.app.DatePickerDialog.OnDateSetListener;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.DatePicker;
import android.widget.Toast;

import com.dialog.DatePickerFragment;

public class MainActivity extends FragmentActivity {

 @Override
 public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
  findViewById(R.id.date).setOnClickListener(new OnClickListener() {

   @Override
   public void onClick(View v) {
    showDatePicker();
   }
  });
 }

 private void showDatePicker() {
  DatePickerFragment date = new DatePickerFragment();
  /**
   * Set Up Current Date Into dialog
   */
  Calendar calender = Calendar.getInstance();
  Bundle args = new Bundle();
  args.putInt("year", calender.get(Calendar.YEAR));
  args.putInt("month", calender.get(Calendar.MONTH));
  args.putInt("day", calender.get(Calendar.DAY_OF_MONTH));
  date.setArguments(args);
  /**
   * Set Call back to capture selected date
   */
  date.setCallBack(ondate);
  date.show(getSupportFragmentManager(), "Date Picker");
 }

 OnDateSetListener ondate = new OnDateSetListener() {
  @Override
  public void onDateSet(DatePicker view, int year, int monthOfYear,
    int dayOfMonth) {
   Toast.makeText(
     MainActivity.this,
     String.valueOf(year) + "-" + String.valueOf(monthOfYear)
       + "-" + String.valueOf(dayOfMonth),
     Toast.LENGTH_LONG).show();
  }
 };

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

}

Step Final ) Now you are done from your side..We just need to create one class that will extends DialogFragment and will return a DatePicker .

package com.dialog;

import android.app.DatePickerDialog;
import android.app.DatePickerDialog.OnDateSetListener;
import android.app.Dialog;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;

public class DatePickerFragment extends DialogFragment {
 OnDateSetListener ondateSet;

 public DatePickerFragment() {
 }

 public void setCallBack(OnDateSetListener ondate) {
  ondateSet = ondate;
 }

 private int year, month, day;

 @Override
 public void setArguments(Bundle args) {
  super.setArguments(args);
  year = args.getInt("year");
  month = args.getInt("month");
  day = args.getInt("day");
 }

 @Override
 public Dialog onCreateDialog(Bundle savedInstanceState) {
  return new DatePickerDialog(getActivity(), ondateSet, year, month, day);
 }
}  

See how to integrate Action bar with Tab

Android Developers Blog: Google Play Seller Support in India

That's the news i want to hear from the last few month. I am happy that i can post paid application on market. It will going to boost android development and competition as well in my country. Indian has potential to add value to android in term of developer and user both. We have huge market

Android Developers Blog: Google Play Seller Support in India

Wednesday 10 October 2012

Android : Lazy loading and Caching of Images with Image downloader

Downloading does always fascinated me. When we download movie, song or Wallpaper. But when i went into development then i came to know how much complication involve in that.
I saw so many people struggling in downloading. So i decide to make one download manager for all android developer. And now i am revealing all my hard work to you guys so that it make your work much easier.

When to use AhamdDownloaderManager :->

   when you want to download images
  •  When you want to cache images for later use
  • When you want to handle network failure and other error.

When not to use AhamdDownloaderManager :->

If you want to download Video, Mp3 then its not for you guys

Qualities of AhamdDownloaderManager :->

  • It will check automatically your sdcard is mounted or not and give you alert
  • Return a callback with Bitmap value as null if in any case Image is not successfully downloaded
  • Save all image inside sdcard and later on it use these image if URL name is same.
  •  Fast

How to use AhamdDownloaderManager :->


Step 1) Download Jar and add to your project. Download this Jar and to your project
   
Step 2) It handle progress untill your images downloaded so create your layout similar like this


<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/imagrParent"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >

    <ImageView
        android:id="@+id/imageView"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_gravity="center_vertical|center_horizontal"
        android:contentDescription="@string/app_name"
        android:scaleType="fitXY" >
    </ImageView>

    <ProgressBar
        android:id="@+id/bar"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:visibility="visible" />

</RelativeLayout>

Step 3) Now set AhamdDownloaderManager to load images


  ImageView img = (ImageView) findViewById(R.id.imageView);
  ProgressBar bar = (ProgressBar) findViewById(R.id.bar);
  img.setTag(Url_To_download);
  AhmadDownloadManager ahmadDownload = new AhmadDownloadManager(this);
  ahmadDownload.DisplayImage(Url_To_download, this, img, bar, this);

Step 4) Handle failure : - We have one call back interface that we have to implement in Step 3


 @Override
 public void result(Bitmap bitmap) {
  Log.i("AhmadDownloadCallback", "Not able to download");
 }

 

Update 1.0.1 : I updated it on demand of my reader for reason likes.

1) How to scale image on base of custom height and width : New download jar have method 


ahmad.setCustomHeight(100, 100);

 

2) Avoiding condition if your URL is null : set Custom URL in new jar


ahmad.setCustomURL("www.google.com");

Download Sample Project

Tuesday 9 October 2012

Viewpager Example in android

Viewpager  is  the best way to switching among view. It provide a way to swipe views from left to right and right to left. Viewpager provide strong way to swipe any views but here i have taken ImageView to swipe left and right.

Viewpager is strong widget as well as very simple. So here we go step wise solution  with explanation.

Add the support library while you are creating project because Viewpager does not support in lower android version 


Step 1) After creating a fresh project. change your main.xml to as follow so that it have one Viewpager widget in it.


<?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" >

    <android.support.v4.view.ViewPager
        android:id="@+id/myfivepanelpager"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</LinearLayout>


Step 2) Now our main concern is to bind data inside a Viewpager so that you can easily swipe. PagerAdapter bind the data to Viewpager and create view dynamically when needed. In PagerAdapter we remove the view as soon as its use is over so that we can avoid memory wastage . So create one new class and paste below code inside it.


package com.horizontalscrollviewwithpageindicator;

import android.app.Activity;
import android.os.Parcelable;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;

public class ViewPagerAdapter extends PagerAdapter {

 Activity activity;
 int imageArray[];

 public ViewPagerAdapter(Activity act, int[] imgArra) {
  imageArray = imgArra;
  activity = act;
 }

 public int getCount() {
  return imageArray.length;
 }

 public Object instantiateItem(View collection, int position) {
  ImageView view = new ImageView(activity);
  view.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,
    LayoutParams.FILL_PARENT));
  view.setScaleType(ScaleType.FIT_XY);
  view.setBackgroundResource(imageArray[position]);
  ((ViewPager) collection).addView(view, 0);
  return view;
 }

 @Override
 public void destroyItem(View arg0, int arg1, Object arg2) {
  ((ViewPager) arg0).removeView((View) arg2);
 }

 @Override
 public boolean isViewFromObject(View arg0, Object arg1) {
  return arg0 == ((View) arg1);
 }

 @Override
 public Parcelable saveState() {
  return null;
 }
}

Step 3) This is the final step and Viewpager complete. As in PagerAdapter , i have created one ImageView to display as child of Viewpager so we need one image array to show image. I have image in my drawable folder. I created one array like this


private int imageArra[] = { R.drawable.antartica1, R.drawable.antartica2,
   R.drawable.antartica3, R.drawable.antartica4,
   R.drawable.antartica5, R.drawable.antartica6,
   R.drawable.antartica7, R.drawable.antartica8 };

Now we just need to attach our PagerAdapter to android Viewpager . So we will change our main activity code to as following ---


package com.horizontalscrollviewwithpageindicator;

import android.app.Activity;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.view.Menu;

public class PageIndicatorActivity extends Activity {

 @Override
 public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
  ViewPagerAdapter adapter = new ViewPagerAdapter(this, imageArra);
  ViewPager myPager = (ViewPager) findViewById(R.id.myfivepanelpager);
  myPager.setAdapter(adapter);
  myPager.setCurrentItem(0);
 }

 private int imageArra[] = { R.drawable.antartica1, R.drawable.antartica2,
   R.drawable.antartica3, R.drawable.antartica4,
   R.drawable.antartica5, R.drawable.antartica6,
   R.drawable.antartica7, R.drawable.antartica8 };

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

}

See the video to get perfect idea about what's the outcome will be. And if you are not able to follow the above procedure than no need to worry. Just download the source code and play with it


                                                         
                                                       

Download Source Code

Android News and source code