2017-07-17 8 views
0

Androidスタジオでファイルを読み込み、各文字列をarraylistに配置しようとしていますが、arraylistから文字列を取得しようとするとアプリがクラッシュします(メッセージ:「残念なことに、App停止しました ")誰かが何が間違っているか教えていただけますか?arraylist.get()がAndroidスタジオで自分のアプリをクラッシュする

protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 


//////////////////////////////////////////////////////////////////////////// 
    String text = ""; 

    tv_view = (TextView) findViewById(R.id.textview1); 

    Scanner s = new Scanner(System.in); 

    File n = new File("C:\\Users\\Admin\\AndroidStudioProjects\\LOTOS.1\\app\\src\\main\\assets\\nouns.txt"); 

    //Instantiate Scanner s with f variable within parameters 
    //surround with try and catch to see whether the file was read or not 
    try { 
     s = new Scanner(n); 
    } catch (FileNotFoundException e) { 

     e.printStackTrace(); 
    } 

    //Instantiate a new ArrayList of String type 
    ArrayList<String> theWord = new ArrayList<String>(); 


    //while it has next .. 
    while(s.hasNext()){ 
     //Initialise str with word read 
     String str=s.next(); 

     //add to ArrayList 
     theWord.add(str); 

    } 

    text = theWord.get(150); 

    tv_view.setText(text); 
    //return ArrayList 


} 
+0

これはEclipseでうまく動作します –

+0

@ShaishavJogani問題は、イベントログにエラーがなくコンパイルされていることです。しかし、アプリケーションがクラッシュする –

+0

クラッシュした場合、間違いなく間違いがあります。 –

答えて

0

問題AndroidのWindowsシステムからファイルを直接読み取ることはできません。 AndroidデバイスとWindowsはまったく別のシステムです。ファイルがassetsフォルダに置かれていても、そのパスがWindows構造を参照しているため、ファイルを読み取ることはできません。

あなたのAndroidデバイスまたはエミュレーターがこのパス読むことができません:AndroidのメーカーにごassestsからファイルにアクセスするにはC:\\Users\\Admin...

を、あなたはgetAssets().open(...)メソッドを使用する必要があります。

以下は、ファイルを読む方法の例です。

BufferedReader reader = null; 
reader = new BufferedReader(
     new InputStreamReader(getAssets().open("nouns.txt"), "UTF-8")); 

// do reading, usually loop until end of file reading 
String mLine; 
while ((mLine = reader.readLine()) != null) { 
     //process 
     ... 
} 
+0

ありがとう、私はそれを試みます –

+0

私はしましたが、私は15未満の評判を持っているので、それは公開されていませんが、記録されています。もう一度ありがとう –

+1

それはいくつかの調整で働いて、あなたの時間と提案にとても感謝します –

関連する問題