Various file operations(create, rename, delete, list files) in Android

You can perform many file operation in Android. I described few of them here.

  • Create directory
  • Create directory and sub-directories in one instance
  • Rename directory
  • Delete directory
  • List the contain of that directory

The code for the first one, create a single directory at the root of your external storage directory.

File dirMain = new File(extdir + File.separator + "com.acomputerengineer");
if(!dirMain.exists())   {
  boolean mkdir = dirMain.mkdir();
  if(mkdir)   {
    Log.e("test", "Directory " + dirMain.getPath() + " created successfully");
  }
  else if(!mkdir) {
    Log.e("test", "Directory " + dirMain.getPath() + " not created");
  }
}

Result:

Screenshot of directory created

directory created

 

Now creating directory and sub-directories at the same time.

//example 1
File dirWithSubdir1 = new File(extdir + File.separator + "com.acomputerengineer" + File.separator + "testDir1" + File.separator + "testSubdir1");
if(!dirWithSubdir1.exists()) {
  dirWithSubdir1.mkdirs();
}

//example 2
File dirWithSubdir2 = new File(extdir + File.separator + "com.acomputerengineer" + File.separator + "testDir2" + File.separator + "testSubdir2" + File.separator + "testSubSubdir2");
if(!dirWithSubdir2.exists()) {
  dirWithSubdir2.mkdirs();
}

Result:

Screenshot of subdirectory created

subdirectory created

 

Now rename the directory ‘dirWithSubdir1’ from the above example.

File renameDir = new File(extdir + File.separator + "com.acomputerengineer" + File.separator + "newTestDir1");
dirWithSubdir1.renameTo(renameDir);

Result:

Screenshot of rename directory

rename directory

 

Now deleting the directory.

dirWithSubdir1.delete();

Result:

Screenshot of delete directory

delete directory

 

Now listing the content of the directory by logging them into logcat.

String[] dirMainFiles = dirMain.list();
for (int i = 0; i < dirMainFiles.length; i++)   {
  Log.e("test", "file " + i + " :" + dirMainFiles[i]);
}

Result:

Screenshot of list content of directory

list content of directory

 

Screen Shot of list content of directory

list content of directory

Convert pixel to dp or dip and dp to pixel in Android

If we need to set dimension of any view from the java file, it will use pixel as default unit. Where as in XML file we use dp or dip(density independent pixel). So 100 dp is not equal to 100 pixel.

Screenshot_20160623-151106

200dp = 525pixel in this case

Android uses density factor to provide support to different devices with different screensize. So the conversion works as explained below.

First we will check the conversion of dp to pixel. Here dp is density independent and pixel is dependent on density. So if we need to find pixel from give dp, we need to multiply it with the density of the device.

So the equation will be like this

pixel = dp * (density of the device);

Here is the function to convert dp to pixel.

public static float dpTopixel(Context c, float dp) {
  float density = c.getResources().getDisplayMetrics().density;
  float pixel = dp * density;
  return pixel;
}

Now we will convert pixel to dp. Here we need to divide the pixel with the density of the device so the result will become independent of density(dp).

So the equation will be like this

dp = pixel / (density of the device);

Here is the function to convert pixel to dp.

public static float pixelTodp(Context c, float pixel) {
  float density = c.getResources().getDisplayMetrics().density;
  float dp = pixel / density;
  return dp;
}

Now if you want to use this value as width or height in any of your view’s LayoutParams, it will ask you for Integer(int) value and above functions will return you Float(float) value. So you have to do following thing to convert it to Integer(int).

int width = (int) dpTopixel(MainActivity.this, 200);

Please comment if you find any mistake or want to give feedback.

Rotate image(bitmap) to any angle in Android

In many image related Android applications, we may need to rotate the bitmap(not ImageView). Here I added the code below to rotate the image at any possible angle using Matrix.

Screenshot_20160619-211636

rotation of image resulted from below code

Bitmap bInput/*your input bitmap*/, bOutput;
float degrees = 45;//rotation degree
Matrix matrix = new Matrix();
matrix.setRotate(degrees);
bOutput = Bitmap.createBitmap(bInput, 0, 0, bInput.getWidth(), bInput.getHeight(), matrix, true);

Flip image(bitmap) horizontally and vertically in Android

In any photo related Android application, flipping image is necessary feature. So here I wrote the code to flip the image in both horizontal as well as vertical direction.

Screenshot_20160619-211419

Result of the below code

Code for vertical flip bitmap:

Bitmap bInput/*your input bitmap*/, bOutput;
Matrix matrix = new Matrix();
matrix.preScale(1.0f, -1.0f);
bOutput = Bitmap.createBitmap(bInput, 0, 0, bInput.getWidth(), bInput.getHeight(), matrix, true);

Code for horizontal flip bitmap:

Bitmap bInput/*your input bitmap*/, bOutput;
Matrix matrix = new Matrix();
matrix.preScale(-1.0f, 1.0f);
bOutput = Bitmap.createBitmap(bInput, 0, 0, bInput.getWidth(), bInput.getHeight(), matrix, true);

Various material designs for Button in Android

It is very important to update/create your app with material design. It will boost up your app downloads compare to older design.

Using AppCompat library you can design Button in your app in many ways. Here is demonstrate you 6 different kind of buttons with example code so you can directly integrate them in your code.

Screenshot_2016-04-28-23-52-27

1. Simple Button

<Button
  android:layout_width="match_parent"
  android:layout_height="wrap_content"
  android:text="Simple Button" />

2. Coloured Button

<Button
  style="@style/Widget.AppCompat.Button.Colored"
  android:layout_width="match_parent"
  android:layout_height="wrap_content"
  android:layout_marginTop="10dp"
  android:text="Colored Button" />

3. Borderless Button

<Button
  style="@style/Widget.AppCompat.Button.Borderless"
  android:layout_width="match_parent"
  android:layout_height="wrap_content"
  android:layout_marginTop="10dp"
  android:text="Borderless Button" />

4. Borderless Coloured Button

<Button
  style="@style/Widget.AppCompat.Button.Borderless.Colored"
  android:layout_width="match_parent"
  android:layout_height="wrap_content"
  android:layout_marginTop="10dp"
  android:text="Borderless Colored Button" />

5. Simple Button Without Shadow

<Button
  android:layout_width="match_parent"
  android:layout_height="wrap_content"
  android:stateListAnimator="@null"
  android:layout_marginTop="10dp"
  android:text="Simple Button Without Shadow" />

6. Coloured Button Without Shadow

<Button
  style="@style/Widget.AppCompat.Button.Colored"
  android:layout_width="match_parent"
  android:layout_height="wrap_content"
  android:stateListAnimator="@null"
  android:layout_marginTop="10dp"
  android:text="Colored Button Without Shadow" />

Download Source Code: https://github.com/dakshbhatt21/a-computer-engineer

Upload image from Android app to server using PHP without any library

Image uploading is necessary in any Android app now a days.
We can upload image to our server from the Android app. Here I used PHP at the server side to catch and save the image file.

Here we did it without using any kind of external library. So you can directly use it in your project without any hassle.

First we pick the image from the gallery. You can checkout my article, “Pick image from gallery before and after KITKAT version in Android” and get the path of the image file in the “path” variable.

Then use following code snippet to upload that image to the server.

String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
try {
  connectURL = new URL("http://example.com/imageupload.php");
  HttpURLConnection conn = (HttpURLConnection) connectURL.openConnection();
  conn.setDoInput(true);
  conn.setDoOutput(true);
  conn.setUseCaches(false);
  conn.setRequestMethod("POST");
  conn.setRequestProperty("Connection", "Keep-Alive");
  conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);

  DataOutputStream dos = new DataOutputStream(conn.getOutputStream());
  dos.writeBytes(twoHyphens + boundary + lineEnd);

  HashMap<String, String> params = new HashMap<>();
  params.put("key", "value");	//post params that you want yo send
  StringBuilder result = new StringBuilder();
  for (Map.Entry<String, String> entry : params.entrySet()) {
    result.append("Content-Disposition: form-data; name=\"" + entry.getKey() + "\"" + lineEnd);
    result.append(lineEnd);
    result.append(entry.getValue());
    result.append(lineEnd);
    result.append(twoHyphens + boundary + lineEnd);
  }

  dos.writeBytes(result.toString());
  if (!String.valueOf("").equals(path)) {
    dos.writeBytes("Content-Disposition: form-data; name=\"" + "picture" + "\";filename=\"" + "picture.jpg" + "\"" + lineEnd);
    dos.writeBytes(lineEnd);
    fis = new FileInputStream(path);
    int bytesAvailable = fis.available();

    int maxBufferSize = 8192;
    int bufferSize = Math.min(bytesAvailable, maxBufferSize);
    byte[] buffer = new byte[bufferSize];

    int bytesRead = fis.read(buffer, 0, bufferSize);

    while (bytesRead > 0) {
      dos.write(buffer, 0, bufferSize);
      bytesAvailable = fis.available();
      bufferSize = Math.min(bytesAvailable, maxBufferSize);
      bytesRead = fis.read(buffer, 0, bufferSize);
    }
    dos.writeBytes(lineEnd);
    dos.writeBytes(twoHyphens + boundary + lineEnd);
    fis.close();
  }
  dos.flush();

  InputStream is = conn.getInputStream();

  int ch;

  StringBuffer b = new StringBuffer();
  while ((ch = is.read()) != -1) {
    b.append((char) ch);
  }
  json = b.toString();
  dos.close();
} catch (MalformedURLException ex) {
} catch (IOException ioe) {
}

Make sure that you call this code snippet inside of AsyncTask or Thread. Once you get the response from the server, your image has been uploaded to the server.

Now here is the code for PHP to move the uploaded to the same directory as php file.

    move_uploaded_file($_FILES['picture']['tmp_name'], $_FILES['picture']['name']);

And done! You can find your uploaded image in “images” directory on your server.

Add “Like Us on Facebook” button to your Android App

It’s really a good idea to include the link to your Facebook page in the Android app. It will help you to keep in touch with the users of your app.

Below is the code you should put in the click event of the “Like Us on Facebook” button.

String fbPageId = "149483785425721";
String fbPageUrl = "https://www.facebook.com/bmicalculatorapp";

try {
  getPackageManager().getPackageInfo("com.facebook.katana", 0);
  Intent fb = new Intent(Intent.ACTION_VIEW, Uri.parse("fb://page/" + fbPageId));
  startActivity(fb);
} catch (Exception e) {
  Intent fb = new Intent(Intent.ACTION_VIEW,  Uri.parse(fbPageUrl));
  startActivity(fb);
}

You just need to replace the fbPageId and fbPageUrl in above code. You can find the page id of your Facebook page in Your Page -> Settings -> Page Info section.