Thursday 20 March 2014

Creating and Storing Log File on device in Android


Hello Friends,
        Today, I am sharing another android tutorial which helps you in Creating
and Storing Log File in your android phone.


1. MainActivity.java
package com.example.logfileimplementation;

import java.io.File;

import android.os.Bundle;
import android.os.Environment;
import android.app.Activity;
import android.util.Log;
import android.view.Menu;
import android.widget.TextView;

public class MainActivity extends Activity {
 
 public static final String SDCARD = String.valueOf(Environment
   .getExternalStorageDirectory());
 TextView mTextView;
 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  try {
  deleteLog();
  setContentView(R.layout.activity_main);
  createAppDirectories();
  mTextView = (TextView) findViewById(R.id.action_settings);
  mTextView.setText("Android crash Reporter");
  } catch(Exception ex) {
   Utilities.writeIntoLog(Log.getStackTraceString(ex));
  }
 }

 @Override
 public boolean onCreateOptionsMenu(Menu menu) {
  // Inflate the menu; this adds items to the action bar if it is present.
  getMenuInflater().inflate(R.menu.main, menu);
  return true;
 }

 // Creating App Directory For Log File
 private void createAppDirectories() {
  System.out.println("hiii");
  File dir1 = new File(Utilities.APP_DIR);
  if (!dir1.exists()) {
   dir1.mkdir();
  }
 }

 // Deleting App Directory which is used for Log File
 private void deleteLog() {

  File log = new File(Utilities.LOG_FILE_PATH);
  if (log.exists()) {
   log.delete();
  }
 }
}

2. Utilities.java
package com.example.logfileimplementation;

import java.io.BufferedWriter;
import java.io.FileWriter;


public class Utilities {
 public static String APP_DIR = MainActivity.SDCARD+"/Logfile";
 public static String LOG_FILE_PATH = APP_DIR+"/ myapp_log.txt";  
 
 
 
 public static void writeIntoLog(String data) 
 {
   
  FileWriter fw = null;    
  try {
   
   fw = new FileWriter(LOG_FILE_PATH , true);
   BufferedWriter buffer = new BufferedWriter(fw);   
   buffer.append(data+"\n");
    
   buffer.close();

  } catch (Exception e) { 
   e.printStackTrace();
  }
   
 }  
}

3. activity_main.xml


<RelativeLayout 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:paddingBottom="@dimen/activity_vertical_margin"

    android:paddingLeft="@dimen/activity_horizontal_margin"

    android:paddingRight="@dimen/activity_horizontal_margin"

    android:paddingTop="@dimen/activity_vertical_margin"

    tools:context=".MainActivity" >



    <TextView

        android:id="@+id/textView"

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:text="@string/hello_world" />

  

</RelativeLayout>
4. AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.logfileimplementation"
    android:versionCode="1"
    android:versionName="1.0" >

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

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

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

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

</manifest>
Hope this will help you.
Enjoy Coding. Cheers.... :)

Tuesday 18 March 2014

"Collect preferences failed" eclipse ADT error | You may have an "No repository found error"


Hello Droid Guys,
                           After updating the sdk manager to latest sdk i.e version 22.6.
           


I am start getting following error: 
[2014-03-18 13:12:03 - Framework Resource Parser] Collect preferences failed, class java/lang/AutoCloseable not found in D:\Android-Eclipse\Eclipse and ADT\android-sdk\platforms\android-19\android.jar

Then I found the solution by updating the Eclipse ADT plugin.
1. go Help | Install New Sofware
2. select "Android Developer Tools Update Site - http://dl-ssl.google.com/android/eclipse/"
3. press "Select All"
4. press "Finish"

Note : While doing above steps I faced other issue i.e:
    You may have an "No repository found error" while installing the tools.

Then I do following tweak I removed the http://dl-ssl.google.com/android/eclipse/ site and then re-added it, then everything downloaded fine.

Hope, this will helps some one.
Enjoy Coding :)


Thursday 13 March 2014

Android Robotium Test -run robotium tests in a specific order

Hello Friends,
                         This is very common scenario when you are running any testsuits. It
by default runs in alphabetical order. I too faces the same problem while writing the
test case using Robotium.

In my case I want to execute the testcase in following order :
MainLoginScreenTest -> EmailSignUpScreenTest -> EmailLoginScreenTest

But it actually runs in alphabetical order like,
 EmailLoginScreenTest -> EmailSignUpScreenTest - > MainLoginScreenTest

Then I follow this link and find the way to come out from this problem. Here is
my code.

1. AllTests.java
package com.android.test;
import junit.framework.TestSuite;
import android.app.Activity;
import android.test.ActivityInstrumentationTestCase2;

public class AllTests extends 
        ActivityInstrumentationTestCase2<Activity>{
 
 public AllTests(Class activityClass) {
  super(activityClass);
 }

 public static TestSuite suite() {
  TestSuite t = new TestSuite();
  t.addTestSuite(MainLoginScreenTest.class);
  t.addTestSuite(EmailSignUpScreenTest.class);
  t.addTestSuite(EmailLoginScreenTest.class);
  
  return t; 
 }
 
 @Override
 public void setUp() throws Exception {
  
 }
 
 
 @Override
 public void tearDown() throws Exception {
 }

}


2.MainLoginScreenTest.java

package com.android.test;

import android.app.Activity;
import android.test.ActivityInstrumentationTestCase2;
import android.widget.ImageButton;

import com.android.Login.EmailSignUpScreen;
import com.android.Login.MainLoginScreen;
import com.android.android.R;
import com.robotium.solo.Solo;

public class MainLoginScreenTest extends
          ActivityInstrumentationTestCase2<MainLoginScreen> {
 
 private Solo solo;
 private Activity activity;
 
 public MainLoginScreenTest() {
  super(MainLoginScreen.class);
  // TODO Auto-generated constructor stub
 }
 
 @Override
 public void setUp() throws Exception {
  //setUp() is run before a test case is started. 
  //This is where the solo object is created.
  this.activity = this.getActivity();
  this.solo = new Solo(getInstrumentation(), this.activity);
 }
 
 
 @Override
 public void tearDown() throws Exception {
       solo.finishOpenedActivities();
 }

 public void testDisplay() throws Exception {
   solo.waitForActivity(MainLoginScreen.class);
   ImageButton emailLogin = (ImageButton) this.solo.getView(R.id.btn_email_login);
   assertEquals(emailLogin.getId(), R.id.btn_email_login);
   this.solo.clickOnImageButton(1);
   this.solo.waitForActivity(EmailSignUpScreen.class, 1000);
   assertEquals(EmailSignUpScreen.class, solo.getCurrentActivity().getClass());
   //this.solo.goBack();
 }
}


3.EmailSignUpScreenTest.java

package com.android.test;

import junit.framework.Test;
import junit.framework.TestSuite;
import android.app.Activity;
import android.test.ActivityInstrumentationTestCase2;
import android.test.suitebuilder.annotation.MediumTest;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.TextView;

import com.android.Login.EmailLoginScreen;
import com.android.Login.EmailSignUpScreen;
import com.android.android.R;
import com.robotium.solo.Solo;

public class EmailSignUpScreenTest extends 
           ActivityInstrumentationTestCase2<EmailSignupScreen>{

 private Solo solo;
 private Activity activity;
 
 public EmailSignUpScreenTest() {
  super(EmailSignUpScreen.class);
 }
 public EmailSignUpScreenTest(String name) {
  super(EmailSignUpScreen.class);
  setName(name);
 }
 
 public static final Test suite(  ) {
   TestSuite suite = new TestSuite();
   suite.addTest(new TestSuite(EmailSignUpScreen.class));
   suite.addTest(new TestSuite(EmailLoginScreen.class));
   return suite;
   }

 @Override
 public void setUp() throws Exception {
  //setUp() is run before a test case is started. 
  //This is where the solo object is created.
  this.activity = this.getActivity();
  this.solo = new Solo(getInstrumentation(), this.activity);
 }
 
 @Override
 public void tearDown() throws Exception {
       solo.finishOpenedActivities();
 }

 public void testDisplay() throws Exception {
  String fName = "Sam";
  String lName = "Joshi";
  String email = "sam@gmail.com";
  String password = "abc123";
  String dob = "03-11-2014";
  String zipcod = "201301";
    
  this.solo.typeText((EditText) this.activity.findViewById(R.id.edt_first_name), fName);
  //this.solo.enterText((EditText) this.activity.findViewById(R.id.edt_last_name), lName);
  this.solo.typeText((EditText) this.activity.findViewById(R.id.edt_email), email);
  this.solo.typeText((EditText) this.activity.findViewById(R.id.edt_password), password);
  this.solo.typeText((EditText) this.activity.findViewById(R.id.edt_confirm_password), password);
  this.solo.enterText((EditText) this.activity.findViewById(R.id.edt_birth_date), dob);
  RadioButton rb = (RadioButton) solo.getView(R.id.rb_female);
  solo.clickOnView(rb);
  this.solo.typeText((EditText) this.activity.findViewById(R.id.edt_zip_code), zipcod);
  //Click on the button named "Sign up".
  this.solo.clickOnButton("Sign Up");
  //this.solo.w
  //Check to see if the given text is displayed.
  //assertTrue(this.solo.searchText(text));
 }
 
 @MediumTest
 public void testStartEmailLoginScreen() throws Exception {     
   this.solo.waitForActivity(EmailSignUpScreen.class); 
   TextView tvSignIn = (TextView) this.activity.findViewById(R.id.sign_in_label);
   String text = tvSignIn.getText().toString();
   this.solo.waitForText(text);
   this.solo.clickOnText(text);
   this.solo.waitForActivity(EmailLoginScreen.class, 1000);
   assertTrue(solo.waitForActivity(EmailLoginScreen.class));
 }
}

4.EmailLoginScreenTest.java
package com.android.test;

import android.app.Activity;
import android.test.ActivityInstrumentationTestCase2;
import android.widget.EditText;

import com.android.Login.EmailLoginScreen;
import com.android.android.R;
import com.robotium.solo.Solo;

public class EmailLoginScreenTest extends
        ActivityInstrumentationTestCase2<EmailLoginScreen>{

 private Solo solo;
 private Activity activity;
 
 public EmailLoginScreenTest() {
  super(EmailLoginScreen.class);
 }

 @Override
 public void setUp() throws Exception {
  //setUp() is run before a test case is started. 
  //This is where the solo object is created.
  this.activity = this.getActivity();
  this.solo = new Solo(getInstrumentation(), this.activity);
 }
 
 
 @Override
 public void tearDown() throws Exception {
       solo.finishOpenedActivities();
 }

 public void testDisplay() throws Exception {
  String email = "mukesh@gmail.com";
  String password = "abc123";
  
  
  this.solo.typeText((EditText) this.activity.findViewById(R.id.edt_login_email), email);
  //this.solo.enterText((EditText) this.activity.findViewById(R.id.edt_login_password), password);
  //Click on the button named "Sign up".
  this.solo.clickOnButton("Login");
  this.solo.waitForActivity(EmailLoginScreen.class, 2000);
  //Check to see if the given text is displayed.
  //assertTrue(this.solo.searchText(text));
 }
}


Note: Right click on AllTests.java and choose Run As-> Android Junit test ->
               select AllTests>java file.

Hope this post is helpful for some one.
Enjoy Coding......  :)

Friday 7 March 2014

java.lang.RuntimeException: Stub! in Robolectric


Hello Droid Friends,
                              Have you facing following error while running a test case using
Roboelectric and Junit-4.

java.lang.RuntimeException: Stub!
at android.content.Context.<init>(Context.java:4)
at android.content.ContextWrapper.<init>(ContextWrapper.java:5)
at android.view.ContextThemeWrapper.<init>(ContextThemeWrapper.java:5)
at android.app.Activity.<init>(Activity.java:6)
at com.actionbarsherlock.app.SherlockActivity.<init>(SherlockActivity.java:21)
at com.opttown.OptTown.DrawerBaseActivity.<init>(DrawerBaseActivity.java:34)
at com.opttown.Places.MyPlaces.<init>(MyPlaces.java:63)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:525)
at org.fest.reflect.constructor.Invoker.newInstance(Invoker.java:77)
at org.robolectric.util.ActivityController.<init>(ActivityController.java:47)
at org.robolectric.Robolectric.buildActivity(Robolectric.java:1409)
at com.opttown.test.MyPlacesTest.setUp(MyPlacesTest.java:25)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:601)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:45)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:42)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:27)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:263)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:68)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:47)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:231)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:60)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:229)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:50)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:222)
at org.junit.runners.ParentRunner.run(ParentRunner.java:300)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)


Most of stub!  exceptions are because the tests are not annotated with the correct TestRunner. For example in my case I forgot to add:
@RunWith(RobolectricTestRunner.class)

After adding the above annotation the above issue will be fixed.


import static org.junit.Assert.assertNotNull;
import static org.robolectric.Robolectric.shadowOf;

import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.Robolectric;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.annotation.Config;
import org.robolectric.shadows.ShadowActivity;

import android.content.Context;

import com.android.Places.MyPlaces;

@RunWith(RobolectricTestRunner.class)
public class MyPlacesTest {
 
 private MyPlaces activity;
 Context ctx;
 ShadowActivity shadowActivity;
 
 @Before
 public void setUp() throws Exception {
  activity = Robolectric.buildActivity(MyPlaces.class)
                .create()
                .get();
  shadowActivity = shadowOf(activity);
  ctx = activity;
 }
 
 /**
   * @testdox: for activity instance test 
   * given: 
   * when:  app launch
   * then: checking the instance of activity
   */
  @Test
  @Config(reportSdk = 10)
  public void testActivityInstance() {
   assertNotNull(shadowActivity.getApplicationContext());
   Assert.assertEquals("Result",activity.getApplicationContext(),sh                       adowActivity.getApplicationContext());
  }



Hope this will help you during writing the test case for your android project.



Enjoy Coding... :) 

You may also Read this:
1. Roboelectric setup with eclipse
2. R
oboelectric AndroidManifest.xml not found error
3. Roboelectric tutorial
4. Asserting Toast message using Robolectric
.

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 :)

 

Copyright @ 2013 Android Developers Blog.