2017-07-17 47 views
0

我想在Android Studio中讀取一個文件,並將每個字符串放入一個ArrayList中,但是當我嘗試從ArrayList中獲取該字符串時,應用程序崩潰(消息:「不幸的,應用程序已停止「)任何人都可以告訴我什麼是錯的?arraylist.get()在Android Studio中崩潰我的應用程序

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

問題是你不能直接從你的Windows系統在Android中讀取文件。 Android設備和Windows是完全不同的系統。儘管如此,您已將文件放在assets文件夾中,但無法讀取它,因爲路徑引​​用了Windows結構。

您的Android設備或模擬器無法讀取路徑:C:\\Users\\Admin...

要從assests訪問文件Android Studio中,你應該使用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

它進行了一些調整,非常感謝您的時間和建議 –