Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8387071
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 9, 20262026-06-09T18:06:58+00:00 2026-06-09T18:06:58+00:00

I’m working on my first Android application and I’ve run into an issue where

  • 0

I’m working on my first Android application and I’ve run into an issue where I’m reusing alot of code snippets to perform the db-connectivity. I see myself rewriting the same try/catch statements over and over again but I’m having issues seeing a good way to handle it. Please have a look at this code, do you see any obvious way that I am missing on how to refactor this?

As you can see there is often only 1 or 2 line difference in the methods. Here’s an example (all the other try/catch code is similar):

Cursor cursor = dbAdapter.fetchReceipts(timeFrom, timeTo);

Communicator.java

    public ArrayList<Receipt> getReceipts(int limit)
{
    ArrayList<Receipt> receiptList = null;
    DbAdapter dbAdapter = new DbAdapter(context);

    try
    {
        dbAdapter.open();
        Cursor cursor = dbAdapter.fetchReceipts(limit);

        if (cursor != null)
        {
            receiptList = buildReceiptList(cursor);
        }

        dbAdapter.close();
    }
    catch (SQLException e)
    {
        Log.d(context.getString(R.string.tag_receipttracker), e.getMessage());
        showToast(MESSAGE_COULD_NOT_OPEN);
    }
    return receiptList;
}

public ArrayList<Receipt> getReceipts(long timeFrom, long timeTo)
{
    ArrayList<Receipt> receiptList = null;
    DbAdapter dbAdapter = new DbAdapter(context);

    try
    {
        dbAdapter.open();
        Cursor cursor = dbAdapter.fetchReceipts(timeFrom, timeTo);

        if (cursor != null)
        {
            receiptList = buildReceiptList(cursor);
        }

        dbAdapter.close();
    }
    catch (SQLException e)
    {
        Log.d(context.getString(R.string.tag_receipttracker), e.getMessage());
        showToast(MESSAGE_COULD_NOT_OPEN);
    }
    return receiptList;
}


public Receipt getLatestReceipt()
{
    Receipt receipt = null;
    Cursor cursor = null;
    DbAdapter dbAdapter = new DbAdapter(context);

    try
    {
        dbAdapter.open();
        cursor = dbAdapter.fetchLastReceipt();

        if (cursor.getCount() > 0)
        {
            receipt = buildReceipt(cursor);
        }

        dbAdapter.close();
    }
    catch (SQLException e)
    {
        Log.d(context.getString(R.string.tag_receipttracker), e.getMessage());
        showToast(MESSAGE_COULD_NOT_OPEN);
    }
    return receipt;
}

public ArrayList<Receipt> searchReceipts(String query)
{
    ArrayList<Receipt> receiptList = null;
    DbAdapter dbAdapter = new DbAdapter(context);

    try
    {
        dbAdapter.open();
        Cursor cursor = dbAdapter.searchReceiptName(query);

        if (cursor != null)
        {
            receiptList = buildReceiptList(cursor);
        }

        dbAdapter.close();
    }
    catch (SQLException e)
    {
        Log.d(context.getString(R.string.tag_receipttracker), e.getMessage());
        showToast(MESSAGE_COULD_NOT_OPEN);
    }

    return receiptList;
}

public boolean updateReceipt(Receipt receipt)
{
    DbAdapter dbAdapter = new DbAdapter(context);
    boolean result = false;
    try
    {
        dbAdapter.open();
        result = dbAdapter.updateReceipt(receipt.getId(), receipt.getName(), receipt.getPhoto(), receipt.getTimestamp(),
                receipt.getLocationLat(), receipt.getLocationLong(), receipt.getSum(), receipt.getTax(), receipt.getComment());
        showResult(result);
        dbAdapter.close();
    }
    catch (SQLException e)
    {
        Log.d(context.getString(R.string.tag_receipttracker), e.getMessage());
        showToast(MESSAGE_COULD_NOT_OPEN);
    }
    return result;
}

private boolean insertReceipt(Receipt receipt)
{
    boolean result = false;
    DbAdapter dbAdapter = new DbAdapter(context);
    try
    {
        dbAdapter.open();
        result = dbAdapter.createReceipt(receipt.getName(), receipt.getPhoto(), receipt.getTimestamp(), receipt.getLocationLat(),
                receipt.getLocationLong(), receipt.getSum(), receipt.getTax(), receipt.getComment());
        showResult(result);
        dbAdapter.close();
    }
    catch (SQLException e)
    {
        Log.d(context.getString(R.string.tag_receipttracker), e.getMessage());
        showToast(MESSAGE_COULD_NOT_OPEN);
    }
    return result;
}

DBAdapter.java

public Cursor fetchReceipt(long rowId) throws SQLException
{

    Cursor cursor = db
            .query(true, DATABASE_TABLE_RECEIPTS, new String[] { KEY_ROWID, KEY_NAME, KEY_PHOTO, KEY_TIMESTAMP, KEY_LOCATION_LAT,
                    KEY_LOCATION_LONG, KEY_SUM, KEY_TAX, KEY_COMMENT }, KEY_ROWID + "=" + rowId, null, null, null, null, null);
    if (cursor != null)
    {
        cursor.moveToFirst();
    }
    return cursor;

}

public Cursor fetchReceipts(long timeFrom, long timeTo)
{
    Cursor cursor = db.query(true, DATABASE_TABLE_RECEIPTS, new String[] { KEY_ROWID, KEY_NAME, KEY_PHOTO, KEY_TIMESTAMP,
            KEY_LOCATION_LAT, KEY_LOCATION_LONG, KEY_SUM, KEY_TAX, KEY_COMMENT }, KEY_TIMESTAMP + ">" + timeFrom + " AND "
            + KEY_TIMESTAMP + "<" + timeTo, null, null, null, KEY_TIMESTAMP + " DESC", null);
    if (cursor != null)
    {
        cursor.moveToFirst();
    }
    return cursor;
}

public Cursor fetchLastReceipt()
{
    Cursor cursor = db.query(true, DATABASE_TABLE_RECEIPTS, new String[] { KEY_ROWID, KEY_NAME, KEY_PHOTO, KEY_TIMESTAMP,
            KEY_LOCATION_LAT, KEY_LOCATION_LONG, KEY_SUM, KEY_TAX, KEY_COMMENT }, null, null, null, null, KEY_ROWID + " DESC", "1");
    if (cursor != null)
    {
        cursor.moveToFirst();
    }
    return cursor;
}

public Cursor searchReceiptName(String query)
    {
        Cursor cursor = db.query(DATABASE_TABLE_RECEIPTS, new String[] { KEY_ROWID, KEY_NAME, KEY_PHOTO, KEY_TIMESTAMP, KEY_LOCATION_LAT,
                KEY_LOCATION_LONG, KEY_SUM, KEY_TAX, KEY_COMMENT }, KEY_NAME + " LIKE ?", new String[] { "%" + query + "%" }, null, null,
                null);
        if (cursor != null)
        {
            cursor.moveToFirst();
        }
        return cursor;
    }
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-09T18:07:00+00:00Added an answer on June 9, 2026 at 6:07 pm

    First of all when opening the db, I’d better use something like this:

    if (db == null || !db.isOpen()) {
    db = getWritableDatabase(); //getReadableDatabase();
    }
    

    which takes care for you to either create or open the database in case it is not yet done.

    For the first block of methods I’d clearly go for somethink like:

    public ArrayList<Receipt> searchReceipts(String query, DbAdapter _db, Cursor cursor)
    {
        ArrayList<Receipt> receiptList = null;
    
        try
        {
            _db.open();
    
            if (cursor != null)
            {
                receiptList = buildReceiptList(cursor);
            }
    
            _db.close();
        }
        catch (SQLException e)
        {
            Log.d(context.getString(R.string.tag_receipttracker), e.getMessage());
            showToast(MESSAGE_COULD_NOT_OPEN);
        }
    
        return receiptList;
    }
    

    This way you’ll just need to previously create the adapter and the cursor and pass them along in that main method that will perform the rest of the logic for all the calls.
    I noticed there’s one method in which you just return an object instead of an array. In this case you could just pass an array with a sole object inside.

    Hope it helps.

    Let me know about your impressions / updates.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

link Im having trouble converting the html entites into html characters, (&# 8217;) i
I ran into a problem. Wrote the following code snippet: teksti = teksti.Trim() teksti
I have a string like this: La Torre Eiffel paragonata all&#8217;Everest What PHP function
this is what i have right now Drawing an RSS feed into the php,
I have this code to decode numeric html entities to the UTF8 equivalent character.
I have a French site that I want to parse, but am running into
I would like to run a str_replace or preg_replace which looks for certain words
I'm parsing an RSS feed that has an &#8217; in it. SimpleXML turns this
We're building an app, our first using Rails 3, and we're having to build
I have this code: - (void)parser:(NSXMLParser *)parser foundCDATA:(NSData *)CDATABlock { NSString *someString = [[NSString

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.