2013-07-08 54 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

相關問題