Good Post on Clean Code


Using SQL Statements as a String in Class file while working on Android or Java application can be such a pain.

I was checking in the net to find out whether there are any ways in which we can store the SQL Statments separately so that the code can be more readable.

I found some interesting stuff. Please find below the links for the same.

1. Clean Code

2. Java Practices : Keep SQL out of code.

3. Android : Store SQL Queries in an XML File (Stackoverflow answer)

I am working on a way to store all my SQL Statements in an XML File while working with Android.

Found this post on placing XML File with Data on Android in StackOverflow.

res

  • No subdirectorys are allowed under the specific resource-folders.
  • The R-class indexes all resources and provides simple access.
  • There are some simple methods which help reading files stored in the res-directory

assets

  • Subdirectorys are allowed (as much as you like).
  • No indexing by the R-class
  • Reading resources stored in assets is done using the AssetManager.

Also found a cool post on Working with resources in Android : Link.

 

SQL Statements in the case of Android can be stored in the strings.xml under the resources–> values  folder.

In case you using a Database class which is a pure java class the this link will be able to help you on how to do the same.

In my case, I created a separate DAO Class called the DBClass which deals with the connecting and disconnecting with the database. I set the context of the DAO class so that the strings can be used here.

Android: Filling a table from resource file using xml (SQLite)


Good link.

Cleanest way to build an SQL string in Java


Properties file can be used:

update_query=UPDATE user_table SET name=? WHERE id=?

Then with the help of a simple utility class:

public class Queries {

    private static final String propFileName = "queries.properties";
    private static Properties props;

    public static Properties getQueries() throws SQLException {
    	InputStream is = 
    		Queries.class.getResourceAsStream("/" + propFileName);
    	if (is == null){
    		throw new SQLException("Unable to load property file: " + propFileName);
    	}
    	//singleton
    	if(props == null){
    		props = new Properties();
    		try {
    			props.load(is);
    		} catch (IOException e) {
    			throw new SQLException("Unable to load property file: " + propFileName + "\n" + e.getMessage());
    		}			
    	}
    	return props;
    }

    public static String getQuery(String query) throws SQLException{
    	return getQueries().getProperty(query);
    }

}

you might use your queries as follows:

PreparedStatement stm = c.prepareStatement(Queries.getQuery("update_query"));

All credits to the guy who gave the answer.

Source : StackOverflow

Working with date in SQLite for Android


Working with dates in Oracle for reporting is very easy ( Since Oracle recognizes the date as datatype). But SQLite does not recognize Date as a datatype, this causes an issue when when you have to query for records that fall in between a range in SQLite.

 

Oracle it is very easy, just use he to_date command –

Oracle query :

SELECT amount,purchase_date FROM table_z
WHERE purchase_date >= TO_DATE('21-MAY-2011’,’DD-MON-YYYY’)
  AND puchase_date  <  TO_DATE('21-JAN-2012','DD-MON-YYYY');

In SQLite date needs to be converted into appropriate format before storing it in the database.

While storing in the database the date can be converted into YYYYMMDD format and stored in the database as an integer. Storing in this format in the database will ensure that older dates will have lesser value than the later ones.

Eg: 21-MAY-2011 will have 20110521

      21-JAN-2012  will have 20120121

The integer 20110521 < 20120121

So the SQlite equivalent of the query will be

SQLite Query :

SELECT amount,purchase_date FROM table_z
WHERE purchase_date >= 20110521
  AND puchase_date  <  20120121

Source: StackOverflow

Android Programming – setContentView()


setContentView() is a very important function when it comes to programming with Android.

One has to understand its use completely to work with Android UserInterface.

Basically what this function does is display the Layout created thorugh XML or the Dynamically created layout view in the Screen.

 

Syntax –

For an XML Layout –

setContentView(R.layout.showexcer);

where showexcer.xml is your xml file.

For Dynamically created Java View/Layout

View v1=new View(this);
setContentView(v1);

Similarly a dynamically created layout can be dispalyed using setContentView();

  • setContentView is amethod of Activity class. So to call you the class should be a subclass of Activity class.

Android Database Table export to CSV – Part 1


The best way to export data out of Android Sqlite database is create a copy the DB file into the SDCard.

Copy the Android database into DB File –

Advantages –

  • The import and export of the database would be a lot easy.
  • All tables could be backed up using a single file. ( This can have the backup of the user defined configuration of the program also ).

Disadvantages –

  • We need special tools to read this DB file which makes it difficult to be portable.

Copy a table into CSV file –

Advantages –

  • Only data required by the user can be given.
  • It is the more readable and portable format.

In my application I have decided to have both this methods. Will be updating soon.

Create a Alert Dialog in Android


Dialogs are generally used to display the the intermediate data like Status Messages, Warning Messages or Error Messages.

In this post we will go through how to create a Dialog Box in Android App development –

  • Create a function will call the Alert Dialog (AddEx is the activity. You can use your activity name over here ).
  1: private void displayDialog(String str1)
  2: {
  3:   AlertDialog.Builder builder = new AlertDialog.Builder(AddEx.this);
  4:   builder.setMessage(str1);
  5:   builder.setCancelable(false);
  6:   builder.setTitle("Status");
  7:   builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
  8:          @Override
  9:          public void onClick(DialogInterface dialog, int id) {
 10:           AddEx.this.finish();
 11:          }
 12:        });
 13:   AlertDialog alert = builder.create();
 14:   alert.show();
 15: }

  • Call this function anywhere in your activity class.
  1:  if(status == true)
  2:  {
  3:   displayDialog("Completed Successfully");
  4:  }
  5:  else
  6:  {
  7:    displayDialog("Error inserting into Table");
  8:  }
  • In the Alert Dialog you can also implement builder.setNegativebutton() method to have “CANCEL” part included in the dialog. Implementation is similar to setPositiveButton.