Pages

Showing posts with label google. Show all posts
Showing posts with label google. Show all posts

Wednesday, January 15, 2014

ImageView ScaleTypes

When there are images that need to be displayed in an Android app, we need to be careful with the way they are scaled. A first basic step is setting the right scaletype in your layout file.

The different scaletypes are:

  • center
  • centerInside
  • centerCrop
  • fitXY
  • fitStart
  • fitCenter (which is the default)
  • fitEnd
  • matrix (can be used for transformations but is not covered here)


This post will just simple show the different scaletypes with a screenshot of how it looks in the app.
Here's the code of my layout:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <ImageView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:src="@drawable/logo"
        android:scaleType="centerCrop" />

</RelativeLayout>

Image larger than its given space


center
centerInside
centerCrop
fitXY
fitStart
fitCenter (default)

fitEnd

Image smaller than its given space



center
centerInside
centerCrop
fitXY
fitStart

fitCenter

fitEnd

Wednesday, April 24, 2013

Parcelable versus Serializable

In this post I'm going to talk about the differences between Parcelables and Serializables.

Android Activities are great, aren't they? They allow you to structure your app in a nice and easy way. Switching between two Activities is also really easy. Just write this.startActvitiy(intent) somewhere in your first Activity and you're done.
There's only one thing that's not so easy to do, and that's passing data between these two Activities. If we want to pass data we have to put it in an Intent or a Bundle. This is quite easy for primitive classes such as String or int, but it's a bit harder for other (custom) objects.

If you have some experience in Java, you probably know something about 'serialization'. Since we're using Java in our Android app, we could let our object implement Serializable and we're done, right? Well, not quite. Android provides us with another interface called Parcelable to do this and there's a reason why.

Serializable

First of all let's have a look at our TestObject that implements Serializable.
public class TestObject implements Serializable{



 private static final long serialVersionUID = 643301981519798569L;

 private String mString;

 private int mInt;

 private List<String> mList;

 

 public TestObject() {

  this.mString = "This is a String";

  this.mInt = 777;

  mList = new ArrayList<String>();

  for(int i=0; i<100; i++){

   mList.add(String.valueOf(i));

  }

 }

    //Getters and Setters...

}

The only thing we had to do to make sure TestObject could be passed with an Intent or Bundle, was implementing it with java.io.Serializable and add a generated serialVersionUID. Now let's have a look at the same class but as a Parcelable.

Parcelable

This is our TestObject, implementing android.os.Parcelable.

public class TestObject implements Parcelable{



 private String mString;

 private int mInt;

 private List<String> mList;



 public TestObject() {

  this.mString = "This is a String";

  this.mInt = 777;

  mList = new ArrayList<String>();

  for(int i=0; i<100; i++){

   mList.add(String.valueOf(i));

  }

 }

 

 public TestObject(Parcel in) {

  mString = in.readString();

  mInt = in.readInt();

  mList = new ArrayList<String>();

  in.readStringList(mList);

 }



 @Override

 public int describeContents() {

  return 0;

 }



 @Override

 public void writeToParcel(Parcel dest, int flags) {

  dest.writeString(mString);

  dest.writeInt(mInt);

  dest.writeStringList(mList);

  

 }

 

 public static final Parcelable.Creator<TestObject> CREATOR = new Parcelable.Creator<TestObject>() {

        public TestObject createFromParcel(Parcel in) {

            return new TestObject(in); 

        }



        public TestObject[] newArray(int size) {

            return new TestObject[size];

        }

    };

    

    //Getters and Setters...

}
The first thing we notice here is that our class just became a lot bigger. As you can see we have to override two methods, write a Parcelable.Creator and write a new Constructor. Why should you go through all this trouble if you can just simple use Serializable instead? The answer is performance.

Parcelable splits your object up into primitives, sends those primitives and rebuilds the object afterwards. By doing this, it should run a lot faster. Serializable creates a lot of temporary objects and this causes quite some garbage collection, which should always be avoided, especially on mobile devices.

Putting it to the test

Of course, I ran a small test on this. I created an instance of TestObject, added it to an Intent, started another Activity and took our TestObject out of the Intent. I used TraceView for to check how long this process took for Parcelable and Serializable.
Here's our result for using the Serializable interface:


So we can see this whole process took 248ms. 
Now let's have a look at the results of using the Parcelable interface:

As you can see, for only this one object, the process was completed in less than half of the time for our first way. And let's not forget, this is the whole process of switching to another Activity, not just writing and reading the object!

Conclusion

Parcelable works a lot faster than Serializable and is the best way to go. But if we don't need to be faster, and it's possible to just use Serializable (e.g. android.graphics.Bitmap causes problems), just use Serializable and you don't have to bother about anything anymore.

Important notes:

  • Read from the Parcel in the same order that you wrote to it
  • Don't use raw Creators (specify by adding <TestObject> in this example)

Sunday, April 21, 2013

Image Caching with LruCache

Caching images

When we are building an application, whether it's a web app or a mobile app or whatsoever, we want to make sure it runs as fast as possible. One of the most important things we have to keep in mind is caching. If we are using certain resources in our application, we should know that it isn't always that easy to retrieve them. So we should always avoid to retrieve the same resources multiple times. This can be done by caching them. In this tutorial I'm going to give an example of how to cache images in your Android app.

Images can easily get quite large, so retrieving them can take up quite some time. Since mobile devices have limited resources (such as battery life, data transfers, etc), it's twice as important to make sure we cache images the right way.

SoftReferences?

Java already provides an easy way to do this. It's called SoftReferences. You can read all about it here. The only problem is that there is an issue in Android that causes the garbage collector not to respect these SoftReferences. You can read all about this issue here. The Android System provides another way of caching your objects, called LruCache.

LruCache

LRU stands for Least Recently Used. This already tells us a lot about how this cache would work. LruCaches have a fixed cache size and work like a queue, you might say.  If a new object is added to the cache, it's placed in the beginning of the queue. If the app asks to get an object from the cache, it's also placed in the beginning of this queue. This way the least recently used objects are left at the beginning of the queue.



If the cache doesn't have enough memory left, it deletes the least recently used objects until it has enough free space to store the new object(s).


API levels

LruCache was only added to API level 12 but don't worry, they have included this in the support library v4.

Code it!

Okay, it's nice to know how it works but now we still have to implement it in our code. For this tutorial I've made a small app that puts all the thumbnails of the images on the device in a large list. If the user scolls down, the images are loaded. This is actually really simple to implement. First let's have a look on how we could code the LruCache.


public class ThumbnailCache extends LruCache<Long, Bitmap>{



  public ThumbnailCache(int maxSizeInBytes) {

   super(maxSizeInBytes);

  }



  @Override

  protected int sizeOf(Long key, Bitmap value) {

   return value.getByteCount();

   

   //before API 11

   //return value.getRowBytes() * value.getHeight();

  }

  

  

 }

We have to add a value in the constructor of this LruCache. This is the maximum size of the cache in bytes. It can be hard to know how much this should be. You can get some help of the ActivityManager to do this.
ActivityManager am = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
int memoryClassBytes = am.getMemoryClass() * 1024 * 1024;
If we run this code, we'll get the memory limit of our application. This depends on what device you are using (on a Nexus S and Galaxy SII it's 48MB). Have a look here for more information.
It's obvious that we don't want our image cache to take up all of the memory of my application. So we only take a part of this. For this example let's say we use a sixth.
mCache = new ThumbnailCache(memoryClassBytes / 6);
Now place the image in our LruCache when it is retrieved using this line of code.
mCache.put(photoId, bitmap);

And check if it is in cache before retrieving it like this:
Bitmap cachedResult = mCache.get(photoId);

             if (cachedResult != null) {

                 imageView.setImageBitmap(cachedResult);

             }else{
              //retrieves the thumbnail and puts it in an imageview
              new ThumbnailTask(imageView).execute(photoId);

That's all you need to do. Give it a try!

Saturday, April 13, 2013

Supporting portrait and landscape screen orientations

When you are trying to make the next best app, it's important that you make sure your app looks great in both portrait and landscape orientation. Although the Android system already scales the default layout for both orientations, you should still make sure you optimize your application for the different orientations. Not only does it maximize the user experience of your app. But it can also provide an extra feature to you app. For example: showing a map in landscape view and a list in portrait view.

Now how do we make sure both of the orientations are optimized? Android provides a way to do this as effortless as possible. The only thing you have to do is create a new sub folder in the res folder. Let me just point out the three folders you can use/make to do this:

  • layout-land: The Android system will use these layouts when the device is in landscape view.
  • layout-port: The Android system will use these layouts when the device is in portrait view.
  • layout: This is the default folder for your layouts. If the system could not find the specified folder of the orientation, it will use the layouts inside this folder. So basically you just need to make one of the folders above.
Just make sure the layout files have the same name. That's all you have to do, it's just as simple as that.

Here's a small example of how your layouts should be organized.



Tuesday, April 9, 2013

Optimizing your Java code in Android (part 2)

It took me a bit longer than I had hoped, but I was finally able to write this next post in my series on Android Optimization. Some of the things in this post may seem obvious for people that have some experience in Java, but I have noticed that there are a lot of people who haven't seen that much (or none at all) Java code that get started on Android right away. So I'll mention these things in here as well.

I/O streams

I/O stands for Input and Output streams. We use these streams to read from and write to files on the device or on other devices. The classes for this can be found in the java.io package.

Closing streams

The first thing I want to start is closing streams. I just spent quite some time today at work figuring out why some files could not get deleted. The person who wrote the code forgot to close the InputStream of a file :/

So, whenever you are using an Input or OutputStream, always close it afterwards. The best way to do this is in a finally block. This way it will always be closed when the job is done, even if something went wrong. Here's an example:

FileInputStream fileInputStream = null;
  try
  {
   fileInputStream = new java.io.FileInputStream(someFile);
   fileInputStream.read ();
  }
  catch (java.io.FileNotFoundException e1)
  {
   System.out.println("Exception : File not found");
  }
  catch (java.lang.Exception e)
  {
   e.printStackTrace();
  }
  finally
  {
   fileInputStream.close ();
  }

Remember this. This will save you (and others) a lot of trouble.



Buffering

Most of the streams read and write one byte at a time. Unfortunately, this causes bad performance because it takes a lot of time to read/write when you are dealing with large amounts of data. But have no fear, java.io provides Buffered streams that can override this byte by byte behavior.

These classes are BufferedInputStream and BufferedOutputStream. The BufferedInputStream stores all the bytes that the FileInputStream sends until it reaches a limit. This limit is by default 512 bytes, but you can change this. Once this limit is reached, the BufferedInputStream sends the data.

If you want, you can also create a custom buffer. This can be done really easy by adding a byte[] to the constructor. This is probably one of the fastest ways to send a file. It all depends on the size of your file. Since I haven't got a lot of time, I looked for an example of using the streams online instead of writing one myself. But nevertheless it should explain everything.

This first method uses no Buffered stream, so sends everything byte by byte.
public static void readWrite(String fileFrom, String fileTo) throws IOException{

             InputStream in = null;

             OutputStream out = null;

             try{

                          in = new FileInputStream(fileFrom);

                          out = new FileOutputStream(fileTo);

                          while(true){

                                          int bytedata = in.read();

                                          if(bytedata == -1)

                                          break;

                                          out.write(bytedata);

                          }

             }

             finally{

              if(in != null)

                          in.close();

              if(out !=null)

                          out.close();

             }

}

This second method uses a Buffered stream with the default buffer of 512 bytes
public static void readWriteBuffer(String fileFrom, String fileTo) throws IOException{

             InputStream inBuffer = null;

             OutputStream outBuffer = null;

             try{

                          InputStream in = new FileInputStream(fileFrom);

                          inBuffer = new BufferedInputStream(in);

                          OutputStream out = new FileOutputStream(fileTo);

                          outBuffer = new BufferedOutputStream(out);

                          while(true){

                                          int bytedata = inBuffer.read();

                                          if(bytedata == -1)

                                          break;

                                          out.write(bytedata);

                          }

             }

             finally{

              if(inBuffer != null)

                          inBuffer.close();

              if(outBuffer !=null)

                          outBuffer.close();

             }

}

This last methods uses the method available() to define the size of the byte array. This is not always the best way, but it will do for this example.
         

public static void readWriteArray(String fileFrom, String fileTo) throws IOException{

             InputStream in = null;

             OutputStream out = null;

             try{

                          in = new FileInputStream(fileFrom);

                          out = new FileOutputStream(fileTo);

                          int availableLength = in.available();

                          byte[] totalBytes = new byte[availableLength];

                          int bytedata = in.read(totalBytes);

                          out.write(totalBytes);

                            

             }

             finally{

              if(in != null)

                          in.close();

              if(out !=null)

                          out.close();

             }

}          

}

A possible outcome of these methods (depending on the file):

  • the first method took 660 ms
  • the second method took 270ms
  • the third method took only 1 ms
Very important note: Custom buffering takes lot of memory if your file size is large, you should be careful about the memory capability of your system. If custom buffering takes lot of memory, try to reduce the array size so that the memory usage will not be large.

Monday, December 31, 2012

Move map to my location - Google Maps Android API v2

On request, here's a very small tutorial on how to move the map to your location in the new API.
Have a look at this code:

private void moveMapToMyLocation() {

  LocationManager locMan = (LocationManager)getActivity().getSystemService(Context.LOCATION_SERVICE);

  Criteria crit = new Criteria();

  Location loc = locMan.getLastKnownLocation(locMan.getBestProvider(crit, false));

  

  CameraPosition camPos = new CameraPosition.Builder()

   .target(new LatLng(loc.getLatitude(), loc.getLongitude()))

   .zoom(12.8f)

   .build();

  CameraUpdate camUpdate = CameraUpdateFactory.newCameraPosition(camPos);

  getMap().moveCamera(camUpdate);

  

 }

This is a method I made, you can place it somewhere in your custom MapFragment or in your Activity.

It's important to call this moment at the right time. We have to make sure that the map is loaded before we ask it to move to somewhere else:

  • in custom MapFragment: call the method somewhere in onActivityCreated(Bundle)
  • in Activity: call the method somewhere in onStart()
Moving the camera (your view of the map) around is possible by making a CameraPosition object, and using that to make the right CameraUpdate object.

Once we have our CameraUpdate object, we can choose to use moveCamera(CameraUpdate) or animateCamera(CameraUpdate). With moveCamera, the view will instantly change and with animateCamera you'll see the map moving on the screen towards the destination that we want. There are multiple arguments possible for these methods, please check the android API here for more information.

Good luck!

Thursday, December 27, 2012

Using InfoWindowAdapter Part 2: getInfoWindow

As promised, here's the second part on how to use the InfoWindowAdapter in Google Maps Android API v2. This is a sequel to my last blog post and also to the post before that. So be sure to check that out first.

In my last blog I told you how to change the contents of your InfoWindow without changing the default window layout. Now I'll show you how to change that window as well. First of all let me quote something that I read on the Android developers site:
The API will first call getInfoWindow(Marker) and if null is returned, it will then callgetInfoContents(Marker). If this also returns null, then the default info window will be used.
So this means you have to implement the contents of your InfoWindow in getInfoWindow(Marker) as well, if you want to change the window. The API will ignore what's in getInfoContents(Marker) if getInfoWindow(Marker) does not return null.

This is a screenshot of what our InfoWindow should look like:

You'll see I've copied the code of getInfoContents(Marker) of my last post and used this in getInfoWindow(Marker). I also did this with my xml layout file.

First of all, we're going to create this oval shape with the gradient blue background. We'll use this as background of our window. I've named it circle_window.xml and placed it in (one of) my drawable folder(s).


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

<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="oval" >

    <gradient android:startColor="#FFA1A4E3" android:endColor="#AFA1CDED"

            android:angle="270"/>

</shape>

Next I made a new layout file called custom_window.xml:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

  android:layout_width="wrap_content"

  android:layout_height="wrap_content"

  android:orientation="horizontal"

  android:background="@drawable/circle_window"

  android:padding="15dp">

  <ImageView

    android:id="@+id/ivInfoWindowMain"

    android:layout_width="wrap_content"

    android:layout_height="wrap_content"

    android:layout_marginRight="5dp"

    android:adjustViewBounds="true"

    android:src="@drawable/ic_launcher">

  </ImageView>

  <LinearLayout

    android:layout_width="wrap_content"

    android:layout_height="wrap_content"

    android:orientation="vertical">

    <TextView

      android:id="@+id/txtInfoWindowTitle"

      android:layout_width="wrap_content"

      android:layout_height="wrap_content"

      android:layout_gravity="center_horizontal"

      android:ellipsize="end"

      android:singleLine="true"

      android:textColor="#ff000000"

      android:textSize="14dp"

      android:textStyle="bold"/>

    <TextView

      android:id="@+id/txtInfoWindowEventType"

      android:layout_width="wrap_content"

      android:layout_height="wrap_content"

      android:ellipsize="end"

      android:singleLine="true"

      android:textColor="#ff7f7f7f"

      android:textSize="14dp"/>

  </LinearLayout>

</LinearLayout>

It's basically exactly the same as in my previous post, except for two things.

  • set the oval shape as background of my layout.
  • set a padding of about 15dp so that our contents is placed nicely within our oval shape
To finish of we need to implement our InfoWindowAdapter like this:

mapFragment.getMap().setInfoWindowAdapter(new InfoWindowAdapter() {

   

   private final View window = getLayoutInflater().inflate(R.layout.custom_window, null);

   

   @Override

   public View getInfoWindow(Marker marker) {

    EventInfo eventInfo = eventMarkerMap.get(marker);

    

    String title = marker.getTitle();

             TextView txtTitle = ((TextView) window.findViewById(R.id.txtInfoWindowTitle));

             if (title != null) {

                 // Spannable string allows us to edit the formatting of the text.

                 SpannableString titleText = new SpannableString(title);

                 titleText.setSpan(new ForegroundColorSpan(Color.RED), 0, titleText.length(), 0);

                 txtTitle.setText(titleText);

             } else {

                 txtTitle.setText("");

             }

             

             TextView txtType = ((TextView) window.findViewById(R.id.txtInfoWindowEventType));

             txtType.setText(eventInfo.getType());

             

    return window;

   }

   

   @Override

   public View getInfoContents(Marker marker) {

    //this method is not called if getInfoWindow(Marker) does not return null

    return null;

   }

  });

As always, if you have any questions, feel free to leave a comment below and I'll see what I can do.

Download source code here

Good luck!

Tuesday, December 18, 2012

Hi there!

Hi and welcome to Bon App-etit!

Let me introduce myself:
My name is Fré Dumazy and I'm a 22-year old computer science student from Belgium.
Lately I've been programming quite a lot in Android and that's why I wanted to start this blog.
Since Android names all its versions after snacks, I think "Bon App-etit" would be a good name for the blog.

I've been looking for a lot of good Android tutorials on the web, regarding specific subjects such as using the ActionBar, Google Maps integration, connecting to a remote database, etc.
I've found some good tutorials on these subjects but not on all of them.

I will try to write some good posts on specific subjects with example code, screenshots, etc. whenever I've got the time. So stay tuned!

PS: If there is a certain subject you would like to see in this blog, please place a comment and I'll see what I can do.