Pages

Thursday, 1 October 2015

Android date and time formate

Following is example of date and time formate from timeMillis.

Date date = new Date(time millis here);
SimpleDateFormat formatter = new SimpleDateFormat("hh:mm a");
String receivedTime = formatter.format(date); // hh:mm a format
// it may return like 06:55 PM

SimpleDateFormat dateformatter = new SimpleDateFormat("dd-MM-yyyy");
String receivedDate = dateformatter .format(date);
// it may return like 22-09-2015 


Following link have more format char.
http://developer.android.com/reference/java/text/SimpleDateFormat.html

How do I make links in a TextView clickable?

I'm using only android:autoLink="web" and it works fine. A click on the link opens the browser and shows the correct page.

How to Copy Text to Clip Board in Android?

Use this class to copy text to clipboard

package com.dedoc.app.utils;

import android.annotation.SuppressLint;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.res.AssetFileDescriptor;
import android.net.Uri;
import android.util.Log;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;

/**
 * Created by hb on 01-Oct-15.
 */
public class MyClipboardManager {

 @SuppressLint("NewApi")
 @SuppressWarnings("deprecation")
 public static boolean copyToClipboard(Context context, String text) {
  try {
   int sdk = android.os.Build.VERSION.SDK_INT;
   if (sdk < android.os.Build.VERSION_CODES.HONEYCOMB) {
    android.text.ClipboardManager clipboard = (android.text.ClipboardManager) context
      .getSystemService(context.CLIPBOARD_SERVICE);
    clipboard.setText(text);
   } else {
    android.content.ClipboardManager clipboard = (android.content.ClipboardManager) context
      .getSystemService(context.CLIPBOARD_SERVICE);
    android.content.ClipData clip = android.content.ClipData
      .newPlainText("", text);
    clipboard.setPrimaryClip(clip);
   }
   return true;
  } catch (Exception e) {
   return false;
  }
 }

 @SuppressLint("NewApi")
 public static  String readFromClipboard(Context context) {
  int sdk = android.os.Build.VERSION.SDK_INT;
  if (sdk < android.os.Build.VERSION_CODES.HONEYCOMB) {
   android.text.ClipboardManager clipboard = (android.text.ClipboardManager) context
     .getSystemService(context.CLIPBOARD_SERVICE);
   return clipboard.getText().toString();
  } else {
   ClipboardManager clipboard = (ClipboardManager) context
     .getSystemService(Context.CLIPBOARD_SERVICE);

   // Gets a content resolver instance
   ContentResolver cr = context.getContentResolver();

   // Gets the clipboard data from the clipboard
   ClipData clip = clipboard.getPrimaryClip();
   if (clip != null) {

    String text = null;
    String title = null;

    // Gets the first item from the clipboard data
    ClipData.Item item = clip.getItemAt(0);

    // Tries to get the item's contents as a URI pointing to a note
    Uri uri = item.getUri();

    // If the contents of the clipboard wasn't a reference to a
    // note, then
    // this converts whatever it is to text.
    if (text == null) {
     text = coerceToText(context, item).toString();
    }

    return text;
   }
  }
  return "";
 }

 @SuppressLint("NewApi")
 public static CharSequence coerceToText(Context context, ClipData.Item item) {
  // If this Item has an explicit textual value, simply return that.
  CharSequence text = item.getText();
  if (text != null) {
   return text;
  }

  // If this Item has a URI value, try using that.
  Uri uri = item.getUri();
  if (uri != null) {

   // First see if the URI can be opened as a plain text stream
   // (of any sub-type). If so, this is the best textual
   // representation for it.
   FileInputStream stream = null;
   try {
    // Ask for a stream of the desired type.
    AssetFileDescriptor descr = context.getContentResolver()
      .openTypedAssetFileDescriptor(uri, "text/*", null);
    stream = descr.createInputStream();
    InputStreamReader reader = new InputStreamReader(stream,
      "UTF-8");

    // Got it... copy the stream into a local string and return it.
    StringBuilder builder = new StringBuilder(128);
    char[] buffer = new char[8192];
    int len;
    while ((len = reader.read(buffer)) > 0) {
     builder.append(buffer, 0, len);
    }
    return builder.toString();

   } catch (FileNotFoundException e) {
    // Unable to open content URI as text... not really an
    // error, just something to ignore.

   } catch (IOException e) {
    // Something bad has happened.
    Log.w("ClippedData", "Failure loading text", e);
    return e.toString();

   } finally {
    if (stream != null) {
     try {
      stream.close();
     } catch (IOException e) {
     }
    }
   }

   // If we couldn't open the URI as a stream, then the URI itself
   // probably serves fairly well as a textual representation.
   return uri.toString();
  }

  // Finally, if all we have is an Intent, then we can just turn that
  // into text. Not the most user-friendly thing, but it's something.
  Intent intent = item.getIntent();
  if (intent != null) {
   return intent.toUri(Intent.URI_INTENT_SCHEME);
  }

  // Shouldn't get here, but just in case...
  return "";
 }

}

Saturday, 8 August 2015

android multiple listView or multiple expandable listView in one screen

To make whole screen scrollable when screen having more then one listview or more then one ExpandableListView.

First we need to measure height of whole list and apply same height to that list. we need to calculate height for all list separately.

Following code will use to calculate height of Expandable list

public static boolean setListViewHeightBasedOnItems(ExpandableListView listView) {

  ExpandableJunkListAdapter listAdapter = (ExpandableJunkListAdapter) listView.getExpandableListAdapter();
  if (listAdapter != null) {
   int desiredWidth = View.MeasureSpec.makeMeasureSpec(listView.getWidth(), View.MeasureSpec.EXACTLY);
   int numberOfItems = listAdapter.getGroupCount();

   // Get total height of all items.
   int totalItemsHeight = 0;
   for (int itemPos = 0; itemPos < numberOfItems; itemPos++) {
    View item = listAdapter.getGroupView(itemPos, listView.isGroupExpanded(itemPos), null, listView);
    View childItem = null;
    int noOfChilds = listAdapter.getRealChildrenCount(itemPos);
    int childPos = 0;
    if (listView.isGroupExpanded(itemPos)) {

     for (childPos = 0; childPos < noOfChilds; childPos++) {
      if (childPos == (noOfChilds - 1)) {
       childItem = listAdapter.getRealChildView(itemPos, childPos, true, null, listView);
      } else {
       childItem = listAdapter.getRealChildView(itemPos, childPos, false, null, listView);
      }
      childItem.measure(desiredWidth, View.MeasureSpec.UNSPECIFIED);
      totalItemsHeight += childItem.getMeasuredHeight();
     }
    }
    item.measure(desiredWidth, View.MeasureSpec.UNSPECIFIED);
    totalItemsHeight += item.getMeasuredHeight();
   }

   // Get total height of all item dividers.
   int totalDividersHeight = listView.getDividerHeight() * (numberOfItems - 1);

   // Set list height.
   ViewGroup.LayoutParams params = listView.getLayoutParams();
   params.height = totalItemsHeight + totalDividersHeight;
   // Log.i("height", "" + params.height);
   Log.e("height", "" + params.height);
   listView.setLayoutParams(params);
   listView.requestLayout();

   return true;

  } else {
   return false;
  }
 }

you need to call this function at the time of "setAdapter","notifydatasetChanged", "ongroupClick" for expandableListView.  
Whenever any view related operation performed then we need to call this function to calculate actual height of list.

For ListView We may use following function. call it at time of Notifydatasetchaged, setAdapter etc

public static void getTotalHeightofListView(ListView listView) {

    ListAdapter mAdapter = listView.getAdapter();

    int totalHeight = 0;

    for (int i = 0; i < mAdapter.getCount(); i++) {
        View mView = mAdapter.getView(i, null, listView);

        mView.measure(
                MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED),

                MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));

        totalHeight += mView.getMeasuredHeight();
        Log.w("HEIGHT" + i, String.valueOf(totalHeight));

    }

    ViewGroup.LayoutParams params = listView.getLayoutParams();
    params.height = totalHeight
            + (listView.getDividerHeight() * (mAdapter.getCount() - 1));
    listView.setLayoutParams(params);
    listView.requestLayout();

}

Tuesday, 4 August 2015

android: how to hide folder from appearing in the Gallery

Put a file named .nomedia in the folder. This can be a zero-byte file if you want -- the name is what matters.