2013-07-08 56 views
2

我在我的应用程序中使用外部数据库,我想从数据库中获取最大报告代码(例如13-T005),并将其增加1.但是我一直在努力如何获得最后3位数字,因为我使用'int',它只能得到最后一位数字。我怎样才能得到报告代码的最后3位数字,而没有任何问题,或者更好的报告代码本身?谢谢。如何在Android中自动增加数据库中的代码?

在我MainActivity.java:

private void getNextReportCode() { 
     tv_Code = (TextView) findViewById(R.id.tv_Code); 
     String query = "SELECT SUBSTR(MAX(ReportCode),5) AS ReportCode FROM " + Constants.TABLE_REPORT; //getting the last 3 digits from the code 
     Cursor cursorReportCode = databaseHandler.getLastRCode(query); 
     int reportCode = cursorReportCode.getInt(cursorReportCode.getColumnIndex(Constants.REPORT_CODE)) +1; //increment by 1 
     String newReportCode = "13-T" + reportCode; 
     tv_Code.setText(newReportCode); 
} 

DatabaseHandler.java

public Cursor getLastRCode(String query) { 
     SQLiteDatabase db = this.getReadableDatabase(); 

     Cursor cursor = db.rawQuery(query, null); 
      if (cursor != null); 
      cursor.moveToFirst(); 

     db.close(); 
     return cursor; 
    } 
+0

考虑让'reportCode'一个'String',并使用'cursorReportCode.getString(...)'? – LuckyMe

+0

@LuckyMe我实际上做了这个解决方案,但是如何通过使用String来增加它? – androidBoomer

+0

似乎像其他人一样打我说明:) – LuckyMe

回答

1

此代码示例应该做你想做的。关键是提取您的报告索引使用子字符串,因为你提到它在最后3位数字。然后你可以解析和增加。回到你的报告代码需要一个字符串格式,它使用“%03d”来指定一个长度为3位的零填充整数。

public class Report { 

    public String incrementReportCode(String s) { 
     // Get last 3 characters 
     int length = s.length(); 
     String lastThreeChars = s.substring(length - 3, length); 

     // Parse report index 
     int reportIndex = Integer.parseInt(lastThreeChars); 

     // Increment report index 
     int incrementedReportIndex = reportIndex + 1; 

     // Format as report code, with a zero-filled report index for the last 3 characters 
     String reportCode = String.format("13-T%03d", incrementedReportIndex); 
     return reportCode; 
    } 

} 

下面是测试我这个做:

public void testIncrement() { 
    Report r = new Report(); 
    String incrementedString = r.incrementReportCode("13-T005"); 
    assertEquals("13-T006", incrementedString); 
} 
+0

如何使用上面的代码实现您的代码?我很难从数据库获取报告代码。 – androidBoomer

+1

我想你会得到你的报告代码:cursorReportCode.getColumnIndex(Constants.REPORT_CODE)。也许你可以将它分配给一个String类型:String reportCode = cursorReportCode.getString(cursorReportCode.getColumnIndex(Constants.REPORT_CODE));然后,您可以使用此代码片段获取递增的报告代码:new Report()。incrementReportCode(reportCode); – louielouie

1

每LuckyMe的在评论中建议,你可能想用一个字符串。

从那里你的问题变成:How do I increment the String?这似乎相当于要求How do I increment the number at the end of the String?。 (纠正我,如果我错了?)

这里的关键是,你知道你的字符串将遵循特定模式;特别是[number1]-T[number2],您有兴趣number2

您可能需要的工具是Regular Expressions。幸运的是,Java提供了一个API和一个tutorial。要点是:您呈现您的字符串将遵循的模式,而正则表达式(又名正则表达式)可让您捕获它的特定部分。

希望让你走上正轨!

编辑:具体来说,这里是the Android documentation on regex

+0

注意。感谢@ mfrankli – androidBoomer

相关问题