Maintaining global Application state

SDK Version: 

As a possible solutions mentioned in previous article Leaving an Android application the Application object can come handy. If you want to store data, global variables that needs to be accessed from everywhere in the application, from multiple Activities, in other words is you want to maintain a global "state" of the whole application the Application object can help.

For this we must make a class which extends the class add our own methods to it, and define this class in the AndroidManifest.xml as below:

  1. An example for the Application class:
  3. public class HelloApplication extends Application {
  4.         private int globalVariable=1;
  6.         public int getGlobalVariable() {
  7.                 return globalVariable;
  8.         }

Store images/files in database

SDK Version: 

Hoever the practice is to store them normally and save the access route (Uri), sometimes it can be handy to store files/images completely in database.
In sqlite database there are only a few data types, so its easy to choose: files can be stored in a text as a ByteArray.

Lets see a sample code, where we download an image from the Internet then store it in the local database:

  1. //where we want to download it from
  2. URL url = new URL(IMAGE_URL);  //
  3. //open the connection
  4. URLConnection ucon = url.openConnection();
  5. //buffer the download
  6. InputStream is = ucon.getInputStream();
  7. ByteArrayBuffer baf = new ByteArrayBuffer(128);
  8. //get the bytes one by one
  9. int current = 0;
  10. while ((current = != -1) {
  11.         baf.append((byte) current);
  12. }
  14. //store the data as a ByteArray
  15. //db is a SQLiteDatabase object
  16. ContentValues dataToInsert = new ContentValues();                          

Syndicate content