好的,所以我试图从对象的链接列表中填充 android 中的列表视图。我正在从文本文件中读取行,从文本文件的每一行中拆分出两个值,用“,”分隔,将这些值中的每一个存储到对象的链接列表中。然后我拉出每个对象的名称字段来填充列表视图。我知道这很草率我刚开始使用 Android :E 它现在根本不会运行,但代码中没有错误。
这是我的 activity.java 文件
package com.pkuCalc.pkuCalc;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import android.app.Activity;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.os.Bundle;
public class PkuCalcActivity extends Activity {
private ListView lv;
List<Food> foodlist = new LinkedList<Food>();
int numFoodItems = 0;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
lv = (ListView) findViewById(R.id.listView1);
try{
InputStream inputStream = getResources().openRawResource(R.raw.food);
if (inputStream != null) {
InputStreamReader inputreader = new InputStreamReader(inputStream);
BufferedReader r = new BufferedReader(inputreader);
String strLine;
while (( strLine = r.readLine()) != null) {
int z = 0;
int length = strLine.length();
int ind = strLine.indexOf( ',' );
String name = "";
for (int i = 0; i < ind; i++) {
name = name + strLine.charAt(i);
}
String sphe = "";
for (int i = ind + 2; i < length; i++) {
sphe = sphe + strLine.charAt(i);
}
int phe = Integer.parseInt(sphe);
Food newFood = new Food(name, phe);
foodlist.add(newFood);
numFoodItems = z;
z++;
}
}
inputStream.close();
} catch (IOException e){ //Catch exception if any
e.printStackTrace();
}
ArrayList<String> values = new ArrayList<String>();
for (int i = 0; i <= numFoodItems; i++) {
values.add((foodlist.get(i)).getName());
}
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, values);
lv.setAdapter(arrayAdapter);
setContentView(R.layout.main);
}
}