2011-08-29 112 views
0

解析CSV文件時出現問題。只有2行數據用逗號分隔。第一行是日期,第二行是一個值。日期字段將始終具有日期,但有時該值爲空(或空值?)。當它達到空值時,我得到一個StringIndexOutOfBoundsException並且應用程序崩潰。我記錄每個循環,並可以看到數據,但一旦我得到一個空值,它會停止循環並給出錯誤。如果沒有空值,那麼它完美。這裏是我的代碼:Android CSV解析器問題

 BufferedReader buf = new BufferedReader(new StringReader(file)); 
     String line = null; 
     while ((line = buf.readLine()) != null) { 
      try { 
       String date = null, value = null; 
       String[] RowData = line.split(","); 
       date = RowData[0]; 
       value = RowData[1]; (this is the row it crashes on) 

這是CSV的樣子:

2011-08-28 09:16,8.23

2011-08-28 09:15,8.24

2011-08-28 09:14,8.26

2011-08-28 09:13,8.34

2011-08-28 09:12,

2011-08-28 09:11,10.72

2011-08-28 9時10,

2011-08-28 09:09,

在9點13的值是我在得到錯誤之前在logcat中的最後一件事。

這個固定:

   if(RowData.length == 2) { 
        date = RowData[0]; 
        value = RowData[1]; 
       } else { 
        date = RowData[0]; 
        value = "0"; 
       } 

我在值字段所以後來的過程不會對空值嗆寫了一個0。感謝您的幫助!

回答

2

你想這樣做或類似的東西:

String date = null, value = null; 
String[] RowData = line.split(","); 
date = RowData[0]; 

if(RowData.length ==2)value = RowData[1]; (this is the row it crashes on) 

或者例如它的一些變化如果(RowData.length < 2)不嘗試讀取值。它是一個非常標準的東西 - 如果你問一個數組的索引值,它沒有Java會崩潰。

+0

我試過各種變化,它仍然崩潰。我試過的東西像if(RowData.length <2){value =「0」;} else {value = RowData [1];}像往常一樣,我可能錯過了一些簡單的哈哈。 – Opy

+0

我不得不在日期之前放置if語句= RowData [0];謝謝! – Opy

0

你試過先檢查

if (RowData[1]!=null) or possibly if (RowData[1]!="") 

我不明白爲什麼會導致您的應用程序崩潰,雖然, 它應該只是設定值null""

+0

謝謝,我已經修復它,但它崩潰了,因爲導致它實際崩潰的應用程序部分不會接受空字符串。 – Opy

1

檢查的長度RowData在嘗試訪問它之前。它看起來像split()返回一個數組與一個單一的對象,但你試圖訪問第二個對象,這確實超出了界限。

+0

我更新了上面的問題,以包含導致崩潰的CSV文件的部分。該行不是null,但有時是第二個對象。我已經嘗試了與if語句一起檢查null的不同變體,但它總是在逗號後面沒有任何變體。 – Opy

2

爲什麼編寫自己的CSV解析,當你可以使用已經寫好的庫,它會爲你做?或許OpenCSV將幫助您實現CSV解析目標。

+0

因爲我不想要一個完整的庫,只需幾行代碼即可完成我所需的工作。我只是不能讓它跳過空值。 – Opy

+1

使用ProGuard在編譯時去除任何未使用的類。 – CrackerJack9

+0

我使用簡單的if語句修復了它。我只是不確定要檢查什麼。我正在檢查我試圖設置的字符串,而不是整個RowData。無論如何感謝您的建議。當我第一次編寫代碼時,我已經考慮了一段時間,但是我決定在第一個空字段後殺死循環並將現有數據轉儲到數據庫。我終於回到了它,現在它已經修復:) – Opy

1
public class CityParser { 
    DocumentBuilderFactory factory; 
    DocumentBuilder builder; 
    Document doc; 

    Element ele; 

    int mediaThumbnailCount;`enter code here` 
    boolean urlflag; 
    CityListBean objBean = null; 

    Vector<CityListBean> vecCityList; 

    public CityParser() { 

    } 

    public Vector<CityListBean> getCityData() { 

     vecCityList = new Vector<CityListBean>(); 
     try { 
      HttpClient httpClient = new DefaultHttpClient(); 
      HttpContext localContext = new BasicHttpContext(); 
      HttpGet httpGet = new HttpGet(
        "http://heresmyparty.com/cms/index.php?option=com_chronocontact&chronoformname=add_event_form_download"); 
      HttpResponse response = httpClient.execute(httpGet, localContext); 
      // String result = ""; 

      BufferedReader reader = new BufferedReader(new InputStreamReader(
        response.getEntity().getContent())); 

      CSVReader csvreader = new CSVReader(reader); 
      String[] nextLine; 
      while ((nextLine = csvreader.readNext()) != null) { 

       CityListBean objcitylist = new CityListBean(); 
       // nextLine[] is an array of values from the line 
       objcitylist.setText_title(nextLine[5]); 
       objcitylist.setText_host(nextLine[6]); 
       objcitylist.setText_price(nextLine[7]); 
       objcitylist.setDate(nextLine[8]); 
       objcitylist.setText_venue(nextLine[11]); 
       objcitylist.setAddress(nextLine[12]); 
       objcitylist.setLatitude(nextLine[13]); 
       objcitylist.setLongitude(nextLine[14]); 
       objcitylist.setFile(nextLine[15]); 
       objcitylist.setText_description(nextLine[16]); 
       objcitylist.setCity(nextLine[17]); 
       vecCityList.addElement(objcitylist); 

      } 


       /*for (int i = 0; i < vecCityList.size(); i++) { CityListBean 
       objcity = (CityListBean) vecCityList.get(i); 

       System.out.println("Cf_id : " + objcity.getCityName()); 
       System.out.println("-----------------------------------"); }*/ 


     } catch (Exception ex) { 
      ex.printStackTrace(); 
     } 

     return vecCityList; 
    } 
} 

========================================================================================== 

public class CSVReader { 

    private BufferedReader br; 

    private boolean hasNext = true; 

    private char separator; 

    private char quotechar; 

    private int skipLines; 

    private boolean linesSkiped; 


    public static final char DEFAULT_SEPARATOR = ','; 

    public static final char DEFAULT_QUOTE_CHARACTER = '"'; 

    public static final int DEFAULT_SKIP_LINES = 0; 

    public CSVReader(Reader reader) { 
     this(reader, DEFAULT_SEPARATOR, DEFAULT_QUOTE_CHARACTER, 
      DEFAULT_SKIP_LINES); 
    } 

    public CSVReader(Reader reader, char separator, char quotechar, int line) { 
     this.br = new BufferedReader(reader); 
     this.separator = separator; 
     this.quotechar = quotechar; 
     this.skipLines = line; 
    } 

    public String[] readNext() throws IOException { 

     String nextLine = getNextLine(); 
     return hasNext ? parseLine(nextLine) : null; 
    } 

    private String getNextLine() throws IOException { 
     if (!this.linesSkiped) { 
      for (int i = 0; i < skipLines; i++) { 
       br.readLine(); 
      } 
      this.linesSkiped = true; 
     } 
     String nextLine = br.readLine(); 
     if (nextLine == null) { 
      hasNext = false; 
     } 
     return hasNext ? nextLine : null; 
    } 

    private String[] parseLine(String nextLine) throws IOException { 

     if (nextLine == null) { 
      return null; 
     } 

     List<String> tokensOnThisLine = new ArrayList<String>(); 
     StringBuffer sb = new StringBuffer(); 
     boolean inQuotes = false; 
     do { 
       if (inQuotes) { 
       // continuing a quoted section, reappend newline 
       sb.append("\n"); 
       nextLine = getNextLine(); 
       if (nextLine == null) 
        break; 
      } 
      for (int i = 0; i < nextLine.length(); i++) { 

       char c = nextLine.charAt(i); 
       if (c == quotechar) { 
         // this gets complex... the quote may end a quoted block, or escape another quote. 
         // do a 1-char lookahead: 
         if(inQuotes // we are in quotes, therefore there can be escaped quotes in here. 
          && nextLine.length() > (i+1) // there is indeed another character to check. 
          && nextLine.charAt(i+1) == quotechar){ // ..and that char. is a quote also. 
           // we have two quote chars in a row == one quote char, so consume them both and 
           // put one on the token. we do *not* exit the quoted text. 
           sb.append(nextLine.charAt(i+1)); 
           i++; 
         }else{ 
           inQuotes = !inQuotes; 
           // the tricky case of an embedded quote in the middle: a,bc"d"ef,g 
           if(i>2 //not on the begining of the line 
               && nextLine.charAt(i-1) != this.separator //not at the begining of an escape sequence 
               && nextLine.length()>(i+1) && 
               nextLine.charAt(i+1) != this.separator //not at the  end of an escape sequence 
           ){ 
             sb.append(c); 
           } 
         } 
       } else if (c == separator && !inQuotes) { 
        tokensOnThisLine.add(sb.toString()); 
        sb = new StringBuffer(); // start work on next token 
       } else { 
        sb.append(c); 
       } 
      } 
     } while (inQuotes); 
     tokensOnThisLine.add(sb.toString()); 
     return (String[]) tokensOnThisLine.toArray(new String[0]); 

    } 

    public void close() throws IOException{ 
     br.close(); 
    } 

} 
+0

謝謝,這幫了我很多! –