How to calculate time difference in Android?




public static String getDateDifference(Date thenDate){
        Calendar now = Calendar.getInstance();
        Calendar then = Calendar.getInstance();
        now.setTime(new Date());
        then.setTime(thenDate);

       
        // Get the represented date in milliseconds
        long nowMs = now.getTimeInMillis();
        long thenMs = then.getTimeInMillis();
       
        // Calculate difference in milliseconds
        long diff = nowMs - thenMs;
       
        // Calculate difference in seconds
        long diffMinutes = diff / (60 * 1000);
        long diffHours = diff / (60 * 60 * 1000);
        long diffDays = diff / (24 * 60 * 60 * 1000);

        if (diffMinutes<60){
            if (diffMinutes==1)
                return diffMinutes + " minute ago";
            else
                return diffMinutes + " minutes ago";
        } else if (diffHours<24){
            if (diffHours==1)
                return diffHours + " hour ago";
            else
                return diffHours + " hours ago";
        }else if (diffDays<30){
            if (diffDays==1)
                return diffDays + " day ago";
            else
                return diffDays + " days ago";
        }else {
            return "a long time ago..";
        }
    }
}


    

Android Bitmap Scaling--Dynamically




Android Bitmap Scaling


call it in main class

BitmapScaler scaler = new BitmapScaler(getResources(), R.drawable.moorwen, newWidth);
imageView.setImageBitmap(scaler.getScaled())



//----------------------------------------



class BitmapScaler {
private static class Size {
int sample;
float scale;
}

private Bitmap scaled;

BitmapScaler(Resources resources, int resId, int newWidth)
throws IOException {
Size size = getRoughSize(resources, resId, newWidth);
roughScaleImage(resources, resId, size);
scaleImage(newWidth);
}

BitmapScaler(File file, int newWidth) throws IOException {
InputStream is = null;
try {
is = new FileInputStream(file);
Size size = getRoughSize(is, newWidth);
try {
is = new FileInputStream(file);
roughScaleImage(is, size);
scaleImage(newWidth);
} finally {
is.close();
}
} finally {
is.close();
}
}

BitmapScaler(AssetManager manager, String assetName, int newWidth)
throws IOException {
InputStream is = null;
try {
is = manager.open(assetName);
Size size = getRoughSize(is, newWidth);
try {
is = manager.open(assetName);
roughScaleImage(is, size);
scaleImage(newWidth);
} finally {
is.close();
}
} finally {
is.close();
}
}

Bitmap getScaled() {
return scaled;
}

private void scaleImage(int newWidth) {
int width = scaled.getWidth();
int height = scaled.getHeight();

float scaleWidth = ((float) newWidth) / width;
float ratio = ((float) scaled.getWidth()) / newWidth;
int newHeight = (int) (height / ratio);
float scaleHeight = ((float) newHeight) / height;

Matrix matrix = new Matrix();
matrix.postScale(scaleWidth, scaleHeight);

scaled = Bitmap.createBitmap(scaled, 0, 0, width, height, matrix, true);
}

private void roughScaleImage(InputStream is, Size size) {
Matrix matrix = new Matrix();
matrix.postScale(size.scale, size.scale);

BitmapFactory.Options scaledOpts = new BitmapFactory.Options();
scaledOpts.inSampleSize = size.sample;
scaled = BitmapFactory.decodeStream(is, null, scaledOpts);
}

private void roughScaleImage(Resources resources, int resId, Size size) {
Matrix matrix = new Matrix();
matrix.postScale(size.scale, size.scale);

BitmapFactory.Options scaledOpts = new BitmapFactory.Options();
scaledOpts.inSampleSize = size.sample;
scaled = BitmapFactory.decodeResource(resources, resId, scaledOpts);
}

private Size getRoughSize(InputStream is, int newWidth) {
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeStream(is, null, o);

Size size = getRoughSize(o.outWidth, o.outHeight, newWidth);
return size;
}

private Size getRoughSize(Resources resources, int resId, int newWidth) {
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeResource(resources, resId, o);

Size size = getRoughSize(o.outWidth, o.outHeight, newWidth);
return size;
}

private Size getRoughSize(int outWidth, int outHeight, int newWidth) {
Size size = new Size();
size.scale = outWidth / newWidth;
size.sample = 1;

int width = outWidth;
int height = outHeight;

int newHeight = (int) (outHeight / size.scale);

while (true) {
if (width / 2 < newWidth || height / 2 < newHeight) {
break;
}
width /= 2;
height /= 2;
size.sample *= 2;
}
return size;
}
}

ExpandableList in Android For drop down Contact us Form


Drop down Contact us Form in Android



We use expandable list for this....

ContactUs Adapter class
public class ContactUsAdapter extends BaseExpandableListAdapter {
 private LayoutInflater inflater;

 public Context ctxt;
 Typeface myTypeface;

 static class ChildHolder {
  private EditText etName, etEmail, etMessage;
  private Button btnSubmit;
 }

 static class GroupHolder {
  private TextView txtGroupName;
 }

 public ContactUsAdapter(Context context) {

  this.ctxt = context;

  myTypeface = Typeface.createFromAsset(ctxt.getAssets(),
    "fonts/BRADHITC_0.ttf");
  inflater = (LayoutInflater) ctxt
    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
 }

 @Override
 public View getChildView(int groupPosition, int childPosition,
   boolean isLastChild, View convertView, ViewGroup parent) {

  final ChildHolder holder;

  if (convertView == null) {
   convertView = inflater.inflate(R.layout.contactus, null);
   holder = new ChildHolder();

   holder.etName = (EditText) convertView.findViewById(R.id.etName);
   holder.etEmail = (EditText) convertView.findViewById(R.id.etEmail);
   holder.etMessage = (EditText) convertView
     .findViewById(R.id.etMessage);
   holder.btnSubmit = (Button) convertView
     .findViewById(R.id.btnMailSubmit);
   // holder.txtChildName.setTypeface(myTypeface);
   convertView.setTag(holder);

  } else {
   holder = (ChildHolder) convertView.getTag();
  }
  holder.btnSubmit.setOnClickListener(new OnClickListener() {

   @Override
   public void onClick(View v) {
    
   
  AlertDialog.Builder alertLogout = new AlertDialog.Builder(ctxt);
  alertLogout.setTitle(R.string.app_name);
  alertLogout.setMessage("Mail Successfully Sent!..");
  alertLogout.setPositiveButton("Ok",new DialogInterface.OnClickListener() {
   @Override
   public void onClick(DialogInterface dialog,int which) {
   
   dialog.dismiss();
      }
    });
  alertLogout.show();
    }
    

    
   }
  });

 }

 @Override
 public View getGroupView(int groupPosition, boolean isExpanded,
   View convertView, ViewGroup parent) {
  GroupHolder holder;

  if (convertView == null) {
   convertView = inflater.inflate(R.layout.group_list, null);
   holder = new GroupHolder();

   holder.txtGroupName = (TextView) convertView
     .findViewById(R.id.txtGroupName);
   holder.txtGroupName.setTypeface(myTypeface);
   convertView.setTag(holder);

  } else {
   holder = (GroupHolder) convertView.getTag();
  }

  holder.txtGroupName.setText("Contact Us");
  return convertView;
 }

 @Override
 public Object getChild(int arg0, int arg1) {
  return null;
 }

 @Override
 public long getChildId(int groupPosition, int childPosition) {
  return 0;
 }

 @Override
 public int getChildrenCount(int groupPosition) {
  
  return 1;
 }

 @Override
 public Object getGroup(int groupPosition) {
  return null;
 }

 @Override
 public int getGroupCount() {
  return 1;
 }

 @Override
 public long getGroupId(int groupPosition) {
  return 0;
 }

 @Override
 public boolean hasStableIds() {
  return false;
 }

 @Override
 public boolean isChildSelectable(int groupPosition, int childPosition) {
  return false;
 }





  
Contact Us .xml

   <?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <RelativeLayout
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:background="@color/brown" >

        <RelativeLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="5dp"
            android:layout_marginRight="5dp"
            android:layout_marginTop="10dp" >

            <LinearLayout
                android:id="@+id/linear1"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content" >

                <TextView
                    android:id="@+id/textView1"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="Name"
                    android:textColor="@color/black" />

                <EditText
                    android:id="@+id/etName"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_marginLeft="5dp"
                    android:layout_weight="1"
                    android:ems="10"
                    android:inputType="textPersonName" />

            </LinearLayout>

            <LinearLayout
                android:id="@+id/linear2"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:layout_below="@id/linear1" >

                <TextView
                    android:id="@+id/textView1"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="Email"
                    android:textColor="@color/black" />

                <EditText
                    android:id="@+id/etEmail"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_marginLeft="5dp"
                    android:layout_weight="1"
                    android:ems="10"
                    android:inputType="textPersonName" />

            </LinearLayout>

            <LinearLayout
                android:id="@+id/linear3"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:layout_below="@id/linear2"
                android:orientation="vertical" >

                <TextView
                    android:id="@+id/textView2"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="Message"
                    android:textColor="@color/black" />

                <EditText
                    android:id="@+id/etMessage"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:inputType="textMultiLine" />
            </LinearLayout>

            <RelativeLayout
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:layout_below="@id/linear3" >

                <Button
                    android:id="@+id/btnMailSubmit"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_centerInParent="true"
                    android:text="Submit" />

            </RelativeLayout>
        </RelativeLayout>

    </RelativeLayout>

</RelativeLayout>

Contactus.xml layout  is inflated in getChildV
iew Method of adapter class..

Modifying OsmDroid in Android

Modifying OsmDroid in Android. 

Inorder to Modify osmdroid,we have to import it first.



How to import osmdroid-android project ?

While importing osmdroid-androi source,there may occur errors.
 So to avoid wastage of time ,we have to create a new java project "osmdroid-android" and place all files in "src" in the order it is from google svn checkout.
There contains other files like assets,bin etc and copy /create that also.Sometimes you have to import android.jar also.


After doing this ,suppose if we want a jar of this....

Follow the steps--------------
  1. Go to the Java Build Path (right click on your project in the navigator -> properties -> Java Build Path -> Libraries)
  2. Edit the “ANDROID_SDK_PLATFORM/android.jar” entry
  3. Click the “Variable” Button and add a new Variable called “ANDROID_SDK_PLATFORM” and your android platform folder as the desired path
  4. Back at the Build Path Libraries look inside the folder”JUnit 4″ and write down the filename of hamrest.core and the path of the junit.jar file – we’ll need them later
  5. change from Java Build Path to “Builders”
  6. Create a new Ant Builder and add the build.xml into “Buildfile” and select the project itself as Base Directory.
  7. Change to Tab “Target and click “Set Targets…” at the Manual Build Option
  8. Check “jar” in the selection and close with ok. There should be in the Manual Build: “build, jar”.
  9. Click Ok and be sure to have the new Ant builder active and the java Builder INACTIVE
  10. Open “build-jar.xml and delete in line 32 the following “depends=”version”
  11. Delete on line 37 “.r${version}
  12. Change on line 43 “destfile” to the folder where you want the Jar file to be created.
  13. Open build.xml and change the following lines
  14. 9 – at the value field enter your android platform folder
  15. 10 – at value enter your eclipse folder
  16. 16 and 17 – be sure the path and filename of the JUnit files are correct
  17. Run and hope that you get a Jar file at the end


Another Method for Creating Jar in Android
Select "osmdroid-android" project and click "Export".
In this,select "Java"-> "jar" and select what all files you want in your jar and 
finally  specify the destination path.

After creating the Modified Osmdroid jar,you can directly use in Android Project.


  

    


Open Street maps in Android -Part 2

Open Street maps in Android -Part 2

For knowing the basics of openstreet maps ,Refer 
http://androidtraininginkerala.blogspot.in/2013/01/open-street-maps-in-android-part-1.html


Today ,we have to check how to create offline map using osmdroid.For that we requires

Steps

1:Offline Map Source .

     Use MOBAC for creating offline map source.


2:After creating zip file,copy that file and paste it inside  /sdcard/osmdroid/
For eg: if our zipfile is "mymap.zip",then it should be like 
   /sdcard/osmdroid/mymap.zip

Folder Structure of mymap.zip
 " Mapnik->ZoomLevels->X value->Y.png "
Sample Code:
public class OsmdroidDemoMap extends Activity {

    private MapView         mMapView;
    private MapController   mMapController;

    @Override
    public void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);



         MapView mapView = new MapView(this, 256); //constructor
         mMapController=mapView.getController();
         mapView.setClickable(true);

         mapView.setBuiltInZoomControls(true);
         mapView.setMultiTouchControls(true);
         setContentView(mapView); 
          mapView.getController().setZoom(5); your need

         mMapController.setCenter(new GeoPoint(10.5649,-20.7097)); 

         mapView.setUseDataConnection(true);
       }
        
    }

  

    


Open Street Maps in Android--Part 1

Open Street Maps in Android--Part 1

Open Street Maps (Osmdroid) is mainly used as an alternative for Google Maps.The main Advantage of

this is the use of offline access.

To use this map, we requires 

1: Latest osmdroid jar (osmdroid-android-3.0.8.jar)
2: slf4j-android-1.5.8.jar

you can check out the project from 

https://code.google.com/p/osmdroid/


Sample Code:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <org.osmdroid.views.MapView
        android:id="@+id/mapview"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:clickable="true" />

</LinearLayout>

OsmdroidDemoMap.java
 public class OsmdroidDemoMap extends Activity {

    private MapView         mMapView;
    private MapController   mMapController;

    @Override
    public void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
    MapView map = (MapView) findViewById(R.id.map);
    map.setTileSource(TileSourceFactory.MAPNIK);   
    map.setBuiltInZoomControls(true);
    map.setMultiTouchControls(true);
    map.getController().setZoom(16);
    map.getController().setCenter(new GeoPoint(30266000, -97739000));
}  
Manifest Permissions
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/> 
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />


Load Images From Phone in Android by Specifying Image Path

Load Images From Phone in Android

Sample Code


private Bitmap getBitmap(String imageFilePath)
{



// Load up the image's dimensions not the image itself

BitmapFactory.Options bmpFactoryOptions = new BitmapFactory.Options();

bmpFactoryOptions.inJustDecodeBounds = true;

Bitmap bmp = BitmapFactory.decodeFile(imageFilePath, bmpFactoryOptions);

int heightRatio = (int) Math.ceil(bmpFactoryOptions.outHeight/ (float) DISPLAYHEIGHT);

int widthRatio = (int) Math.ceil(bmpFactoryOptions.outWidth/ (float) DISPLAYWIDTH);

Log.v("HEIGHTRATIO", "" + heightRatio);

Log.v("WIDTHRATIO", "" + widthRatio);

// If both of the ratios are greater than 1, one of the sides of
// the image is greater than the screen


if (heightRatio > 1 && widthRatio > 1) {

if (heightRatio > widthRatio) {

// Height ratio is larger, scale according to it

bmpFactoryOptions.inSampleSize = heightRatio;

} else {

// Width ratio is larger, scale according to it

bmpFactoryOptions.inSampleSize = widthRatio;

}

}

// Decode it for real
bmpFactoryOptions.inJustDecodeBounds = false;

bmp = BitmapFactory.decodeFile(imageFilePath, bmpFactoryOptions);

return bmp;
}

ClipBoard in Android



For Copying text ,we use Clipboard in android


Sample Code 



   ClipboardManager clipboard = (ClipboardManager) context
.getSystemService(Context.CLIPBOARD_SERVICE);
    clipboard.setText("Hello World");




For Pasting ,Use Long Press...................................

Getting AccessToken Using App id, App Secret Key of facebook app

Getting AccessToken  Using App id, App Secret Key of facebook app

use the url 

 https://graph.facebook.com/oauth/access_token? type=client_cred&client_id="+appId+"&client_secret="+appSecret


Sample Code:
 public static String getAccessToken() {


  InputStream is = null;

  String result = "";
  String url;
  String urlParameters = null;
  
  try {
   url = "https://graph.facebook.com/oauth/access_token?type=client_cred&client_id="+appId+"&client_secret="+appSecret;
   
   System.out.println("url is "+url);

   HttpClient httpclient = new DefaultHttpClient();
   HttpPost httppost = new HttpPost(url);
   HttpResponse response = httpclient.execute(httppost);
   HttpEntity entity = response.getEntity();
   is = entity.getContent();
  } catch (Exception e) {
   Log.e("log_tag", "Error in http connection " + e.toString());
  }
  // convert response to string
  try {

   BufferedReader reader = new BufferedReader(new InputStreamReader(
     is, "iso-8859-1"), 8);
   StringBuilder sb = new StringBuilder();
   String line = null;
   while ((line = reader.readLine()) != null) {
    sb.append(line + "\n");
   }
   is.close();

   result = sb.toString();

  } catch (Exception e) {
   Log.e("log_tag", "Error converting result " + e.toString());

  }

  return result;

 }
 

Popular Posts

About Me

Only For Sharing Android Related Things...

Facebook Fan Page