在用户操作App时更新Android SQLite数据库表,避免错误/糟糕的用户体验

时间:2012-10-02 05:29:18

标签: android sqlite

我的Android应用程序在SQLite数据库中有一个产品表,该数据库在用户安装时预先填充。该表可以从Azure Web服务更新。

我只想将2900条记录返回给应用程序,而不是仅从Web服务返回更新的记录并使用更新的记录填充SQLite表。这是因为大多数产品都会发生变化。打开App时,将使用SQL查询删除products表,并将ksoap2响应发送到插入数据库的Product对象。

虽然对产品表的更新正在进行,但我希望用户能够在不中断的情况下使用该应用程序。如果Products表已被删除,则他们无法正常操作App。

我有什么选择?我可以填充一个临时的Product表,当服务完成填充后,我可以将它复制到'live'Product表中。或者我可以完全删除Product表并将临时表重命名为“Product”吗?

或者我完全错了。任何建议都将非常感激。 代码摘录如下:

 try {

          productDatasource.open();
          productDatasource.deleteProductTable();
          productDatasource.close();
          ArrayList<Product> arrProduct = new ArrayList<Product>();
          SoapObject request = new SoapObject(NAMESPACE, PRODUCT_METHOD_NAME); 

         SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
         envelope.dotNet = true;
         envelope.setOutputSoapObject(request);
         System.out.println("startit");
         HttpTransportSE ht = new HttpTransportSE(URL);
         ht.debug = true;
         ht.call(SOAP_ACTION_PRODUCT, envelope);

         SoapObject response = (SoapObject) envelope.getResponse();

         productDatasource.open();
         productDatasource.deleteProductTable();
         Product[] products = new Product[response.getPropertyCount()];

         for (int i = 0; i < products.length; i++) {

             SoapObject prodObj = (SoapObject)response.getProperty(i);
             Product product = new Product();

             product.setProductID(Integer.parseInt(prodObj.getProperty(10).toString()));
             product.setProductName(prodObj.getProperty(11).toString());
             product.setFKCategoryID(Integer.parseInt(prodObj.getProperty(5).toString()));
             product.setFKSubCategoryID(Integer.parseInt(prodObj.getProperty(13).toString()));
             product.setFKBrandID(Integer.parseInt(prodObj.getProperty(2).toString()));      

             productDatasource.createProduct(product);
         }

2 个答案:

答案 0 :(得分:3)

DBHelper类遵循Respsitory模式。对底层数据的访问权限包含在“存储库”类中。这将释放您的主要逻辑,专注于业务逻辑,并将所有数据处理职责推送到存储库。根据应用程序的复杂性,存储库可以充当“Facade”,其中调用只是代理到负责域对象的存储库。

下面的代码为DBHelper

创建了一个非常简单的模板
public class DBHelper 
{

    Context context;
    private SQLiteDatabase db;
    private final String DB_NAME = "MYDataBase";
    private final int DB_VERSION = 1;
    private final String TABLE_NAME = "Animal";
    private final String TABLE_ROW_ID = "id";
    private final String TABLE_ROW_ONE = "animal_name";
    private final String TABLE_ROW_TWO = "animal_bio";


    public DBHelper(Context context)
    {
        this.context = context;
        CustomSQLiteOpenHelper helper = new CustomSQLiteOpenHelper(context);
        this.db = helper.getWritableDatabase();
    }

    public static byte[] getBitmapAsByteArray(Bitmap bitmap)
     {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        bitmap.compress(CompressFormat.PNG, 0, outputStream);       
        return outputStream.toByteArray();
    }   

    public void addRow(String name, String bio)
    {

        ContentValues values = new ContentValues();
        values.put(TABLE_ROW_ONE, name);
        values.put(TABLE_ROW_TWO, bio);


        try
        {
            db.insert(TABLE_NAME, null, values);
            Log.w("database message","Insert successfully");
        }
        catch(Exception e)
        {
            Log.e("DB ERROR", e.toString());
            //e.printStackTrace();
        }
    }
    public void deleteRow(long rowID)
    {
        try 
        {
            db.delete(TABLE_NAME, TABLE_ROW_ID + "=" + rowID, null);
                Log.w("database message","delete successfully");
        }
        catch (Exception e)
        {
            Log.e("DB ERROR", e.toString());
            e.printStackTrace();
        }
    }

    public void updateRow(long rowID,String name,String bio)
    {


        ContentValues values = new ContentValues();
        values.put(TABLE_ROW_ONE, name);
        values.put(TABLE_ROW_TWO, bio);

        try 
        {
            db.update(TABLE_NAME, values, TABLE_ROW_ID + "=" + rowID, null);
            Log.w("database message","Update successfully");
        }
        catch (Exception e)
        {
            Log.e("DB Error", e.toString());
            e.printStackTrace();
        }
    }
    public int count_row()
    {
        int row=0;
            Cursor cursor;

        try
        {
                    cursor = db.query(
                    TABLE_NAME,
                    new String[]{TABLE_ROW_ID, TABLE_ROW_ONE, TABLE_ROW_TWO},
                    null, null, null, null, null
            );

            cursor.moveToFirst();

            if (!cursor.isAfterLast())
            {
                do
                {
                    row++;
                }

                while (cursor.moveToNext());
            }
        }
        catch (SQLException e)
        {
            Log.e("DB Error", e.toString());
            e.printStackTrace();
        }
    Log.w("row count..",""+row);
        return row;
    }



    public void getRow(long rowID)
    {
        Cursor cursor;

        try
        {
            cursor = db.query
            (
                    TABLE_NAME,
                    new String[] { TABLE_ROW_ID, TABLE_ROW_ONE, TABLE_ROW_TWO},
                    TABLE_ROW_ID + "=" + rowID,
                    null, null, null, null, null
            );

            cursor.moveToFirst();

            if (!cursor.isAfterLast())
            {
                do
                {                   
                    Log.w("row ",""+cursor.getLong(0));
                    Log.w("row ",""+cursor.getString(1));
                    Log.w("row ",""+cursor.getFloat(2));

                }

                while (cursor.moveToNext());
            }
            cursor.close();
        }
        catch (SQLException e) 
        {
            Log.e("DB ERROR", e.toString());
            e.printStackTrace();
        }
    }
    public void getAllRows()
    {


        int i=0;
            Cursor cursor;

        try
        {
                    cursor = db.query(
                    TABLE_NAME,
                    new String[]{TABLE_ROW_ID, TABLE_ROW_ONE, TABLE_ROW_TWO},
                    null, null, null, null, null
            );

            cursor.moveToFirst();

            if (!cursor.isAfterLast())
            {
                do
                {
                    Log.w("row "+i,""+cursor.getLong(0));
                    Log.w("row "+i,""+cursor.getString(1));
                    Log.w("row "+i,""+cursor.getFloat(2));

                    i++;
                }

                while (cursor.moveToNext());
            }
        }
        catch (SQLException e)
        {
            Log.e("DB Error", e.toString());
            e.printStackTrace();
        }

    }
    private class CustomSQLiteOpenHelper extends SQLiteOpenHelper
    {
        public CustomSQLiteOpenHelper(Context context)
        {
            super(context, DB_NAME, null, DB_VERSION);
        }

        @Override
        public void onCreate(SQLiteDatabase db)
        {
            String newTableQueryString = "create table " +
                                        TABLE_NAME +
                                        " (" +
                                        TABLE_ROW_ID + " integer primary key autoincrement not null," +
                                        TABLE_ROW_ONE + " text," +
                                        TABLE_ROW_TWO + " text" +
                                        ");";
                db.execSQL(newTableQueryString);

        }


        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
        {

        }
    }
}

public void onCreate(Bundle savedInstanceState)     {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    DBHelper database = new DBHelper(this);
    database.addRow("name1","bio1"); 
    database.addRow("name2","bio2");        
    database.addRow("name3","bio3"); 
    database.addRow("name4","bio4"); 
    database.addRow("name5","bio5");

    database.getAllRows();

    database.updateRow(2,"name20","bio20");

    database.getAllRows();

    database.deleteRow(2);

    database.getAllRows();
}

更多细节 http://mel-tools.mit.edu/code/SimpleContentProvider/doc/edu/mit/mobile/android/content/class-use/DBHelper.html

在您的应用程序中复制DBHelper类 我希望它很有用.....

答案 1 :(得分:1)

将ContentProvider与CursorLoader一起使用,以便在内容更新时UI保持流畅。使用BulkInsert可以更快地添加行。如果您只是更新记录而不是替换它们,那么添加一个列,使您可以将记录标记为需要更新。有关在Android上开始使用SQL数据库的信息,请参阅http://developer.android.com/guide/topics/data/data-storage.html#dbhttp://developer.android.com/training/basics/data-storage/databases.html