运行服务时发生数据库锁定错误

发布于 2024-12-10 04:26:11 字数 7573 浏览 0 评论 0原文

我有一项服务,它将在服务的帮助下每 10 分钟更新一次 Sqllite 数据库的数据。我已经打开了一个数据库连接,并在数据更新时关闭了连接。

在我的应用程序中,我有不同的页面进行数据库更新。我还打开了数据库连接并关闭了每个页面的连接以进行数据更新。

问题是,当服务正在运行时,当在服务中打开连接时,我无法通过我的应用程序将数据更新到 sqlite。

有没有办法使用服务和应用程序同时运行数据库更新。

有人帮忙拿样品吗?

我正在调用我的服务中的函数,如下所示(代码)

public class service_helper extends Service {
    public static final String TAG = "Service";
    private NotificationManager mNM;
    private DatabaseAdapter dbAdapter;
    private service_updator serviceUpdator;
    private int NOTIFICATION = 1;
    private Timer timer = new Timer();
    @Override
    public IBinder onBind(Intent arg0) {

        return null;

    }

    @Override
    public void onCreate() {

        super.onCreate();


        serviceUpdator = new service_updator(this);
        dbAdapter = new DatabaseAdapter(this);
        dbAdapter.open();
        Toast.makeText(this, "Service created ...", Toast.LENGTH_LONG).show();   
        startService() ;
    }

    @Override
    public void onStart(Intent intent, int startid) {

    }

    @Override
    public void onDestroy() {
        timer.cancel();
        super.onDestroy();

        Toast.makeText(this, "Service destroyed ...", Toast.LENGTH_LONG).show();

    }

     private void startService()     
     {                   
         timer.scheduleAtFixedRate(new mainTask(), 0, 250000);   
         }    
     private class mainTask extends TimerTask    
     {         
         public void run()    
         {           
             try {
                serviceUpdator.UploadData();
                Log.d(TAG, "Service");
            } catch (ParserConfigurationException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();

            }
             }    
         } 



    private Runnable threadBody = new Runnable() {


             public void run() {

            try {

                serviceUpdator.UploadData();

                Log.d(TAG, "Service");
            } catch (ParserConfigurationException e) {
                            }

        }




    };


    }

UploadData() Function Code

    dbAdapter = new DatabaseAdapter(this.context);
            dbAdapter.open();
            Long transactionType = null;
            String transactionData = null;
            String sql = "Select * from tblTransaction where PKTransaction >?";
            Cursor cursorTransaction = dbAdapter.ExecuteRawQuery(sql, "-1");
            cursorTransaction.moveToFirst();
            dbAdapter.close();

                  for (int i = 0; i < cursorTransaction.getCount(); i++) {
                  }

    dbAdapter.close();

Application Code

    private void SaveSortOrder() throws Exception {
            try {
                String server1IPAddress = "";
                String server2IPAddress = "";
                String deviceId = "";

                Cursor cursorTransaction;
                Cursor cursorAdmin;

                DatabaseAdapter dbAdapter;
                DataXmlExporter dataXmlExporter;
                admin_helper adminhelper;
                Date date = new Date();

                SimpleDateFormat sdf = new SimpleDateFormat("dd-MMM-yyyy");
                String RevisedEstimatedDate = sdf.format(date);

                adminhelper = new admin_helper(this);
                cursorAdmin = adminhelper.GetAdminDetails();
                if (cursorAdmin.moveToFirst())
                    server1IPAddress = cursorAdmin.getString(cursorAdmin
                            .getColumnIndex("RemoteServer1IPAddress"));
                server2IPAddress = cursorAdmin.getString(cursorAdmin
                        .getColumnIndex("RemoteServer2IPAddress"));
                deviceId = cursorAdmin.getString(cursorAdmin
                        .getColumnIndex("DeviceID"));
                cursorAdmin.close();

                ContentValues initialSortOrder = new ContentValues();
                ContentValues initialTransaction = new ContentValues();
                for (int i = 0; i < ListSortOrder.getAdapter().getCount(); i++) {

                    HashMap result = (HashMap) ListSortOrder.getItemAtPosition(i);
                    View vListSortOrder;
                    vListSortOrder = ListSortOrder.getChildAt(i);

                    TextView Sort_DeliveryOrder = (TextView) vListSortOrder
                            .findViewById(R.id.et_Sort_Order);

                    initialSortOrder.put("DeliveryOrder", Sort_DeliveryOrder
                            .getText().toString());
                    dbAdapter = new DatabaseAdapter(this);
                    dbAdapter.open();

                    dbAdapter.BeginTransaction();
                    dbAdapter.UpdateRecord("tblDelivery", initialSortOrder,
                            "PKDelivery" + "="
                                    + result.get("Sort_PKDelivery").toString(),
                            null);

                    dataXmlExporter = new DataXmlExporter(this);
                    dataXmlExporter.StartDataSet();

                    String sqlTransaction = "Select 5 as TransactionType,'Update Delivery Order' as Description,'"
                            + result.get("Sort_PKDelivery").toString()
                            + "' as FKDelivery, "
                            + " deviceId as DeviceID ,'"
                            + Sort_DeliveryOrder.getText().toString()
                            + "' as DeliveryOrder ,date() as TransactionUploadDate,time() as TransactionUploadTime from tblAdmin where PKAdmin > ?";

                    cursorTransaction = dbAdapter.ExecuteRawQuery(sqlTransaction,
                            "-1");
                    dataXmlExporter.AddRowandColumns(cursorTransaction,
                            "Transaction");
                    String XMLTransactionData = dataXmlExporter.EndDataSet();

                    try {

                        if ((server1IPAddress != "") && (server2IPAddress != "")) {
                            try {
                                if (server1IPAddress != "") {
                                    InsertUploadedTrancasctionDetails(
                                            server1IPAddress, deviceId,
                                            XMLTransactionData);
                                }
                            } catch (Exception exception) {

                                if ((server1IPAddress != server2IPAddress)
                                        && (server2IPAddress != "")) {
                                    InsertUploadedTrancasctionDetails(
                                            server2IPAddress, deviceId,
                                            XMLTransactionData);
                                }
                            }

                        }
                    } catch (Exception exception) {

                        initialTransaction
                                .put("ReceivedDate", RevisedEstimatedDate);
                        initialTransaction.put("TransactionData",
                                XMLTransactionData);

                        dbAdapter.InsertRecord("tblTransaction", "",
                                initialTransaction);

                    }

                    dbAdapter.SetSucessfulTransaction();
                    dbAdapter.EndTransaction();
                    dbAdapter.close();

                }
            } catch (Exception exception) {
                throw exception;
            }
        }

I have a service which will update the Sqllite database with data at each 10 minute with the help of service.I have Opened a database connetion and closed the connection when data got updated.

In my application I have differnt pages where database updation took place.I have also Opened a database connetion and closed the connection each and every pages for data updation.

The Problem is that While the service is running I am not Able to Update the data to sqlite throught my application when conncetion opened in the service.

Is there any way to run data base updation simuntanously using service and application.

Will any one help with samples.

I am calling a function in my sevice as given below (code)

public class service_helper extends Service {
    public static final String TAG = "Service";
    private NotificationManager mNM;
    private DatabaseAdapter dbAdapter;
    private service_updator serviceUpdator;
    private int NOTIFICATION = 1;
    private Timer timer = new Timer();
    @Override
    public IBinder onBind(Intent arg0) {

        return null;

    }

    @Override
    public void onCreate() {

        super.onCreate();


        serviceUpdator = new service_updator(this);
        dbAdapter = new DatabaseAdapter(this);
        dbAdapter.open();
        Toast.makeText(this, "Service created ...", Toast.LENGTH_LONG).show();   
        startService() ;
    }

    @Override
    public void onStart(Intent intent, int startid) {

    }

    @Override
    public void onDestroy() {
        timer.cancel();
        super.onDestroy();

        Toast.makeText(this, "Service destroyed ...", Toast.LENGTH_LONG).show();

    }

     private void startService()     
     {                   
         timer.scheduleAtFixedRate(new mainTask(), 0, 250000);   
         }    
     private class mainTask extends TimerTask    
     {         
         public void run()    
         {           
             try {
                serviceUpdator.UploadData();
                Log.d(TAG, "Service");
            } catch (ParserConfigurationException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();

            }
             }    
         } 



    private Runnable threadBody = new Runnable() {


             public void run() {

            try {

                serviceUpdator.UploadData();

                Log.d(TAG, "Service");
            } catch (ParserConfigurationException e) {
                            }

        }




    };


    }

UploadData() Function Code

    dbAdapter = new DatabaseAdapter(this.context);
            dbAdapter.open();
            Long transactionType = null;
            String transactionData = null;
            String sql = "Select * from tblTransaction where PKTransaction >?";
            Cursor cursorTransaction = dbAdapter.ExecuteRawQuery(sql, "-1");
            cursorTransaction.moveToFirst();
            dbAdapter.close();

                  for (int i = 0; i < cursorTransaction.getCount(); i++) {
                  }

    dbAdapter.close();

Application Code

    private void SaveSortOrder() throws Exception {
            try {
                String server1IPAddress = "";
                String server2IPAddress = "";
                String deviceId = "";

                Cursor cursorTransaction;
                Cursor cursorAdmin;

                DatabaseAdapter dbAdapter;
                DataXmlExporter dataXmlExporter;
                admin_helper adminhelper;
                Date date = new Date();

                SimpleDateFormat sdf = new SimpleDateFormat("dd-MMM-yyyy");
                String RevisedEstimatedDate = sdf.format(date);

                adminhelper = new admin_helper(this);
                cursorAdmin = adminhelper.GetAdminDetails();
                if (cursorAdmin.moveToFirst())
                    server1IPAddress = cursorAdmin.getString(cursorAdmin
                            .getColumnIndex("RemoteServer1IPAddress"));
                server2IPAddress = cursorAdmin.getString(cursorAdmin
                        .getColumnIndex("RemoteServer2IPAddress"));
                deviceId = cursorAdmin.getString(cursorAdmin
                        .getColumnIndex("DeviceID"));
                cursorAdmin.close();

                ContentValues initialSortOrder = new ContentValues();
                ContentValues initialTransaction = new ContentValues();
                for (int i = 0; i < ListSortOrder.getAdapter().getCount(); i++) {

                    HashMap result = (HashMap) ListSortOrder.getItemAtPosition(i);
                    View vListSortOrder;
                    vListSortOrder = ListSortOrder.getChildAt(i);

                    TextView Sort_DeliveryOrder = (TextView) vListSortOrder
                            .findViewById(R.id.et_Sort_Order);

                    initialSortOrder.put("DeliveryOrder", Sort_DeliveryOrder
                            .getText().toString());
                    dbAdapter = new DatabaseAdapter(this);
                    dbAdapter.open();

                    dbAdapter.BeginTransaction();
                    dbAdapter.UpdateRecord("tblDelivery", initialSortOrder,
                            "PKDelivery" + "="
                                    + result.get("Sort_PKDelivery").toString(),
                            null);

                    dataXmlExporter = new DataXmlExporter(this);
                    dataXmlExporter.StartDataSet();

                    String sqlTransaction = "Select 5 as TransactionType,'Update Delivery Order' as Description,'"
                            + result.get("Sort_PKDelivery").toString()
                            + "' as FKDelivery, "
                            + " deviceId as DeviceID ,'"
                            + Sort_DeliveryOrder.getText().toString()
                            + "' as DeliveryOrder ,date() as TransactionUploadDate,time() as TransactionUploadTime from tblAdmin where PKAdmin > ?";

                    cursorTransaction = dbAdapter.ExecuteRawQuery(sqlTransaction,
                            "-1");
                    dataXmlExporter.AddRowandColumns(cursorTransaction,
                            "Transaction");
                    String XMLTransactionData = dataXmlExporter.EndDataSet();

                    try {

                        if ((server1IPAddress != "") && (server2IPAddress != "")) {
                            try {
                                if (server1IPAddress != "") {
                                    InsertUploadedTrancasctionDetails(
                                            server1IPAddress, deviceId,
                                            XMLTransactionData);
                                }
                            } catch (Exception exception) {

                                if ((server1IPAddress != server2IPAddress)
                                        && (server2IPAddress != "")) {
                                    InsertUploadedTrancasctionDetails(
                                            server2IPAddress, deviceId,
                                            XMLTransactionData);
                                }
                            }

                        }
                    } catch (Exception exception) {

                        initialTransaction
                                .put("ReceivedDate", RevisedEstimatedDate);
                        initialTransaction.put("TransactionData",
                                XMLTransactionData);

                        dbAdapter.InsertRecord("tblTransaction", "",
                                initialTransaction);

                    }

                    dbAdapter.SetSucessfulTransaction();
                    dbAdapter.EndTransaction();
                    dbAdapter.close();

                }
            } catch (Exception exception) {
                throw exception;
            }
        }

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

热风软妹 2024-12-17 04:26:11

当迁移到 Honeycomb 时,我遇到了类似的问题,它开始抛出 SQLiteDatabaseLockedException 我通过将内容提供程序放在我的数据库上对其进行排序,然后 Android 处理所有线程问题。当然,如果您愿意,您可以尝试找到线程问题,但这肯定会解决它:)

I had a similar problem when moving to Honeycomb it started throwing SQLiteDatabaseLockedException I sorted it by putting a content provider over my database and then Android handles all the threading issues. You can try find the threading problem if you want of course but that would definitely fix it :)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文