Saturday, August 30, 2014

How to solve Gradle project sync failed error in Android Studio

Before Android Studio I was using MotoDev an android IDE by Motorola. But, I found Android Studio which was developed on IDEA. Whenever we create a new project using Android Studio it develops on Gradle. A very common problem with Gradle that if we don't have internet then it fails building your project and gives an exception:

 Gradle project sync failed error
This error caused because it always try to find libraries over Internet and when it fails to find the dependencies then it fails. So, in order to execute you project offline you must need to fix this project setup.


  • Click on Invalidate Caches/Restart from the File Menu



  • Click on Invalidate and Restart



  • Let it download all the Gradle stuff it needs once, Gradle build success !
  • Rebuild project. After successful build of the project you may able to build your project offline.

Wednesday, August 27, 2014

Read Multiple Rows from Android SQLite Helper

This blog is in continuity with my previous three posts which were related to creation of a database helper class, insertion of new data entry intothe table and selection of a record from the database. After creating database in android and open the connection we had to add entries into the database. And after that we have seen how to select a single record from the database.

But now it's time to move to more advance level of retrieving records from the table. And now we must need to select multiple records from the table and populate it to the collection of POJO. (PreferenceInfo.java)

In order to retrieve a stored record into database we had to provide an identity value which will search the record into table against that id. But, here we are planning to search all the records from the database.

A List is a collection which maintains an ordering for its elements. Every element in the List has an index. Each element can thus be accessed by its index, with the first index being zero. Normally, Lists allow duplicate elements, as compared to Sets, where elements have to be unique.
public List<PreferenceInfo> getAllUsers(){
List<PreferenceInfo> preferenceInfos = new ArrayList<PreferenceInfo>();

This time query must not contain any kind of selection criteria and should remain wild.
String query = "select * from " + REGISTER_TABLE;

Now, we must need a connection in order to execute this query. This time we are planning to executing a raw query so will need a Writable Database object.
SQLiteDatabase db = this.getWritableDatabase();

Here, we must need to store the results into the Cursor so that we can retrieve every single row and assign it to the POJO. Once things will be done we will start adding it to the list after each row population.
Cursor cursor = db.rawQuery(query, null);

Iterating over each row, building POJO and adding it to list
PreferenceInfo prefInfo = null;

Move the cursor to the first row. This method will return false if the cursor is empty.
if(cursor.moveToFirst()){
do{

Refreshing object in each iteration and assigning new values from the cursor.
prefInfo = new PreferenceInfo();
prefInfo.setSecurityNumber(Integer.parseInt(cursor.getString(0)));
prefInfo.setEmail(cursor.getString(1));
prefInfo.setPassword(cursor.getString(2));
prefInfo.setUserName(cursor.getString(3));
prefInfo.setMobileNumber(cursor.getString(4));
prefInfo.setKeyMessage(cursor.getString(5));

Adding each object to the list
preferenceInfos.add(prefInfo);
}while(cursor.moveToNext());

Move the cursor to the first row. This method will return false if the cursor is empty. And after completion of iteration we will simply return the list to the method.


  return preferenceInfos;

If you find it helpful kindly click the donate button on the top of page. Also added an attachment of the files used in this blog which can bee seen by clicking on links below:

Read One Record from SQLite Android Helper

This blog is in continuity with my previous two posts which was related to creation of a database helper class and insertion of new data entry into the table. After creating database in android and open the connection we had to add entries into the database. But, as we are already done with the insertion of records into the table. So, now it's time to search for the added record.

So, here we will use PreferenceInfo POJO for assigning retrieved values to the object.

in order to retrieve a stored record into database we must need to provide an identity value which will search the record into table against that id.
public PreferenceInfo getUser(int id){

As I have already mentioned in my previous two blogs; we must need to get a readabledatabase object because here we only need to read a database.

SQLiteDatabase db=null;
// 1. get reference to readable DB
try{
db = this.getReadableDatabase();
}catch (Exception e){
Toast.makeText(currentContext, "database cannot be opened", Toast.LENGTH_LONG);
}

Now like the database we must need to initialize the cursor. Cursor interface provides random read-write access to the result set returned by a database query. So, now we must need to build query:
Cursor cursor =
db.query(REGISTER_TABLE, // a. table
COLUMNS, // b. column names
SECURITY_NUMBER +" = ?", // c. selections
new String[] { String.valueOf(id) }, // d. selections args
null, // e. group by
null, // f. having
null, // g. order by
null); // h. limit

Now, we must need to check for the cursor, if results will be returned then cursor will be populated else it will remain null.
if (cursor != null)

after validating the cursor, we must need to move the cursor to the first row. This method will return false if the cursor is empty. Here, we are retrieving only one record because we know that for each identity only one record exist into the table.
cursor.moveToFirst();

Now we must need to populate the data from table into the POJO and then return the object into that method.
PreferenceInfo preferenceInfo = new PreferenceInfo();

Now we will get the values from the zero-based index of the target column and will set into the relevant property of POJO using the setters.
preferenceInfo.setSecurityNumber(Integer.parseInt(cursor.getString(0)));
preferenceInfo.setEmail(cursor.getString(1));
preferenceInfo.setPassword(cursor.getString(2));
preferenceInfo.setUserName(cursor.getString(3));
preferenceInfo.setMobileNumber(cursor.getString(4));
preferenceInfo.setKeyMessage(cursor.getString(5));

After complete transformation of cursor to object, we will return the object back to the method.
return preferenceInfo;


If you find it helpful kindly click the donate button on the top of page. Also added an attachment of the files


Now, the updated DatabaseHelper file and PreferenceInfo.java file

Insert new record into SQLite Database Android


This blog is in continuity with my previous post which was related to creation of a database helper class. After creating database in android and open the connection we need to add entries into the database.

But before that we just need to create a POJO (Plain Old Java Object) for the table so that we can store the values and directly send it to the database. POJO of PreferenceInfo can be downloaded from this link. (PreferenceInfo.java)

In order to add a new entry into the database we get a SQLiteDatabase writable instance by adding following line
SQLiteDatabase db = this.getWritableDatabase();

After getting the database we must need to set the values that we need to persist into the database to sepecific column name:
ContentValues newValues = new ContentValues();
newValues.put(E_MAIL, preferenceInfo.getEmail());
newValues.put(PASSWORD, preferenceInfo.getPassword());
newValues.put(USER_NAME, preferenceInfo.getUserName());
newValues.put(MOBILE_NUMBER, preferenceInfo.getMobileNumber());
newValues.put(KEY_MESSAGE, preferenceInfo.getKeyMessage());

Now, insert the values into the table by using insert method of the SQLiteDatabase instance
db.insert(REGISTER_TABLE, //table
null,//ColumnHack,
newValues); // key/value -> keys = column names/ values = column values

Now after each and everything we must need to close the database connection after adding the data into database.
db.close();


Updated AndroidHelper file and PreferenceInfo.java POJO.

Android Database Helper


For every android application we mostly need to create a data layer which keeps the parametric data and some user related settings persisted. But it's not equivalent to the actual data layer that we have in our desktop based or web based application where we have an external database server. Because we can't keep such a huge application on our mobile devices.

In order to access stored data into our application, we can try two different approaches, one is to keep the data into a database server and access it via web service. But, for some user related settings why do we need such hassle. Because we don't need to access internet all the time in order to retrieve some basic user related information. So we will go for second approach which is to store a file on our local device and access it directly.

But, we want to make a structure in order to retrieve data and store data in some generic form. Yes, just like we do in databases. So, here in andorid SQLLite is a database which is stored in a file and can be accessed just like a database. I think it's fair enough for just a basic introduction, now we can jump into the code.

In order to keep my code generic and reusable by my other application I have created a separate class which I normally import in my every application which is related to database. Here, I am creating a class which is extending SQLiteOpenHelper which an android class available in package android.database.sqlite.

public class AppNameSQLiteOpenHelper extends SQLiteOpenHelper {

In this line we just need to mention the name of file that will be created in our application.
public static final String DB_NAME = "appname_db.sqllite";

Version is a necessary field that we just need to store into the application, this version will be updated whenever we just need to update the schema otherwise it will be considered the same schema and will never be replaced with a new file. For application development I think it's necessary to keep the version updated after every few changes so, that we can just have an updated schema whenever needed..
public static final int VERSION = 1;

In order to exposes methods to manage a SQLite database. SQLiteDatabase has methods to create, delete, execute SQL commands, and perform other common database management tasks. So, here we are just creating an instance of SQLiteDatabase which will be used later in our application.
public SQLiteDatabase DB;
The path of Database where we will have our database file stored on device.
public String DBPath;

Context is an interface to global information about an application environment. This is an abstract class whose implementation is provided by the Android system. It allows access to application-specific resources and classes, as well as up-calls for application-level operations such as launching activities, broadcasting and receiving intents, etc.
public static Context currentContext;

I am keeping the table name and fields in variables in order to avoid errors.
//Name of Table:
public static final String REGISTER_TABLE = "register";
//Fields:
public static final String USER_NAME = "username";
public static final String PASSWORD = "password";
public static final String E_MAIL = "email";
public static final String MOBILE_NUMBER = "mobilenumber";
public static final String KEY_MESSAGE = "keymessage";
public static final String SECURITY_NUMBER = "securityno";
// Columns:
private static final String[] COLUMNS = {SECURITY_NUMBER, USER_NAME, PASSWORD, E_MAIL, MOBILE_NUMBER, KEY_MESSAGE};

Here I am just creating an overloaded constructor to manage database creation and version management. This construcot will get a context of application as an argument and furhter call the parent class and after that the object will be used to create, open, and/or manage a database.
public TrackerSQLiteOpenHelper(Context context) {

Here context of the application using the database.
super(context, DB_NAME, null, VERSION);

On create method will only be called when the database is created for the first time. This is where the creation of tables and the initial population of the tables should happen. This method expect a variable to hold the database instance,
@Override
public void onCreate(SQLiteDatabase db) {
createTable(db);
}

Create table will be called at the time of onCreate because we don't want to create table eachtime the application starts. Neither we want to create database everytime we start our application. So, here we are using a simple condition to avoid multiple databases creation.
private void createTable(SQLiteDatabase db) {

Here we have created a method checkDbExists that will insure the existence of database on our device.
boolean dbExists = checkDbExists();

checkDbExists method try to open the database with the variables defined for the creation of a new database. If database opens then it returns true else false
SQLiteDatabase checkDB = null;
try {
String myPath = DBPath + DB_NAME;

Here we are opening the database and assigning it to SQLiteDatabase instance, but if the instance is not null means the database doesn't exist.
checkDB = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);

we must need to catch SQLiteException in catch block application will only move if the database will not exist.
} catch (SQLiteException e) {
// database does't exist yet.
}

As here we are just checking for the application so we must need to close the database instance that we have used to check the existence. Because we are not going to execute queries with this instance but, the other instance we have mentioned at the class level.
if (checkDB != null) {
checkDB.close();
}

Update the variable to validate the database.
dbExists = checkDB != null ? true : false;

if (!dbExists) {

This line is the most important line that will even open or create the database with the DB_NAME that we have mentioned in the start of our code.
DB = currentContext.openOrCreateDatabase(DB_NAME, 0, null);

Once, we are done with the craetion of database we will have to move to creation of table where our data will be persisted. So, here similar to SQL we are going to use a create table query.
String CREATE_REGISTER_TABLE = "create table register ( " +
SECURITY_NUMBER +" integer primary key autoincrement, " + USER_NAME + " text, " + PASSWORD +" text," +
E_MAIL +" text, " + MOBILE_NUMBER +" text, " + KEY_MESSAGE +" text )";

Here, we are going to use the database instance that we got from the createTable method and using the method execSQL which will create table for us..
db.execSQL(CREATE_REGISTER_TABLE);

This method will only be called when the database needs to be upgraded. The implementation should use this method to drop tables, add tables, or do anything else it needs to upgrade to the new schema version. This method will only accept 3 variables one database instance, oldVersion and newVersion number which will be integer type of variable.
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

In order to upgrade the schema we must need to Drop older tables if existed and the next line of code will do this for us.
db.execSQL("DROP TABLE IF EXISTS "+REGISTER_TABLE);

And after droping table we must need to create new tables for our database. So, once again we will give call to onCreate method that will create a new table set for us.


        this.onCreate(db);

Will update with the searching and insertion in my next blog.

If you find it helpful kindly click the donate button on the top of page. Also added an attachment of the Initial AndroidHelperClass.

DOWNLOAD SQL Helper Class