2016-10-31 13 views
1

CSVファイルのデータをリストに追加しようとしています。現時点で私はこのコードを持っていますが、アプリケーションを実行しようとするとアプリケーションは終了します。CSVファイルをアンドロイドで読み込んでハッシュマップに入れる

private HashMap<String, GeoLocation> loadLocationData() { 
    String csvFile = "C:\\Users\\MyName\\Documents\\MyApplication\\app\\src\\main\\res\\raw\\geo_locations.csv"; 
    String line = ""; 
    String cvsSplitBy = ","; 

    try (BufferedReader br = new BufferedReader(new FileReader(csvFile))) { 

     while ((line = br.readLine()) != null) { 
      String[] cityloc = line.split(cvsSplitBy); 
      locations.put(cityloc[0], new GeoLocation(cityloc[0], Double.parseDouble(cityloc[1]), Double.parseDouble(cityloc[2]), TimeZone.getTimeZone(cityloc[3]))); 
     } 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } 

    return locations; 
} 

私はすでにCSVファイルの読み込みについて尋ねてきたし、その上に他の質問のリストを与えられた、しかし、それに取り組んで後に私はここに私の問題を解決することができていません。

私がしなければならないことの基本的な要点は、CSVファイルからそのリストを取得し、そこから「場所」に追加できるリストを作成することです。

+0

可能性の重複取得と解析アンドロイドのCSVファイル](http://stackoverflow.com/questions/5360628/get-and-parse-csv-file-in-android)...私は 'C:'がAndroidデバイス。 –

+0

CSVの形式が正しくないとどうなりますか?あなたはすべてのargsを空にしていません(空行)? DoubleまたはTimeZoneの形式が間違っていますか?それを処理するためにあなたのfuctionは保存されていますか? –

+0

あなたのAndroidデバイス/エミュレータにはC:ドライブがありません。 –

答えて

0

この形式(引用エスケープなど)の周囲にコーナーケースが多数あるため、CSVを手作業で解析しないでください。 univocity-parsersを使ってください。うまくいくはずです。

このコードを試してみてください。

CsvParserSettings config = new CsvParserSettings(); 
    //configure what you need by hand, or just do this: 
    config.detectFormatAutomatically(); 

    CsvRoutines csv = new CsvRoutines(config); 

    File input = new File("C:\\Users\\MyName\\Documents\\MyApplication\\app\\src\\main\\res\\raw\\geo_locations.csv"); 

    Map<String, GeoLocation> locations = new LinkedHashMap<String, GeoLocation>(); 
    for(GeoLocation geo : csv.iterate(GeoLocation.class, input)){ 
     locations.put(geo.city, geo); 
    } 

マイGeoLocation実装:

@Fildorとしてあなたのファイルパスが言っ
public class GeoLocation{ 
    @Parsed(index = 0) 
    String city; 
    @Parsed(index = 1) 
    Double longitude; 
    @Parsed(index = 2) 
    Double latitude; 
    @Parsed(index = 3) 
    TimeZone timeZone; 

    public void setTimeZone(String timeZone){ 
     this.timeZone = TimeZone.getTimeZone(timeZone); 
    } 
} 
0

変更、例えば "資産" [の

関連する問題