我收到一个错误:打开跟踪文件时出错:没有这样的文件或目录 java.net.malformedURLexception:找不到协议:cars.xml
我想在内部存储中创建一个 xml 文件并在列表视图中显示 car_name 和 car_model。
我的代码:
public class MainActivity extends Activity {
ListView listView;
Button createCar;
String XML_CONTENT = "<?xml version=\"1.0\" encoding=\"utf-8\"?><cars><car><carMake></carMake><carModel></carModel><fuelType></fuelType><carYear></carYear><carColor></carColor><engineHp></engineHp><engineCcm></engineCcm></car></cars>";
static String myXML = "cars.xml";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String[] myCars = null;
fileCreate();
ParseXML parseXML= new ParseXML();
myCars = parseXML.giveCars(myXML);
listView = (ListView) findViewById(R.id.listView1);
if (myCars.length == 0 || myCars == null)
Toast.makeText(this, "Your car list is empty. Please create a new car!", 8000).show();
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.list_view_row, R.id.textView1, myCars);
listView.setAdapter(adapter);
}
}
private void fileCreate() {
try {
FileOutputStream os = openFileOutput(myXML, MODE_PRIVATE);
os.write(XML_CONTENT.getBytes());
os.close();
Toast.makeText(MainActivity.this, "created", Toast.LENGTH_LONG).show();
} catch (Exception e) {
Toast.makeText(MainActivity.this, "NON created", Toast.LENGTH_LONG).show();
Log.i("ReadNWrite, fileCreate()", "Exception e = " + e);
}
}
giveCars 函数:
public String[] giveCars(String cars) {
try {
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
Document doc = docBuilder.parse(cars);
String[] carsInFile = null;
NodeList myCars = doc.getElementsByTagName("car");
Node myCar;
NodeList spec;
for (int i = 0; i < myCars.getLength(); i++) {
myCar = myCars.item(i);
spec = myCar.getChildNodes();
carsInFile[i] = spec.item(0).toString() + " "
+ spec.item(1).toString();
}
return carsInFile;
} catch (Exception e) {
android.util.Log.e("tag", "", e);
}
return null;
}
如果在一个简单的 java 项目中运行这个函数,一切正常。