Java 无法访问的代码-更新现有行

Java 无法访问的代码-更新现有行,java,unreachable-code,Java,Unreachable Code,在下面的代码中,db.setTransactionSuccessful();给出无法访问的错误代码。谁能告诉我怎么解决这个问题吗 public boolean updateDiaryEntry(String title, long rowId) { ContentValues newValue = new ContentValues(); newValue.put(Constants.TITLE_NAME, title);

在下面的代码中,db.setTransactionSuccessful();给出无法访问的错误代码。谁能告诉我怎么解决这个问题吗

public boolean updateDiaryEntry(String title, long rowId)
        {

            ContentValues newValue = new ContentValues();
            newValue.put(Constants.TITLE_NAME, title);

            db.beginTransaction();


            return db.update(Constants.TABLE_NAME , newValue , Constants.KEY_ID + "= ?" , 
                new String[]{ Double.valueOf(rowId).toString() })>0;

            db.setTransactionSuccessful();
            db.endTransaction();    

        }

您正在返回将退出函数的那一行之前的那一行。

从函数返回后有两行代码,这些代码将永远不会执行,因为您已经离开了函数。这就是为什么您会收到无法访问的代码消息。您不希望在return语句之后有代码行:

return db.update(Constants.TABLE_NAME , newValue , Constants.KEY_ID + "= ?" , 
            new String[]{ Double.valueOf(rowId).toString() })>0;   //returned from function on this line

db.setTransactionSuccessful(); //therefore you never get to this line
db.endTransaction();  
相反,您可能希望执行以下操作:

db_result = db.update(Constants.TABLE_NAME , newValue , Constants.KEY_ID + "= ?" , 
            new String[]{ Double.valueOf(rowId).toString() })>0;

if(db_result){
     db.setTransactionSuccessful(); //Now you can do this conditional on the result of the update
}
db.endTransaction();
return db_result;

通过创建一个变量来存储更新数据库的结果,您可以在从函数返回之前执行与数据库相关的清理/关闭函数。

从函数返回后有两行代码,这些代码将永远不会执行,因为您已经离开了函数。这就是为什么您会收到无法访问的代码消息。