user2742861
user2742861

Reputation: 340

Android few questions

I've a few questions about android programming practices, since some of the tutorials/posts I found on the web (also in stackoverflow) are outdated. They are, mostly, from 2010, 2011 and talks about Android 2.1/2.2.

1) - Database close: Imagine that I have a cycle, which is going to insert/update values according to that cycle. The common insert function of a database initiates the database, opens the database, inserts it's content and closes the database.

public void addProduct(Product product) {
        ContentValues values = new ContentValues();
        values.put(COLUMN_PRODUCTNAME, product.getProductName());
        values.put(COLUMN_QUANTITY, product.getQuantity());

        SQLiteDatabase db = this.getWritableDatabase();

        db.insert(TABLE_PRODUCTS, null, values);
        db.close();
}

And in my activity I'll do the follow:

DatabaseHandler db = new DatabaseHandler(this);
for(int i = 0; i <= 100; i++){
   Product product = 
   new Product("example", i + 10);
   db.addProduct(product);
}

My question then is: it has no problem of closing the connection of database, in this case, 100 times?

2) - As you can see in this topic Is there a unique Android device ID?, the date is from 2010. I would like to know then what is the best way to get unique ID today? Is it ANDROID_ID? And before you ask why do I want unique identifiers, I can tell you that is for product licences and register that licence according to the ID.

3) - Should I use flags in Intents right before opening it? If so, why? I usually only do this piece of code:

Intent A = new Intent(MainActivity.this, OtherActivity.class);
startActivity(A);

Thanks guys.

Upvotes: 0

Views: 81

Answers (1)

CommonsWare
CommonsWare

Reputation: 1007494

My question then is: it has no problem of closing the connection of database, in this case, 100 times?

First, that's inefficient. Please open the database once.

Second, if you intend to use the database from multiple points in your app, particularly if more than one thread is involved, you need to have a singleton instance of SQLiteDatabase that everyone shares, for thread safety. Frequently, that really winds up being a singleton instance of SQLiteOpenHelper, from which you get the database as needed.

I would like to know then what is the best way to get unique ID today?

The best way is to not try. Instead, create unique IDs per app installation.

Should I use flags in Intents right before opening it?

"Right before opening it" is not necessary. Flags can be added to an Intent any time before that Intent is used.

I usually only do this piece of code

That may be fine. You use flags if you have a need for those flags.

Upvotes: 3

Related Questions