Life,Love,God,Health,Wealth,Happiness


Android database error : close() was never explicitly called on database

Posted in Android by laaptu on November 12, 2011
Tags: , , , ,

ERROR/Database:close() was never explicitly called on database

This was the error,which continuously decorated my LOGCAT as I bounce to and fro between activities.And to my agony, I had closed all the opened database on activity onDestroy() method and opened the same database on activity onCreate() method.
Before moving further,I would like to show how I was implementing it

  1. I have DatabaseHelper class extending SQLiteOpenHelper
  2. And DatabaseManager class managing all the database related actions


public class DatabaseHelper extends SQLiteOpenHelper {
public DatabaseHelper(Context context) {
super(context, DB_NAME, null, DB_VERSION);
}

@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_CATEGORY_TABLE);
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS "+ CATEGORY_TABLE_NAME);
onCreate(db);
}
}



public class DatabaseManager {
private SQLiteDatabase db;

public DatabaseManager(Context context) {
DatabaseHelper dbHelper = new DatabaseHelper(context);
this.db = dbHelper.getWritableDatabase();
}

public void closeDatabase() {
db.close();
}
}


And on any activity I would implement database close and open like this

public class MainActivity extends Activity{
private DatabaseManager dbManager;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.firstpage_layout);
dbManager = new DatabaseManager(getApplicationContext());
}

@Override
protected void onDestroy() {
super.onDestroy();
if(dbManager != null)dbManager.closeDatabase();
}
}


But when I navigate from one activity to another,if I have to close the previously opened database ,I have to finish() the previous activity,and then only onDestroy() will be called.And my previously opened database will be closed and I can open the same database on another activity without any LOGCAT errors.

BUT,if I navigate to another activity,without finishing my previous activity,then onDestroy() method of previous activity won’t be called.Then,on next activity onCreate() method ,if I try to open the same database via

dbManager = new DatabaseManager(getApplicationContext());

LOGCAT will show error on DatabaseManager class

this.db = dbHelper.getWritableDatabase();


So,instead on closing database on activity onDestroy() method and opening database on activityonCreate(); close database on activity onPause()method and open database on activityonResume() method.


@Override
protected void onPause() {
super.onPause();
if(dbManager != null)dbManager.closeDatabase();
}

@Override
protected void onResume() {
super.onResume();
dbManager = new DatabaseManager(getAppicationContext());
}


But while browsing on StackOverflow answers I found two verdicts on this,some say it is unwise to close and open database repeatedly and state that open database only once and do all those database related actions.While,the other verdict opposes this and says that opening database for prolonged time is not a good practice. Frankly speaking,I couldn’t test which verdict is right and any of you readers able to clarify me these two verdicts,I will be glad.

Further as per the first verdict i.e. if you want to open database only once,then you can make DatabaseManager a singleton one like this

public class DatabaseManager {
private SQLiteDatabase db;
private static DatabaseManager INSTANCE;

private DatabaseManager(Context context) {
DatabaseHelper dbHelper = new DatabaseHelper(context);
this.db = dbHelper.getWritableDatabase();
}


public static DatabaseManager getInstance(Context context){
if(INSTANCE == null)INSTANCE = new DatabaseManager(context);
return INSTANCE;
}

And access this class on any activity via

public class MainActivity extends Activity{
private DatabaseManager dbManager;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.firstpage_layout);
dbManager = DatabaseManager.getInstance(getApplicationContext());
}
}

When you do this,there will be only one open database in your entire application and the LOGCAT error won’t be shown. I simply can’t decide which verdict to choose from,open database for entire application life or to close and open database on each activity.Any one implementation makes your application get rid of close()
was never explicitly called on database
error and if you could find out which one is the best one my blog comment is always open, CHEERS ;)

Android saving hashmap to phone memory

Posted in Android by laaptu on August 26, 2011
Tags: , , ,


While working on my current project,there was need to save HashMap to phone memory.Lots of example demonstrated saving ArrayList with String object,but my need was to save HashMap with custom objects.The format of my HashMap was

HashMap<String,SettingsValue>

And SettingsValue.java is like this

public class SettingsValue implements Serializable{

 private static final long serialVersionUID = -8631648651074307073L;
 public int intValue = -1;
 public String stringValue =null;
 public Boolean booleanValue =null;

 public Object fetchSomeValue(){
    if(intValue != -1){
      return intValue;
    }else if(stringValue != null){
      return stringValue;
    }else if(booleanValue != null){
      return booleanValue;
   }
     return null;
 }
}

For demonstration purpose let’s consider a layout having two buttons,on click of first button,the HashMap is stored to the memory and on click of second button,the same HashMap is restored from the phone memory.
Let our layout be main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:text="Save"
android:id="@+id/saveButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<Button
android:text="Fetch"
android:id="@+id/fetchButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</LinearLayout>

And lastly,our Activity class where ,there is store and fetch of HashMap of custom objects

public class ReadWriteActivity extends Activity {
private Map<String, SettingsValue> settingValueHolder =new HashMap<String, SettingsValue>();

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
populateHashMap();
Button saveButton=(Button)findViewById(R.id.saveButton);
Button fetchButton=(Button)findViewById(R.id.fetchButton);

saveButton.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
saveToPhoneMemory();
}
});

fetchButton.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
fetchFromPhoneMemory();
}
});
}

/*method to save HashMap to phone memory*/

protected void saveToPhoneMemory() {
String filename ="file.bin";
FileOutputStream fos;
try {
fos =openFileOutput(filename, Context.MODE_PRIVATE);
ObjectOutputStream out = new ObjectOutputStream(fos);
for(Map.Entry<String, SettingsValue>entrySet:settingValueHolder.entrySet()){
out.writeBytes(entrySet.getKey());
SettingsValue setValue = entrySet.getValue();
out.writeObject(setValue);
}
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}

/*method to retrieve stored HashMap from phone memory*/

protected void fetchFromPhoneMemory() {
try {
FileInputStream fIn =openFileInput("file.bin");
InputStreamReader isr = new InputStreamReader(fIn);
ObjectInputStream in = new ObjectInputStream(fIn);
HashMap<String,SettingsValue> newHashMap = new HashMap<String, SettingsValue>();
while(in.available()>0){
newHashMap.put(in.readLine(), (SettingsValue)in.readObject());
}
for(Map.Entry<String, SettingsValue>entrySet:newHashMap.entrySet()){
Log.i("KEY",entrySet.getKey());
SettingsValue setValue = entrySet.getValue();
Log.i("VALUE",String.valueOf(setValue.fetchSomeValue()));
}
} catch (Exception e) {
e.printStackTrace();
}
}

private void populateHashMap(){
SettingsValue setValue = new SettingsValue();
setValue.intValue =20;
settingValueHolder.put("Integer 20 value", setValue);
setValue = new SettingsValue();
setValue.booleanValue =true;
settingValueHolder.put("Boolean true", setValue);
setValue = new SettingsValue();
setValue.stringValue ="Hello there buddy";
settingValueHolder.put("String some value", setValue);
setValue = new SettingsValue();
setValue.booleanValue =false;
settingValueHolder.put("Boolean false", setValue);
}
}

So in this manner,we can save and retrieve HashMap with custom objects to and from phone memory.Hope this could help someone. ;)

Solution to : Android Emulator not connecting to internet even though there is internet connection on computer

Posted in Android,Ubuntu by laaptu on June 14, 2011
Tags: , , ,

For the past 2 days,I was boggled by my android emulator not connecting to the internet even though there was internet on my computer.Before going into quick fix,I would like to explain my scenario

My Scenario !!

Previously,there was proxy server at my office,and recently the proxy server was removed.Though I had unset all the proxy settings from my Lucid Linux,my android emulator was still using proxy settings.I came to know about this by running the emulator from terminal by using
emulator -avd laaptu2.3 -verbose
Here put your emulator name at laaptu2.3
At the terminal,it showed that the emulator is taking the my previous proxy settings.

Road to solution !!!

First I had to unset the proxy settings,that was still on my Ubuntu machine.This happened due to the fact,that while unsetting proxy settings,my Ubuntu machine wasn’t able to apply it system-wide even though I clicked apply system-wide option.The first place to unset proxy settings was from environment variables and you can edit environment variables via
sudo gedit /etc/environment
And remove all proxy settings options,if present there.Now,restart the computer.

Main Solution !!!

After starting your machine, start the emulator via the following ways
Step 1:
emulator -avd laaptu2.3 -dns-server 8.8.8.8 -verbose
Emulator on dns server
adb server

Take a look at second picture and it may be possible that your adb server won’t start.First close the running emulator and execute following command on the terminal

adb kill-server
adb start-server
emulator -avd laaptu2.3 -dns-server 8.8.8.8 -verbose

Here 8.8.8.8 is the dns-server for Google.com,and after searching so many forums and solution,this method really works.

Step 2:
It may seem tedious to add always the dns server from terminal.So for that,you can set this parameter on eclipse and for that follow the steps

Go to run i.e. the green arrow sign on eclipse
Then navigate to run configurations
And a configuration window will be presented
Go to target
And finally to Additional emulator command line options

Eclipse additional command line

And apply the changes.Now your emulator can browse the internet.Above solution i.e. Main Solution works for Window machine too.Hope ,this saves time for some troubled developer.Have fun and enjoy ;)

Ubuntu 10: How to use svn under proxy server

Posted in Ubuntu by laaptu on May 17, 2011


We have proxy servers at our office and due to it, I have to make modifications on several applications that needs to access internet.I frequently use svn for checkout of Google codes and in order to execute svn checkout, I had to manually set proxy configurations. Since, Ubuntu is installed at my workstation I couldn’t find any GUI of svn to manually set proxy setting as I had done on my Windows.
So after few quick search,I found the way to configure proxy settings on Ubuntu and I am sharing this tip.Please follow the following procedure and make sure that svn is installed in your machine

  1. Open terminal
  2. Invoke super user
  3. Navigate to /etc/subversion folder
  4. Then edit servers file using gedit or any other text editor
  5. Then under [global] header put the proxy settings as
  6. [global]
    http-proxy-exceptions = *.
    ##put the location of your proxy server
    http-proxy-host = 192.168.3.5
    ##out the location of your port
    http-proxy-port =3128
  7. Now save the servers file
  8. Now you are able to use svn under your proxy server


Navigate to svn folder
Editing svn servers
Using svn checkout
checkout process

This is all,hope you all can use svn under proxy on your respective Ubuntu OS.

Android: Decompiling resources of *.apk files using android-apktool,dex2jar and JD-GUI

Posted in Android by laaptu on May 16, 2011
Tags: , , , , ,


Since I am from flash background and in our flash environment “swf” decompiling is one of the most commonly used actions. So,I was curious whether the same reverse engineering process is applicable on Android platform or not? After some googling around I found a tool at
http://code.google.com/p/android-apktool/
which claimed to decompile *.apk files of Android. Then,without further delay I downloaded the files from download section of the above url and after completion of download,I extracted the files. Then I set the appropriate environment variables,so that I could access apktool from command line.
Then,I exported a sample.apk in some folder say sampleapp and I navigated to the that folder and used command line as follows


apktool d sample.apk

apktool usage

After that,I navigated to sampleapp folder and found a folder named sample app where there were decompiled files.While carefully examining the files,I found that the resources of sample.apk file was decompiled to the original format,but the java classes under the src folder were in .smali format.
So apktool was great for decompiling resources of android apk files.And if there is need to lookout for codes used on that apk files,you have to follow following procedure
First,you need to download two things from net

  1. dex2jar
  2. JD-GUI

  1. Unzip dex2jar and set environment variables in your respective OS,so that you could access it directly from command line.
  2. Let’s say you have someName.apk file,first unzip that file.
  3. When you unzip that file,you will get .dex extension file along with other files.Just maintain focus on .dex extension folder.
  4. Now go to command line and navigate to just unzipped folder location i.e. the location where .dex extension file exists and type on command line


//let's say our .dex extension filename be someName.dex;
//for windows
dex2jar someName.dex
//for linux versions
dex2jar.sh someName.dex

dex2jar
After doing this ,you will receive

someName.dex.dex2jar.jar

file.Now open ,this(someName.dex.dex2jar.jar) file with JD-GUI.Once you have opened it,you will see all the classes and their respective codes.
JD-GUI
This is so far the process,I have known to decompile .apk files
And finally ,I would recommend these tools, as they are not only great tools but also a way for Android developers to learn more from the sample apps whose resources aren’t readily available

Ubuntu 10: Installing ,upgrading flashplayer 10.2 on Ubuntu

Posted in Flash,Ubuntu by laaptu on May 10, 2011

Right now I am hooked to Ubuntu and I really love to explore it.I do want to thank those brilliant people who have made this incredible piece of marvel and are giving out for free.Keep up this great work to inspire all of us.



Since mine was a new machine with freshly installed Ubuntu 10,I needed to install flashplayer plugin on it.I googled and browsed lots of websites and found a lot of resources,but none was helpful to me.Finally I found the right way to install flash player 10.2 via this website

“http://linux-software-news-tutorials.blogspot.com/2010/09/install-flash-player-102-on-ubuntu.html”

and I like to share the same thing on my blog too.



Just follow the following commands on terminal to get updated version of flashplayer 10.2 on Ubuntu and F.Y.I this method works for upgrading flash player too on Ubuntu environment


  • sudo add-apt-repository ppa:sevenmachines/flash
  • sudo apt-get update
  • sudo apt-get install flashplugin64-installer

Hope this helps some of you to install or upgrade flashplayer 10.2 on Ubuntu 10

Ubuntu 10 : Using Android layoutopt command from terminal

Posted in Android,Ubuntu by laaptu on May 10, 2011


Recently I got to know about “layoutopt” command of Android ,and this command is situated under androidsdk/tools folder.In windows,I do know how to set environment variables ,so that I could access “layoutopt” command from my command line.But in Ubuntu,I found it hard ,not because it is hard but the way to implement it couldn’t be found easily on the net. I found two ways to implement “layoutopt” command in Ubuntu and that is what I am going to share with you all

First Way

  1. Go to terminal
  2. Navigate to the android sdk folder’s tool by typing cd androidsdk/tools
  3. then type ./layoutopt

In this manner you can implement “layoutopt” by jumping directly to the tools location and typing out the “layoutopt” command

Second Way

  1. Go to terminal
  2. Type

  3. sudo su
  4. cd /etc
  5. gedit bash.bashrc



gedit bash.bashrc
Note:gedit works only if gedit is installed in your Ubuntu

After you have opened “bash.bashrc” on gedit then type the following codes on it


#Android
export PATH=$PATH:/home/santosh/android_sdk/android-sdk-linux_x86/tools/

  1. Here “santosh” is the username where you should put your username
  2. And my android sdk is placed in home folder named as android_sdk/android-sdk-linux_x86/ and you should put the location of your androidsdk folder

bash.bashrc



Now save the bash.bashrc file and exit the gedit.
Launch terminal and type layoutopt and holla ,you can access all android tools through command line







Hope now you all can enjoy Android tools through Ubuntu command lines

The reason IT is alive,breathing and healthy

Posted in from my heart by laaptu on May 5, 2011
Tags:

There are billions of dollars invested in Information Technology and with each and every second,technology moves from better to best.With each day,we bask the warmth of new technology be it twitter,facebook,android,IOS and many other,that has indeed enhanced the way we live our life.Information technology is a great podium for revenue generation and that’s why companies are pouring down enormous amount of money on it. I have been actively involved in IT for about 3 years and during these 3 years I have seen rapid development in technology and the way we use web.


The overall credit of this rapid growth and development of IT industry shouldn’t go to IT companies alone.Companies will always be there if there is a chance to generate profit and huge investment will always be there ,if there is plethora of revenue generation schemes.For making IT sector alive and rocking,I want to credit those developers and designers who love to share.These people who work hard at their job and give 100 % at it,and even though they feel tired after a hard day’s work and instead of going to sleep,they work on their passion.And their passion includes sharing of information.Some of these evangelist go on forum and contribute in finding out the solution for others,some write blogs and share the knowledge they gained,some sit down on their code repository and post it on googlecode,github for others to use.They do all these things with full heart and by doing so ,they won’t receive any profit or revenue but also they do it.


Yes,this act,this noble act and I like to say this heroic act has made this IT industry alive and full of fun.These idols have paved a way for future learners and future contributers to move along ,and they do so without any selfishness and without any desire for money.
I have met lot of these peoples at forum,at googlecodes and github and at their personal blog.I want to salute you and you all have been my inspiration and you all are the reason this IT sector has air to breathe and is alive.

More to do and I will do it anyhow

Posted in It's My Life by laaptu on April 24, 2011

I always dream more and I believe I can achieve whatever I dream.But the bigger the dream ,the bigger is the disappointment.Meaning, whenever I dream big,I fail to do small actions that help me move forward to reach my dream.For instance, in order to progress in life,I must make some small changes in my behavior, like do exercise,meditation and give some time to recharge myself. I am always conscious to recharge my phone or my laptop but I don’t give much effort to recharge myself.


Right now ,I am learning Android programming and it is hectic for me to cover lots of topic and understand it fully.So work occupies my most of time and drains lots of my energy.And when I reach home,I always want to surf net or watch tv or go to sleep.This habit of mine hasn’t allowed me recharge myself.But this won’t happen from now on.From today I will give small effort to make small changes in my life and as the time goes by,I know my old habit will again interfere me.But then also,I will carry on cuz I have to do more by doing small things in a regular basis.Step by step,I will make changes in my life and with these little improvements,I will carry on to achieve the big dream I have.Now is the time to do more and do it anyway.

Android: Failed to fetch URL https://dl-ssl.google.com/android/repository/repository.xml :solution

Posted in Android by laaptu on April 14, 2011

At my office,I am using proxy server for internet connections.Due to this, while finding out the available packages from android repository, it always throws “Failed to fetch URL https://dl-ssl.google.com/android/repository/repository.xml “.After going through several internet solution, I finally found out the actual way to do it, by following the steps below

  • First navigate to android_sdk folder
  • Then run SDK Manager (which you will find under android sdk folder
  • At left you will find “settings”
  • At settings fill out HTTP proxy server and proxy port location
  • Then under misc check “force http://”



Now you are able to check available packages and download it

Next Page »

Follow

Get every new post delivered to your Inbox.