Welcome to Gaia! :: View User's Journal | Gaia Journals

 
 

View User's Journal

Report This Entry Subscribe to this Journal
Latinam Scivi
Around a kid, a job, and other instances of life, I attempt to post something once in a blue moon. Restarted, for another attempt, February of 2012.
When I Finally Think Like a Developer
In my android app, the one I plan to use for Sacred Rules Minus and any other card game I design, I finally hit a point where I got sick of thinking like an amateur.

When updating or inserting rows into a database, you can do it several ways: the android supported ContentValues row, which looks bulky in most cases; or by using strings and concatenating them, which leads to easy typos and other issues, and also might look bulky.

To avoid this, I decided to look at the ContentValues constructors to see if there was some way I could pass in a name-value pair list instead of having to initialize them like a map usually is. Nothing.

Which means, to most programmers anyways, make one.

Here's my first go:




Code:
private ContentValues loadValues(String [] cols, String [] values) {
   ContentValues cv = new ContentValues();

   for (int i = 0; i < cols.length; i++) {
      cv.put(cols[i], values[i]);
   }
      
   return cv;
}



Yeah, not particularly pretty, but it makes some functions a lot cleaner.

For example, this




Code:
ContentValues cv = new ContentValues();
      cv.put("col1", val1);
      cv.put("col2", "val2");
      cv.put("col3", "val3");
      cv.put("col4", "val4");
      cv.put("col5", val5);
   db.insert("Table", null, cv);



becomes




Code:
db.insert("Table", null, loadValues(new String[]{"col1", "col2", "col3", "col4",
            "col5"}, new String[]{String.valueOf(val1), val2, val3, val4,
            String.valueOf(val5)}));



This is, admittedly, a personal preference. It requires more computational power (it has to form those arrays, then iterate through them), and doesn't line up as nicely as the "cv.put(column, value)" does. However, since I end up with more than a dozen values in some cases, it looks a lot cleaner than the huge "cv.put(x, y)" lists.

Use it if you want, don't if you think it isn't worth it. Considering the simplicity of it, there's no reality in me sitting on it as if it were entirely my idea.

LiaThistle
Community Member
  • 02/16/14 to 02/09/14 (1)
  • 10/13/13 to 10/06/13 (1)
  • 07/21/13 to 07/14/13 (1)
  • 04/28/13 to 04/21/13 (2)
  • 04/14/13 to 04/07/13 (1)
  • 03/24/13 to 03/17/13 (1)
  • 03/17/13 to 03/10/13 (1)
  • 03/10/13 to 03/03/13 (1)
  • 02/03/13 to 01/27/13 (1)
  • 01/20/13 to 01/13/13 (1)



  •  
     
    Manage Your Items
    Other Stuff
    Get GCash
    Offers
    Get Items
    More Items
    Where Everyone Hangs Out
    Other Community Areas
    Virtual Spaces
    Fun Stuff
    Gaia's Games