Tuesday, May 1, 2012

Android loading and Scaling bitmaps


Android provides some methods which directly loads,scales bitmap to the application.But they have their own disadvantages.They are:
  • BitmapFactory.decodeFile(filePath);
    • This method will decode the image from the specified file path.But this causes some problems like 'Skia-->bitmap retuning null' ,which means application is not able to decode the image file due to memory constraints.
  • Bitmap.createScaledBitmap(bitmap,width, height, true);
    • This method will return a scaled bitmap  with the specified width and height. There is a possibility for the method to return null if application heap is not allowing the image to scale to specified dimensions.
This tutorial helps you to load and scale a bitmaps effectively from disk  in android.

The code below first loads and scales image directly using the methods BitmapFactory.decodeFile() and Bitmap.createScaledBitmap(). If image retrieval is failed by using both of the above methods then go for scaling bitmap using BitmapOptions.
 
 
 /**
     *  Scales the Image in originalFilePath to thumbImagePath ,
     *   Saves the scaled Thumbnail Image. 
     * @param originalFilePath    Path where the Original non scaled image exist
     * @param thumbImagePath    Path in which scaled Thumbnail image is saved.
     */
    private void scaleToThumbNail(String originalFilePath,String thumbImagePath) {
       
        FileOutputStream fos = null;
        FileInputStream fis = null;
        boolean isScaled = false;
       
        try{
           
            //   height of image in px which is defined as 90dp in layout. 
            int heightPX = (int)convertDpToPixel(90, _context);
           
            int IMAGE_MAX_SIZE = heightPX;            //px value
           
            Bitmap bitmap = BitmapFactory.decodeFile(originalFilePath);
            int width = 0;
            int height = 0;
            if(bitmap != null)
            {    // bitmap created from file.
                width  = bitmap.getWidth();
                height = bitmap.getHeight();
               
        //    Calculate width and height maintaining aspect ratio.
                if(width < height)
        {   
                    width = (int)(width*((float)IMAGE_MAX_SIZE/height));
                    height = IMAGE_MAX_SIZE;
                   
                }else{
                    height = (int)(height*((float)IMAGE_MAX_SIZE/width));
                    width = IMAGE_MAX_SIZE;
                }
                try{
                    bitmap = Bitmap.createScaledBitmap(bitmap,width, height, true);
                }catch (OutOfMemoryError e) {
            e.printStackTrace();
        }
            }
           
           if(bitmap != null)
            {    // bitmap scaled succesfully
                fos = new FileOutputStream(thumbImagePath);
                isScaled = bitmap.compress(CompressFormat.PNG, 100, fos);
               
               //    Close File OutputStream
                              
            }
           if(!isScaled)
            {    // Unable to scale the image either in createScaledBitmap or  bitmap.compress
               
                //  Caculate the height and width of the decode stream without 
                //  actually decoding into memory.
                BitmapFactory.Options o = new BitmapFactory.Options();
                o.inJustDecodeBounds = true;
                fis = new FileInputStream(originalFilePath);
                BitmapFactory.decodeStream(fis, null, o);
              
               //Close File InputStream here.
              
               
                int scale = 1;
                if (o.outHeight > IMAGE_MAX_SIZE || o.outWidth > IMAGE_MAX_SIZE)
                {    // Calculating scale based in outHeight and outWidth of BitmapOptions.
                    scale = (int)Math.pow(2, (int) Math.round(Math.log(IMAGE_MAX_SIZE 
                            / (double) Math.max(o.outHeight, o.outWidth)) / Math.log(0.5)));
                }

                //  The actual decoding done here using inSampleSize property.
                //  Apply the above calculated scale value to inSampleSize of 
                //  Bitmap Factory Options.
                BitmapFactory.Options o2 = new BitmapFactory.Options();
                o2.inSampleSize = scale;
                fis = new FileInputStream(originalFilePath);
                bitmap = BitmapFactory.decodeStream(fis, null, o2);
               
                // Write the ThumbNail to thumbImagePath
                fos = new FileOutputStream(thumbImagePath);
                bitmap.compress(CompressFormat.PNG, 0, fos);
            }
         
            isScaled= true;
        }catch (Throwable e) {
            // TODO: handle exception
             e.printStackTrace();
        }finally{
        // close all streams.
        }
           
    }

Converting dip to px code which is used in above code snippet is posted below.

        
 /**
  * This method convets dp unit to equivalent device specific value in pixels. 
  * 
  * @param dp A value in dp(Device independent pixels) unit. Which we need to convert into pixels
  * @param context Context to get resources and device specific display metrics
  * @return A float value to represent Pixels equivalent to dp according to device
  */
 public static float convertDpToPixel(float dp,Context context){
     Resources resources = context.getResources();
     DisplayMetrics metrics = resources.getDisplayMetrics();
     float px = dp * (metrics.densityDpi/160f);
     return px;
 }


Hope this tutorial helps out.Any better ides invited.

Wednesday, June 22, 2011

JVM Error 102 On Blackberry startup

If you get "JVM Error 102" when starting your Blackberry, read this before you wipe everything!!

I had spent hours searching for a solution to this problem (I even went to my service provider) and all I could find was that I would have to wipe the contents of my phone and start all over again -- tough luck if I didn't have backups for my contacts, appointments, program data, etc.



What it comes down to is that the JVM 102 error means that a .cod file on your phone seems to be corrupt, so the phone refuses to load it. Why wipe everything for one bad file? You might not need to!



Follow these steps:

Download JL_Cmder

Connect your phone to your PC using the USB cable that came with it.

Run JL_Cmder and select option 2 (event log)

Scroll to the bottom of the log and look for "JVM Error 102." The line before it should tell you exactly what file is causing the error. It might look something like this. Save the file name; you will need it later.

Go to Start > Run, and type "cmd" then press Enter.

Change directory to the JL_Cmder installation folder.
e.g., type: cd "C:\Program Files\JL_Cmder\" and press enter

Type the following command to remove the offending file:

javaloader.exe -u erase -f FILENAME

where FILENAME is the name of the .cod file.

Disconnect your phone from your PC and restart it.



This might not be a permanent solution, but it should at least let you boot up your Blackberry so that you can back up all your data before reinstalling everything.


reference:

http://supportforums.blackberry.com/t5/BlackBerry-Curve/JVM-Error-102-BEFORE-YOU-WIPE-YOUR-SYSTEM/td-p/92398

Wednesday, June 15, 2011

Install and Uninstall Blackberry COD file using Command prompt

To uninstall the cod using command prompt

Go to Command prompt

C:\Program Files\Research In Motion\BlackBerry JDE 4.7.0\bin\JavaLoader.exe -u erase -f yourcod.cod

The above mentioned is specific to my device.It may vary from device to device depending on installation.

To install the cod Using command prompt

Go to command prompt

C:\Program Files\Research In Motion\BlackBerry JDE 4.7.0\bin\JavaLoader.exe -u load yourpath\yourcod.cod

Mention the local path of COd File while installation

Monday, May 30, 2011

Share in Android

Android provides a nice feature IntentFilter.An application is said to accept share if and only if Activity has IntentFilter ACTION_SEND in Manifest.All the apps such as Twitter,FaceBook,Mail etc.. have ACTION_SEND as Intent Filter in their Manifest Files.


       
Intent picMessageIntent = new Intent(android.content.Intent.ACTION_SEND);  
picMessageIntent.setType("text/*"); 
picMessageIntent.putExtra(Intent.EXTRA_TEXT, "http://www.gpuri.com/images/705/70592.png");
startActivity(Intent.createChooser(picMessageIntent, "Share your picture using:"));

The above code pops a list of apps to recive share event like



Inorder to share to a particular App,First of all Know whether target application is installed in the device using packageManager.

Use following piece,

     
    Intent sendShareIntent = new Intent(Intent.ACTION_SEND);
    PackageManager pm = getPackageManager();
    List activityList = pm.queryIntentActivities(sendShareIntent, 0);
         
    for (int i = 0; i < activityList.size(); i++) { 
        ResolveInfo app = activityList.get(i);
        Log.e("###", "Name: " + app.activityInfo.name);
           
    }
            
      
So,I will check for my FaceBook app installed in my phone or not and i'll directly start facebook share activity using Intent
              
     Intent sendShareIntent = new Intent(Intent.ACTION_SEND);
     sendShareIntent.setClassName("com.facebook.katana", "com.facebook.katana.ShareLinkActivity");
     sendShareIntent.setType("text/*");
     sendShareIntent.putExtra(android.content.Intent.EXTRA_TEXT, "http://www.google.com/");
     startActivity(sendShareIntent);      
  
This will activate facebook app directly if is present.It would be like


For Twitter the package is "com.twitter.android" and share class is "com.twitter.android.PostActivity".

For all the data like text,image,video just set the type of intent to "text/*" and pass the required url in putExtra(ExtraText).

Currently, In FaceBook we cannot share text.At any cost we have to send only Link URL.Otherwise it will ask for the link to post.

Run On UIThread in Android

To push the piece of code running in a thread to main UI thread ,

MyActivityObject.runOnUiThread(new Runnable() {
       
 @Override
        public void run() {
                //code out here
        }
  });
 
One of the usecase will be, modify an UI element's  data from doinbackground() 
method of Asynctask.

Tuesday, May 10, 2011

Loader for WebView : Android

To set Loader for webview,Set the webviewclient and override OnpageStarted,onPageFinished and onReceivedError.

ProgressDialog _dialog ; //  Global Variable

WebView webView = (WebView)findViewById(R.id.webview);
webView.setWebViewClient(new WebViewClient(){

   
   @Override
   public void onPageStarted(WebView view, String url, Bitmap favicon) {
        _dialog =ProgressDialog.show(CurrentActivity.this, "", "Please wait...");
    super.onPageStarted(view, url, favicon);
   }  //  end  OnPageStarted

   @Override
   public void onPageFinished(WebView view, String url) {
    super.onPageFinished(view, url);
    _dialog.dismiss();
   }  //  end OnPageFinished()
   
   @Override
   public void onReceivedError(WebView view, int errorCode,
     String description, String failingUrl) {
    super.onReceivedError(view, errorCode, description, failingUrl);
    try{
     _dialog.dismiss();
    }catch (Exception e) {
     // TODO: handle exception
    }
   }  //  end onReceivedError()
   
  }); // end WebViewclient

When onPageStarted is called ,start the dialog and finish in onPageFinished , onRecievedError() methods.

LWUIT 1.5 and latest Netbeans6.9 for J2Me updates

Attended Oracle developer seminar,Chen revealed some of the latest features of the upcoming LWUIT to be released in a month or so.

Key features:
1)Introduction of GUI builder.
This would minimize the time for UI development.We can do the total page design in Resource Editor.The internal methods of components can be accessed directly from Resource Editor.This will gonna be an amazing feature for developers.
2)Cross platform support
Cross Platfrom support enables to install our build in various devices like nokia,Blackberry etc.For Blackberry we have build the code in a different way.Yet to know.

In latest Netbeans 6.9 we have many features that will be enabled on J2ME integration.They are:
1)On Device Debugging.
Till date there is no onDeviceDebugging for NetBeans.LWUIT 1.5 adds Device Debugging.
2)CPU and N/w Monitor.
The CPU and n/w monitor will trace the amount of time taken to connect,which threads are taking more time etc.
3)List of devices support
An option under Netbeans 6.9 enables us to get the list of devices supported by our Midp . And also we can just check the JSR ,which will give the list of suppoted devices.
4)Different resolutions testing.One solution
The emulator can be maximized ,minimized and change to size what ever you want using cursor.So all resolutions testing can be done very easily.