Thursday 20 February 2014

Android capture image from Camera and Gallery

Hello Droid Friends,

Today , I am sharing the code for capture Image from Camera and Gallery . Actually
I found different behavior of Camera capture Intent and Gallery Intent on different
Android devices .

Here are the few issue I found while capturing Image from Camera and Gallery:
1. In some devices like Samsung  the Camera capture Intent returns
    data null or some time gallery Intent returns data null.
2. Android Camera : data intent returns null
3. Android camera capture activity returns null Uri
4. onActivityResult Camera resulting data as null (SAMSUNG)

I too faces all these issue, then I uses below code which works dine for me.

Code:.

1. MainActivity.java:


package com.gallerycamera.demo;

import java.io.IOException;

import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;

public class MainActivity extends Activity {

 private static int THUMBNAIL_SIZE = 300;
 private static final int YOUR_SELECT_PICTURE_REQUEST_CODE = 232;

 private Button button;
 private ImageView image;
 private Bitmap bmp;

 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);

  image = (ImageView) findViewById(R.id.activity_main_image);
  button = (Button) findViewById(R.id.activity_main_button);
  button.setOnClickListener(buttonListener);
 }

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

 @Override
 protected void onDestroy() {
  super.onDestroy();
  if (bmp != null && !bmp.isRecycled()) {
   bmp.recycle();
   bmp = null;
  }
 }

 private View.OnClickListener buttonListener = new View.OnClickListener() {
  @Override
  public void onClick(View v) {
   // Determine Uri of camera image to save.
   FileUtils.createDefaultFolder(MainActivity.this);
   //final File file = FileUtils.createFile(FileUtils.IMAGE_FILE);
   //outputFileUri = Uri.fromFile(file);
 
   // Camera.
   final Intent captureIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
   //captureIntent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
 
   final Intent galleryIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
   //galleryIntent.setType("image/*");
   // Filesystems
   // galleryIntent.setAction(Intent.ACTION_GET_CONTENT); // To allow file managers or any other app that are not gallery app.
 
   final Intent chooserIntent = Intent.createChooser(galleryIntent, "Select Image");
   // Add the camera options.
   chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, new Intent[] { captureIntent });
   startActivityForResult(chooserIntent, YOUR_SELECT_PICTURE_REQUEST_CODE);
  }
 };

 @Override
 public void onActivityResult(int requestCode, int resultCode, Intent data) {
  try {
   //if (resultCode == Activity.RESULT_OK) {
    if (requestCode == YOUR_SELECT_PICTURE_REQUEST_CODE) {
      Bundle extras2 = data.getExtras();
      if (extras2 != null) {    
       Uri selectedImage = data.getData();
       if (selectedImage != null) {
        String[] filePathColumn = {MediaStore.Images.Media.DATA};
        Cursor cursor = getContentResolver().query(
              selectedImage, filePathColumn, null, null, null);
        cursor.moveToFirst();

        int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
        String filePath = cursor.getString(columnIndex);
        cursor.close();
        
        bmp = ImageUtils.getThumbnail(this,filePath, THUMBNAIL_SIZE);
        image.setImageBitmap(bmp);
        bmp = null;
       }
      }
     }
    //}
   
  } catch (IOException e) {
   System.out.println(e.getMessage());
  }
 }

}



2. ImageUtils.java

package com.gallerycamera.demo;

import java.io.FileNotFoundException;
import java.io.IOException;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;

public class ImageUtils {

 /**
  * Get a thumbnail bitmap.
  * @param uri
  * @return a thumbnail bitmap
  * @throws FileNotFoundException
  * @throws IOException
  */
 public static Bitmap getThumbnail(Context context, String filePath, int thumbnailSize) throws FileNotFoundException, IOException {
  BitmapFactory.Options onlyBoundsOptions = new BitmapFactory.Options();
  onlyBoundsOptions.inJustDecodeBounds = true;
  onlyBoundsOptions.inDither = true;// optional
  onlyBoundsOptions.inPreferredConfig = Bitmap.Config.ARGB_8888;// optional
  BitmapFactory.decodeFile(filePath, onlyBoundsOptions);
  if ((onlyBoundsOptions.outWidth == -1) || (onlyBoundsOptions.outHeight == -1))
   return null;

  int originalSize = (onlyBoundsOptions.outHeight > onlyBoundsOptions.outWidth) ? onlyBoundsOptions.outHeight : onlyBoundsOptions.outWidth;

  double ratio = (originalSize > thumbnailSize) ? (originalSize / thumbnailSize) : 1.0;

  BitmapFactory.Options bitmapOptions = new BitmapFactory.Options();
  bitmapOptions.inSampleSize = getPowerOfTwoForSampleRatio(ratio);
  bitmapOptions.inDither = true;// optional
  bitmapOptions.inPreferredConfig = Bitmap.Config.ARGB_8888;// optional
  Bitmap bitmap = BitmapFactory.decodeFile(filePath, bitmapOptions);
  return bitmap;
 }

 /**
  * Resolve the best value for inSampleSize attribute.
  * @param ratio
  * @return
  */
 private static int getPowerOfTwoForSampleRatio(double ratio) {
  int k = Integer.highestOneBit((int) Math.floor(ratio));
  if (k == 0)
   return 1;
  else
   return k;
 }
 
}


Download code Camera and Gallery Demo

Hope this will help some one.
Enjoy Coding.... :)


Sunday 29 December 2013

Android make Image Sharper | Android image Blur Issue

Hello Droid Guys,
    Today , I am going to share a sample code which helps you in making image
more sharper and clear also helps you in fixing image Blur issue .This is based on
Convolution Matrix Theorem.

About Convolution Matrix : Check this link

Image Before:


Image After :


 1. ImageHelper.java : This is our helper class which helps in processing image
     sharper/


package com.exampl.imagerun;

import android.graphics.Bitmap;
import android.graphics.Color;
 
public class ImageHelper
{
    public static final int SIZE = 3;
 
    public double[][] Matrix;
    public double Factor = 1;
    public double Offset = 1;
 
   //Constructor with argument of size
    public ImageHelper(int size) {
        Matrix = new double[size][size];
    }
 
    public void setAll(double value) {
        for (int x = 0; x < SIZE; ++x) {
            for (int y = 0; y < SIZE; ++y) {
                Matrix[x][y] = value;
            }
        }
    }
 
    public void applyConfig(double[][] config) {
        for(int x = 0; x < SIZE; ++x) {
            for(int y = 0; y < SIZE; ++y) {
                Matrix[x][y] = config[x][y];
            }
        }
    }
 
    public static Bitmap computeConvolution3x3(Bitmap src, ImageHelper matrix) {
        int width = src.getWidth();
        int height = src.getHeight();
        Bitmap result = Bitmap.createBitmap(width, height, src.getConfig());
 
        int A, R, G, B;
        int sumR, sumG, sumB;
        int[][] pixels = new int[SIZE][SIZE];
 
        for(int y = 0; y < height - 2; ++y) {
            for(int x = 0; x < width - 2; ++x) {
 
                // get pixel matrix
                for(int i = 0; i < SIZE; ++i) {
                    for(int j = 0; j < SIZE; ++j) {
                        pixels[i][j] = src.getPixel(x + i, y + j);
                    }
                }
 
                // get alpha of center pixel
                A = Color.alpha(pixels[1][1]);
 
                // init color sum
                sumR = sumG = sumB = 0;
 
                // get sum of RGB on matrix
                for(int i = 0; i < SIZE; ++i) {
                    for(int j = 0; j < SIZE; ++j) {
                        sumR += (Color.red(pixels[i][j]) * matrix.Matrix[i][j]);
                        sumG += (Color.green(pixels[i][j]) * matrix.Matrix[i][j]);
                        sumB += (Color.blue(pixels[i][j]) * matrix.Matrix[i][j]);
                    }
                }
 
                // get final Red
                R = (int)(sumR / matrix.Factor + matrix.Offset);
                if(R < 0) { R = 0; }
                else if(R > 255) { R = 255; }
 
                // get final Green
                G = (int)(sumG / matrix.Factor + matrix.Offset);
                if(G < 0) { G = 0; }
                else if(G > 255) { G = 255; }
 
                // get final Blue
                B = (int)(sumB / matrix.Factor + matrix.Offset);
                if(B < 0) { B = 0; }
                else if(B > 255) { B = 255; }
 
                // apply new pixel
                result.setPixel(x + 1, y + 1, Color.argb(A, R, G, B));
            }
        }
 
        // final image
        return result;
    }
}

 Now, In our Activity class we need to add following code:

ImageView imageView=(ImageView)findViewById(R.id.image);


Now set image on image view

image.setImageBitmap(sharpenImage(BitmapFactory.

decodeResource(getResources(),images[i]),12));

And, here we are using Convolution Matrix Theorem to make image sharper.

 public Bitmap sharpenImage(Bitmap src, double weight) {
    // set sharpness configuration
    double[][] SharpConfig = new double[][] { { 0, -2, 0 },
    { -2, weight, -2 }, { 0, -2, 0 } };
    // create convolution matrix instance
    ImageHelper convMatrix = new ImageHelper(3);
    // apply configuration
    convMatrix.applyConfig(SharpConfig);
    // set weight according to factor
    convMatrix.Factor = weight - 8;
    return ImageHelper.computeConvolution3x3(src, convMatrix);
 }


Hope this will help some one.
Enjoy Coding :)

Friday 13 December 2013

Android File or Folder listing from Sd Card | Android File explorer |Android folder listing | List file from sd card android

Hello Friends,
            This sample helps you in browsing your Sd Card folder and files. List all your music folder, file and images programmatically .



Here are the code:

1.ListFolder.Java
package com.android.sdcard.folder;

import java.io.File;
import java.sql.Date;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.text.DateFormat;

import com.example.fileexplorer.R;

import android.os.Bundle;
import android.app.ListActivity;
import android.content.Intent;
import android.view.View;
import android.widget.ListView;

public class ListFolder extends ListActivity {

 private File currentDir;
 private FileArrayAdapter adapter;

 @Override
 public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  currentDir = new File("/sdcard/");
  fill(currentDir);
 }

 private void fill(File f) {
  File[] dirs = f.listFiles();
  this.setTitle("Current Dir: " + f.getName());
  List dir = new ArrayList();
  List fls = new ArrayList();
  try {
   for (File ff : dirs) {
    String name = ff.getName();
    Date lastModDate = new Date(ff.lastModified());
    DateFormat formater = DateFormat.getDateTimeInstance();
    String date_modify = formater.format(lastModDate);
    /*
     * Note: Remove this
     * name.equalsIgnoreCase("Covenant and Augment Softsol" if u
     * want to list all ur sd card file and folder
     */
    if (ff.isDirectory()
              && name.equalsIgnoreCase("Covenant and Augment Softsol")) {

     File[] fbuf = ff.listFiles();
     int buf = 0;
     if (fbuf != null) {
      buf = fbuf.length;
     } else
      buf = 0;
     String num_item = String.valueOf(buf);
     if (buf == 0)
      num_item = num_item + " item";
     else
      num_item = num_item + " items";

     // String formated = lastModDate.toString();
     dir.add(new Albumb(ff.getName(), num_item, date_modify, ff
       .getAbsolutePath(), "directory_icon"));
    } else {
     /*
      * Note: Remove this
      * f.getName().equalsIgnoreCase("Covenant and Augment Softsol"
      * if u want to list all ur sd card file and folder
      */
     if (f.getName().equalsIgnoreCase(
       "Covenant and Augment Softsol")) {
      fls.add(new Albumb(ff.getName(), ff.length() + " Byte",
        date_modify, ff.getAbsolutePath(), "file_icon"));
     }
    }
   }
  } catch (Exception e) {

  }
  Collections.sort(dir);
  Collections.sort(fls);
  dir.addAll(fls);
  if (!f.getName().equalsIgnoreCase("sdcard"))
   dir.add(0, new Albumb("..", "Parent Directory", "", f.getParent(),
     "directory_up"));
  adapter = new FileArrayAdapter(ListFolder.this, R.layout.file_view, dir);
  this.setListAdapter(adapter);
 }

 @Override
 protected void onListItemClick(ListView l, View v, int position, long id) {
  // TODO Auto-generated method stub
  super.onListItemClick(l, v, position, id);
  Albumb o = adapter.getItem(position);
  if (o.getImage().equalsIgnoreCase("directory_icon")
    || o.getImage().equalsIgnoreCase("directory_up")) {
   currentDir = new File(o.getPath());
   fill(currentDir);
  }
 }

}



2. Albumb.java

package com.android.sdcard.folder;

 public class Albumb implements Comparable{
 private String name;
 private String data;
 private String date;
 private String path;
 private String image;
 
 public Albumb(String name,String date, String dt, String path, String image)
 {
  this.name = name;
  this.data = date;
  this.path = path; 
  this.image = image;
  
 }
 public String getName()
 {
  return name;
 }
 public String getData()
 {
  return data;
 }
 public String getDate()
 {
  return date;
 }
 public String getPath()
 {
  return path;
 }
 public String getImage() {
  return image;
 }
 
 public int compareTo(Albumb o) {
  if(this.name != null)
   return this.name.toLowerCase().compareTo(o.getName().toLowerCase()); 
  else 
   throw new IllegalArgumentException();
 }
}



3. FileArrayAdapter.java

package com.android.sdcard.folder;

import java.util.List;

import com.example.fileexplorer.R;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Drawable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Gallery;
import android.widget.ImageView;
import android.widget.TextView;

public class FileArrayAdapter extends ArrayAdapter {

 private Context c;
 private int id;
 private List items;

 public FileArrayAdapter(Context context, int textViewResourceId,
   List objects) {
  super(context, textViewResourceId, objects);
  c = context;
  id = textViewResourceId;
  items = objects;
 }

 public Albumb getItem(int i) {
  return items.get(i);
 }

 @Override
 public View getView(int position, View convertView, ViewGroup parent) {
  View v = convertView;
  if (v == null) {
   LayoutInflater vi = (LayoutInflater) c
     .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
   v = vi.inflate(id, null);
  }

  /* create a new view of my layout and inflate it in the row */
  // convertView = ( RelativeLayout ) inflater.inflate( resource, null );

  final Albumb item = items.get(position);
  if (item != null) {
   TextView t1 = (TextView) v.findViewById(R.id.TextView01);
   TextView t2 = (TextView) v.findViewById(R.id.TextView02);
   TextView t3 = (TextView) v.findViewById(R.id.TextViewDate);
   /* Take the ImageView from layout and set the city's image */
   ImageView imageCity = (ImageView) v.findViewById(R.id.fd_Icon1);

   String type = item.getImage();
   if (type.equalsIgnoreCase("directory_icon")) {
    String uri = "drawable/" + item.getImage();
    int imageResource = c.getResources().getIdentifier(uri, null,
      c.getPackageName());
    Drawable image = c.getResources().getDrawable(imageResource);
    imageCity.setImageDrawable(image);
   } else {
    Bitmap bmp = BitmapFactory.decodeFile(item.getPath());
    imageCity.setImageBitmap(bmp);
   }
   if (t1 != null)
    t1.setText(item.getName());
   if (t2 != null)
    t2.setText(item.getData());
   if (t3 != null)
    t3.setText(item.getDate());

  }
  return v;
 }

}


4. AndroidManifest,xml

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.fileexplorer"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="15" />

    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.android.sdcard.folder.ListFolder"
            android:label="@string/title_activity_fileexplorer"
            android:theme="@android:style/Theme.Holo" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
</manifest>



Download complete code here



Hope this will helps some one.
Enjoy Coidng :)

Wednesday 4 December 2013

Android Play video from SD Card | Populating a listview with videos from sdcard in android

Hello Friends,
            This is an android simple example which list all videos file store in 
device sd card and Play it in Video view .
Android provides a view control android.widget.VideoView that encapsulates
creating and initializing the MediaPlayer.










1. VideoStoredInSDCard.java

package com.example.videoplayer;

import android.app.Activity;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

public class VideoStoredInSDCard extends Activity {
 private Cursor videocursor;
 private int video_column_index;
 ListView videolist;
 int count;
 String[] thumbColumns = { MediaStore.Video.Thumbnails.DATA,
   MediaStore.Video.Thumbnails.VIDEO_ID };

 /** Called when the activity is first created. */
 @Override
 public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.main);
  init_phone_video_grid();
 }

 @SuppressWarnings("deprecation")
 private void init_phone_video_grid() {
  System.gc();
  String[] proj = { MediaStore.Video.Media._ID,
    MediaStore.Video.Media.DATA,
    MediaStore.Video.Media.DISPLAY_NAME,
    MediaStore.Video.Media.SIZE };
  videocursor = managedQuery(MediaStore.Video.Media.EXTERNAL_CONTENT_URI,
    proj, null, null, null);
  count = videocursor.getCount();
  videolist = (ListView) findViewById(R.id.PhoneVideoList);
  videolist.setAdapter(new VideoAdapter(getApplicationContext()));
  videolist.setOnItemClickListener(videogridlistener);
 }

 private OnItemClickListener videogridlistener = new OnItemClickListener() {
  public void onItemClick(AdapterView parent, View v, int position,
    long id) {
   System.gc();
   video_column_index = videocursor
     .getColumnIndexOrThrow(MediaStore.Video.Media.DATA);
   videocursor.moveToPosition(position);
   String filename = videocursor.getString(video_column_index);
   Intent intent = new Intent(VideoStoredInSDCard.this,
     ViewVideo.class);
   intent.putExtra("videofilename", filename);
   startActivity(intent);
  }
 };

 public class VideoAdapter extends BaseAdapter {
  private Context vContext;

  public VideoAdapter(Context c) {
   vContext = c;
  }

  public int getCount() {
   return count;
  }

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

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

  public View getView(int position, View convertView, ViewGroup parent) {
   System.gc();
   ViewHolder holder;
   String id = null;
   convertView = null;
   if (convertView == null) {
    convertView = LayoutInflater.from(vContext).inflate(
      R.layout.listitem, parent, false);
    holder = new ViewHolder();
    holder.txtTitle = (TextView) convertView
      .findViewById(R.id.txtTitle);
    holder.txtSize = (TextView) convertView
      .findViewById(R.id.txtSize);
    holder.thumbImage = (ImageView) convertView
      .findViewById(R.id.imgIcon);

    video_column_index = videocursor
      .getColumnIndexOrThrow(MediaStore.Video.Media.DISPLAY_NAME);
    videocursor.moveToPosition(position);
    id = videocursor.getString(video_column_index);
    video_column_index = videocursor
      .getColumnIndexOrThrow(MediaStore.Video.Media.SIZE);
    videocursor.moveToPosition(position);
    // id += " Size(KB):" +
    // videocursor.getString(video_column_index);
    holder.txtTitle.setText(id);
    holder.txtSize.setText(" Size(KB):"
      + videocursor.getString(video_column_index));

    String[] proj = { MediaStore.Video.Media._ID,
      MediaStore.Video.Media.DISPLAY_NAME,
      MediaStore.Video.Media.DATA };
    @SuppressWarnings("deprecation")
    Cursor cursor = managedQuery(
      MediaStore.Video.Media.EXTERNAL_CONTENT_URI, proj,
      MediaStore.Video.Media.DISPLAY_NAME + "=?",
      new String[] { id }, null);
    cursor.moveToFirst();
    long ids = cursor.getLong(cursor
      .getColumnIndex(MediaStore.Video.Media._ID));

    ContentResolver crThumb = getContentResolver();
    BitmapFactory.Options options = new BitmapFactory.Options();
    options.inSampleSize = 1;
    Bitmap curThumb = MediaStore.Video.Thumbnails.getThumbnail(
      crThumb, ids, MediaStore.Video.Thumbnails.MICRO_KIND,
      options);
    holder.thumbImage.setImageBitmap(curThumb);
    curThumb = null;

   } /*
    * else holder = (ViewHolder) convertView.getTag();
    */
   return convertView;
  }
 }

 static class ViewHolder {

  TextView txtTitle;
  TextView txtSize;
  ImageView thumbImage;
 }
}


2. ViewVideo.java

package com.example.videoplayer;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.MediaController;
import android.widget.VideoView;

public class ViewVideo extends Activity {
      private String filename;
      VideoView vv;
      @Override
      public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            System.gc();
            Intent i = getIntent();
            Bundle extras = i.getExtras();
            filename = extras.getString("videofilename");
            // vv = new VideoView(getApplicationContext());
            setContentView(R.layout.activity_view);
            vv = (VideoView) findViewById(R.id.videoView);
            vv.setVideoPath(filename);
            vv.setMediaController(new MediaController(this));
            vv.requestFocus();
            vv.start();
      }
}


3. AndroidManifest.xml


<?xml version="1.0" encoding="utf-8"?>

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.videoplayer"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="17" />

    <uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.example.videoplayer.VideoStoredInSDCard"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

              <category android:name="android.intent.category.LAUNCHER" />
           </intent-filter>
        </activity>
        <activity android:name=".ViewVideo" >
            <intent-filter>
                <action android:name="android.intent.action.VIEW" />
                <category android:name="android.intent.category.DEFAULT" />
            </intent-filter>
        </activity>
    </application>
</manifest>






Enjoy Coding :)

Download Source code Code

Monday 18 November 2013

Android Lazy Image loader Class Error | Image Loader not loading the image

Hello Friends,


One of my friend using Image Loader class to load an image from an url and displaying it
in a list view. She told me that the Image Loader is loading the image on an emulator, when
she run the app on a real device it's not loading any image.(Just showing the default image).

This problem occurs only when we didn't pass the permission in AndroidManifest.xml file.
When I saw her code I found following permission is missing..

 
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />


After adding this , the problem is resolved and the the app is working fine on
both emulator as well as on real device.

This issued is faced by most of the android developer , So always remember add
all permission while using lazy Image loader class.

Enjoy.... :)
Happy Coding....

Thursday 14 November 2013

Invalid android_key parameter - Facebook login | Android Facebook hash key error

Hello Droid Friends,
Today , I stuck in Facebook login Issue. I am doing facebook login in my android
application but I am getting following error:


Invalid android_key parameter. The key 26gUhN_wYCwwxenlSneyTeCY
does not match any allowed key. Configure your app key hashes at 
http://developers.facebook.com/apps/22061641443615

I followed following steps:
1. downloaded openssl from here and set it in your system environment path.
     
2. Uses following command to generate hashkey on my pc.
      keytool -exportcert -alias androiddebugkey -keystore "C:\Users\Acer\.android\debug.keystore"
                                 | openssl sha1 -binary | openssl base64
 

3. Then I created a new Facebook app  and also added the generated hashkey.

4. I got the Facebook App Id Which I am now using in my and application.


After following all above steps , still I am facing the error "Invalid android_key
parameter" . Then I go to the facebook developer site and find few new things which
comes in Facebook SDK 3.5. And Its helps me in fixing the above "Invalid android_key
parameter" Issue. There Are Two way:

Step-1. When you get this error, check the logcat it returns you a different hashkey,
so you just need to replace the previous hashkey with this one. If you did not getting
any hashkey in logcat error then step-2 helps you.

Step-2: I think this is the best way of generating hashkey bcoz it removes the dependency
of debugkeystore.No need to copy and paste the same debugkeystore on each developer
machine.Here we generate hashkey on the basis of android application package name.
Just used following code for generating the hashkey.

try  {

      PackageInfo info = getPackageManager().
           getPackageInfo(this.getPackageName(), PackageManager.GET_SIGNATURES);

      for (Signature signature : info.signatures) {

          MessageDigest md = MessageDigest.getInstance("SHA");
          md.update(signature.toByteArray());
          Log.d("====Hash Key===",Base64.encodeToString(md.digest(), 
                   Base64.DEFA  ULT));

      }

  } catch (NameNotFoundException e) {

      e.printStackTrace();

  } catch (NoSuchAlgorithmException ex) {

      ex.printStackTrace();

  }




And use this generated hashkey.This will fixed your "Invalid android_key parameter" issue.

Enjoy :)
Happy Coding... :)


Sunday 10 November 2013

Android Home key press behavior | Activity stack confused when launching app

Hello Droid Guys
I found an strange issue with the behavior of Home key press in android.Please
check below link if you want more details about this issue.


Actually, I think this is an android bug. If an app is installed via market, market 
update, or download from browser and the user launches the app directly from the
installer (ie: when the installer completes it offers the user the options to launch(open)
and done and when use select open the app now) it is launched in such a way that 
the OS gets confused.

If, after the app is launched, the user presses the HOME key to return to the home 
screen and then tries to return to the app by selecting it from the list of applications 
(or by putting a shortcut on the home screen and then selecting the shortcut), the OS
launches the root activity of the app AGAIN, bringing the existing task to the foreground
and placing ANOTHER instance of the root activity on top of the existing activity stack.

This behavior is extremely difficult to debug and has certainly caused countless hours 
of head-scratching by developers.

Note: I too found the same issue when I install an app from my mail and directly launch
the app.Go to Activity "A" then goes to Activity "B" and then I pressed "Home button".
Then ,When I open the same app pressing the app launcher on home screen,Instead of 
taking me directly to Activity "B" where I left it last time , It loads the app from the start.



It takes lots of my time to fixed this issue but finally I did that. I found the
way to resolve this problme :) .
I Added following code in the onCreate() method of my launcher activity and then Its
works fine for me.


protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash_screen);

if (!isTaskRoot()) {
           Intent intent = getIntent();
           String action = intent.getAction();
           if (intent.hasCategory(Intent.CATEGORY_LAUNCHER) && action != null &&                           action.equals(Intent.ACTION_MAIN)) {
               finish();
               return;
           }
    }
}

Hope, my above code will save some one time.
Enjoy Coding :)

 

Copyright @ 2013 Android Developers Blog.