ArrayList
为空,现在我正在按照您的建议更新代码,但出现了一个新错误:
private HashMap<String, String> wordList;
private ArrayList<String> hashWordArray;
private void readFile() {
Scanner scanner = new Scanner(getResources().openRawResource(R.raw.wordsdata));
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
String[] parts = line.split("/t");
wordList.put(parts[0], parts[1]);
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
readFile();
hashWordArray = new ArrayList<String>(wordList.keySet());
ListView listView = (ListView) findViewById(R.id.listitem);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,hashWordArray);
listView.setAdapter(adapter);
}
}
这是显示的错误:
Process: com.example.archit.dictionarytwo, PID: 17915
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.archit.dictionarytwo/com.example.archit.dictionarytwo.MainActivity}: java.lang.ArrayIndexOutOfBoundsException: length=1; index=1
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2778)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2856)
at android.app.ActivityThread.-wrap11(Unknown Source:0)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1589)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6494)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:440)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)
Caused by: java.lang.ArrayIndexOutOfBoundsException: length=1; index=1
at com.example.archit.dictionarytwo.MainActivity.readFile(MainActivity.java:23)
at com.example.archit.dictionarytwo.MainActivity.onCreate(MainActivity.java:32)
at android.app.Activity.performCreate(Activity.java:7009)
at android.app.Activity.performCreate(Activity.java:7000)
应用程序已终止。
实际上,你认为你在readFile()
中初始化了hashWordArrayArrayList
,但你从来没有调用readFile()
。
当你写 :
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,hashWordArray);
hashWordArrayArrayList
从未初始化过。
因此onCreate
方法更改为:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
readFile();
ListView listView = (ListView) findViewById(R.id.listitem);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,hashWordArray);
listView.setAdapter(adapter);
}
如果您可以共享完整的日志,那就太好了。我在你的代码中发现的一个错误是 HashMap.在初始化 HashMap 后添加此语句:
private HashMap<String,String> wordList;
wordList = new HashMap<>();
你能试试这个吗?
'