SQLiteOpenHelper - 无法访问已处置的对象

问题描述 投票:0回答:1

我有一个我的SQLiteOpenHelper类,它被写成一个单身人士。我应该注意到我在Java中没有这样做,我使用Xamarin.Android C#来编写这个。

这是该类的一个片段:

public class DatabaseHelper : SQLiteOpenHelper
{
    private static readonly string TAG = typeof(DatabaseHelper).FullName;

    private static readonly string _databaseName = "istockdb";

    private static readonly int _databaseVersion = 32;

    private static DatabaseHelper _instance;

    private Context _context;

    private DatabaseHelper(Context context) : base(context, _databaseName, null, _databaseVersion)
    {
        _context = context;
    }

    [MethodImpl(MethodImplOptions.Synchronized)]
    public static DatabaseHelper Instance(Context context)
    {
        // *** Use the application context, which will ensure that ***
        // *** the Activity's context is not accidentally leaked ***
        return _instance ?? (_instance = new DatabaseHelper(context.ApplicationContext));
    }

}

所以我的DatabaseHelper是一个单身人士,在活动和服务中使用如下:

服务:

[Service(Name=Text.MobileBackgroundHbService, Enabled = true, Exported = true), IntentFilter(new []{Intents.SyncHeartbeats})]
public class BGHeartbeatService : BaseIntentService
{
    public BGHeartbeatService()
    {
        this._database = DatabaseHelper.Instance(Application.Context);
    }

    protected override void OnHandleIntent(Intent intent)
    {
        if (this._database == null)
            this._database = DatabaseHelper.Instance(Application.Context);

        if (intent.Action.Equals(Intents.SyncHeartbeats)) SyncHeartbeatRecords();

        var broadcastIntent = new Intent(Intents.MobileRefresh);
        SendBroadcast(broadcastIntent);
    }

}

活动,实际上是所有活动继承自的BaseActivity

[Activity(Label = "BaseActivity")]
public abstract class BaseActivity : AppCompatActivity
{
    /// <summary>
    /// Reference to the current context.
    /// </summary>
    protected Context _context { get; set; }

    /// <summary>
    /// "Tag" used for Log functionallity.
    /// </summary>
    protected string _tag { get; set; }

    /// <summary>
    /// Reference To <see cref="RemoteSyncServiceConnection"/>
    /// </summary>
    protected RemoteSyncServiceConnection _service_connection;

    /// <summary>
    /// Reference To The Current SessionState.
    /// </summary>
    protected SessionState _session_state;

    /// <summary>
    /// Reference To <see cref="SyncReceiver"/>
    /// </summary>
    protected SyncReceiver _sync_receiver;

    /// <summary>
    /// Base FloatingActionButton.
    /// </summary>
    protected FloatingActionButton _base_fab;

    /// <summary>
    /// Is the Fab Menu Shown / Hid.
    /// </summary>
    protected static bool _is_fab_open;

    protected IConnection _printer_connection;

    protected string _printer_address;

    protected bool _service_required;

    protected bool _receiver_required;

    protected MediaPlayer _media_player;

    protected DatabaseHelper _database;

    /// <summary>
    /// <see cref="IntentFilter"/> for the <see cref="SyncReceiver"/>
    /// </summary>
    protected readonly string[] _intent_filters =
    {
        Intents.AlarmCompleteOrders,
        Intents.AlarmHeartbeats,
        Intents.AlarmPkas,
        Intents.AlarmTrackingScans,
        Intents.MobileRefresh
    };

    #region Lifecycle Methods

    /// <summary>
    /// Application Lifecycle Method.
    /// </summary>
    /// <param name="savedInstanceState"></param>
    protected override void OnCreate(Bundle savedInstanceState)
    {
        base.OnCreate(savedInstanceState);

        // *** Initialize Xamarin.Essentials ***
        Xamarin.Essentials.Platform.Init(this, savedInstanceState);

        // *** Initialize the DatabaseHelper ***
        if(this._database == null)
            this._database = DatabaseHelper.Instance(this.ApplicationContext);
    }

}

DatabaseHelper实例经常处理,导致服务或活动尝试访问已处置的_database对象。

如何处理这个以及为什么?

我认为在_instance中使DatabaseHelper静态以及使构造函数私有并强制使用DatabaseHelper.Instance方法将保留DatabaseHelper的单个实例,不会在活动和服务之间处理?

我误解了吗?

来自try / catch块的EDIT logcat输出显示抛出的异常。 SaveHeartbeat方法存在于基本活动中:

protected void SaveHeartbeat(DateTime time, string sourceActivity, [CallerMemberName] string sourceEvent = "")
        {
            try
            {
                var heartbeat = new SmartWarehouse.Shared.Models.Heartbeat(sourceActivity,
                                                                            sourceEvent,
                                                                            this._session_state.CurrentSession.ROWID.ToString());

                this._database.InsertHeartbeat(heartbeat);
            }
            catch (Exception e)
            {
                // TODO: Document Exception
                Util.Tools.Bark(e);
            }
        }

Exception Logcat

编辑2 DatabaseHelper.InsertHeartbeat():

/// <summary>
/// Inserts a Heartbeat record into local DB.
/// </summary>
/// <param name="heartbeat"></param>
/// <returns></returns>
public long InsertHeartbeat(Heartbeat heartbeat)
{
    if (heartbeat == null) return -2L;
    using (var db = this.WritableDatabase)
    {
        var id = -3L;
        db.BeginTransactionNonExclusive();
        try
        {
            var cv = GetContentValues(heartbeat);
            id = db.Insert(DatabaseSchema.Heartbeat.TableName, null, cv);
            db.SetTransactionSuccessful();
        }
        catch (Exception e)
        {
            // TODO: Document Exception
            Util.Tools.Bark(e);
        }
        finally
        {
            db.EndTransaction();
        }
        return id;
    }
}

好吧所以我的理论是,当我在db语句中访问using()对象时,它正在处理DatabaseHelper对象使用的数据库。还注意到我没有使用db.InsertOrThrow()方法,我应该...在我的DatabaseHelper类上做一些重新工作,看看是否能解决问题。

c# android xamarin.android sqliteopenhelper
1个回答
0
投票

事实证明,我的DatbaseHelper的单例实例没有被处理掉。

实际上发生的事情是我正在处理SQLiteDatabase对象,这是DatbaseHelper在辅助方法中使用的。

实际解决问题所需要做的就是改变:

/// <summary>
/// Inserts a Heartbeat record into local DB.
/// </summary>
/// <param name="heartbeat"></param>
/// <returns></returns>
public long InsertHeartbeat(Heartbeat heartbeat)
{
    if (heartbeat == null) return -2L;
    // This using() statement is causing the disposal
    using (var db = this.WritableDatabase)
    {
        var id = -3L;
        db.BeginTransactionNonExclusive();
        try
        {
            var cv = GetContentValues(heartbeat);
            id = db.Insert(DatabaseSchema.Heartbeat.TableName, null, cv);
            db.SetTransactionSuccessful();
        }
        catch (Exception e)
        {
            // TODO: Document Exception
            Util.Tools.Bark(e);
        }
        finally
        {
            db.EndTransaction();
        }
        return id;
    }
}

至:

/// <summary>
/// Inserts a Heartbeat record into local DB.
/// </summary>
/// <param name="heartbeat"></param>
/// <returns></returns>
public long InsertHeartbeat(Heartbeat heartbeat)
{
    if (heartbeat == null) return -2L;

    // This is no longer initialized in a using() statement
    var db = this.WritableDatabase;

        var id = -3L;
        db.BeginTransactionNonExclusive();
        try
        {
            var cv = GetContentValues(heartbeat);
            id = db.Insert(DatabaseSchema.Heartbeat.TableName, null, cv);
            db.SetTransactionSuccessful();
        }
        catch (Exception e)
        {
            // TODO: Document Exception
            Util.Tools.Bark(e);
        }
        finally
        {
            db.EndTransaction();
        }
        return id;

}

摘要:

通过在我帮助方法中的SQLiteDatabase db语句中初始化我的using()对象,我正在处理我的SQLiteDatabase所需的DatabaseHelper

© www.soinside.com 2019 - 2024. All rights reserved.