Sunday 26 September 2010

Making Asynchronous calls in Android

I am sharing today a code snippet by which you can make an Asynchronous call in Android


It will be better that this Asynchronous class should be made as an inner class in an activity in which you wants to have an Asynchornous call and dont let UI hang till the process is completed.

private class AsyncClass extends AsyncTask {

        private final ProgressDialog dialog = new ProgressDialog(ABCActivity.this);
       
       
       
        @Override
        protected Void doInBackground(String... params) {
           
            //Make a call here during which you wants that UI shouldnt be hang. Making a server hit or saving something into DB etc. Remember the stuff added here should be non-UI.
           
            return null;
        }
       
       
        protected void onPreExecute() {
            dialog.setMessage("Fetching info...");
            dialog.setCancelable(false);
            dialog.show();






//Here you can add UI stuff which you wanted to show before making the sync call.
           
        }
       
        protected void onPostExecute(final Void unused) {
            if (dialog.isShowing()) {
                dialog.dismiss();
                               
            }
           
           //Here you can add UI stuff which you wanted to show after making the sync call.
       
        }

    }

Thursday 29 April 2010

Found shared references to a collection hibernate

 Today when i was working on my project i saw a very strange bug saying "Found shared references to a collection hibernate" with a long stacktrace. After wasting a long time browsing through different sites. I started seeing the code, there i found a very small thing which solved my problem and it was that i initialized the variable before starting FOR loop and was trying to add multiple objects of the same memory reference again and again. For e.g.

ArrayList list = new ArrayList();
String str= new String("test");
for(int i=0; i
    list.add(i);
}
here you will get the same Found shared references error. Therefore i simply brougth the initialization into the FOR loop and it got resolved

Thursday 22 April 2010

Disable the parent page when thickbox opens using jquery

I faced a problem that when the thickbox opens i can still TAB through the links by pressing tab button despite the model=true and all the stuff i can do through thickbox. After searching long i found that this is the issue all thickbox like libraries are facing that they cant block their parent page while the child div is open. So i did a workaround hope so that it will be useful for someone else too.

$('#content').live('keydown', function(e) {
  var keyCode = e.keyCode;

  if (keyCode == 9) {
    e.preventDefault();

  }
});

$('#footer').live('keydown', function(e) {
  var keyCode = e.keyCode;

  if (keyCode == 9) {
    e.preventDefault();

  }
});

$('#header').live('keydown', function(e) {
  var keyCode = e.keyCode;

  if (keyCode == 9) {
    e.preventDefault();

  }
});

This thing allows tabbing to be done in the child page while not allowing to tab on the parent page. Content, footer, and header are the id's of the divs in which i had my main content. footer and header

Tuesday 13 April 2010

Google launching android powered gpad

Google launching Android-based gPad???
After starting competition with Apple’s iPhone by throwing Nexus One into the market and giving the minimum standards what does Android based phone should have and showing that what can an Android based phone can do - does now Google thinking to launch Android based slate???
After seeing success of iPad, Google has started quickly working on Android based tablet which will be using Google’s branded hardware as Nexus One did.

Reports saying that Google has finally decided to launch its own Android-powered tablet which is right now in secrecy mode. The manufacturer yet is unknown but the people which are working on the project says that Google is testing with a few companies to explore delivery of books, magazines and other content on a tablet.

Sunday 28 March 2010

Gallery Example

Often we need in Android to make a view which contains all the images in a row and we can browse them by sliding them....Gallery is the control in android for this....

First of all you will have to make an inner class which extends BaseAdapter. Here's the code

public class ImageAdapter extends BaseAdapter {

       
        int mGalleryItemBackground;
        private Context mContext;

        private int[] mImageIds = {
                R.drawable.icon,R.drawable.android,R.drawable.array_03
        };


        public ImageAdapter(Context c) {
            mContext = c;
            TypedArray a = obtainStyledAttributes(R.styleable.default_gallery_android_galleryItemBackground ,mImageIds);
            mGalleryItemBackground = a.getResourceId(
                    R.styleable.default_gallery_android_galleryItemBackground, 0);
            a.recycle();
        }

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

        public Object getItem(int position) {
            return position;
        }

        public long getItemId(int position) {
            return position;
        }

        public View getView(int position, View convertView, ViewGroup parent) {
            ImageView i = new ImageView(mContext);

            i.setImageResource(mImageIds[position]);
            i.setLayoutParams(new Gallery.LayoutParams(150, 100));
            i.setScaleType(ImageView.ScaleType.FIT_XY);
            i.setBackgroundResource(mGalleryItemBackground);

            return i;
        }
}

Now the Activity class should look like this...

public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
       
        Gallery g = (Gallery) findViewById(R.id.gallery);
        g.setAdapter(new ImageAdapter(this));

        g.setOnItemClickListener(new OnItemClickListener() {
            public void onItemClick(AdapterView parent, View v, int position, long id) {
                Toast.makeText(HelloGallery.this, "" + position, Toast.LENGTH_SHORT).show();
            }
        });
}


In your xml code you will just have to add these lines...

<?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"
>
<Gallery xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/gallery"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>

</LinearLayout>

At the end your program will look like this





Monday 28 December 2009

Time Picker Example Android

Time Picker Example is completely similar to Date Picker example except that we explicitly add 0 with single digit number

Here's the java code


public class TimePicker extends Activity {

private TextView mTimeDisplay;
private Button mPickTime;

private int mHour;
private int mMinute;

static final int TIME_DIALOG_ID = 0;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
      
     // capture our View elements
        mTimeDisplay = (TextView) findViewById(R.id.timeDisplay);
        mPickTime = (Button) findViewById(R.id.pickTime);

        // add a click listener to the button
        mPickTime.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                showDialog(TIME_DIALOG_ID);
            }
        });

        // get the current time
        final Calendar c = Calendar.getInstance();
        mHour = c.get(Calendar.HOUR_OF_DAY);
        mMinute = c.get(Calendar.MINUTE);

        // display the current date
        updateDisplay();
    }
  
    @Override
    protected Dialog onCreateDialog(int id) {
        switch (id) {
        case TIME_DIALOG_ID:
            return new TimePickerDialog(this,
                    mTimeSetListener, mHour, mMinute, false);
        }
        return null;
    }
  
 // updates the time we display in the TextView
    private void updateDisplay() {
        mTimeDisplay.setText(
            new StringBuilder()
                    .append(pad(mHour)).append(":")
                    .append(pad(mMinute)));
    }
  
 // the callback received when the user "sets" the time in the dialog
    private TimePickerDialog.OnTimeSetListener mTimeSetListener =
        new TimePickerDialog.OnTimeSetListener() {
     public void onTimeSet(android.widget.TimePicker view, int hourOfDay, int minute) {
                mHour = hourOfDay;
                mMinute = minute;
                updateDisplay();
            }





        };
      
        private static String pad(int c) {
            if (c >= 10)
                return String.valueOf(c);
            else
                return "0" + String.valueOf(c);
        }
      

Your main.xml should look like this

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical">

<TextView android:id="@+id/timeDisplay"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=""/>

<Button android:id="@+id/pickTime"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Change the time"/>

</LinearLayout>

 

Struts2 Double Click issue in Firefox

Problem:
The problem i faced was that some of my struts2 actions are being called twice or sometimes thrice in Firefox only when clicked once from my website or UI. This is the only place where IE was working perfectly fine and FF was troubling..lolz (and because of it i was more worried).


Symptoms:


I took myself in debugging mode and was seeing that actions are being called twice. Secondly my log4j logging was also proving this.
I used FireBug to see the how many hits are being generated and it showed that as soon as i clicked once on the hyperlink, two (or three in one case) hits generated. So the issue was finally proved that it is due to some UI stuff.


Due to it for a glimpse of a second i was being shown some validation error(as when the form is submitted second time, it was submitted with null values) plus things got worst when my code started showing exception(Due to null values)


Solution:
After googling for a week(although for sometime i dropped this issue and got involved in other but it took a week) i found its solution that this happens due to empty image tag  <img src=""/>


but the thing was i wasnt using any empty image tag in the whole page. But after some help i figured it out that it was due to background-image


Actually it happens because for images another call is being generated and as we are specifying that background image is null therefore it was hitting the default action we were specifying in s:submit tag


About server being hit thrice, i did a mistake that instead of defining just only href or onClick...i defined both of them. So the problem got resolved when i remove one of them