我正在尝试将从一些动态创建的 EditTexts 中获得的一些值写入文件。EditTexts 在一个数组列表中,我获取它们的值并将它们放在一个字符串 [] 中。然后我需要将这些值放在这样的文件中:
product[1] : quantity[1] : price[1]
product[2] : quantity[2] : price[2]
......
product[n] : quantity[n] : price[n]
我试过这个:
private void writeToSDFile(){
File root = android.os.Environment.getExternalStorageDirectory();
totalc.append("\nExternal file system root: "+root);
File dir = new File (root.getAbsolutePath() + "/download");
dir.mkdirs();
File file = new File(dir, "myData.txt");
try {
FileOutputStream f = new FileOutputStream(file);
PrintWriter pw = new PrintWriter(f);
pw.write("Total : ");
pw.println(totaltest + price[1]);
pw.flush();
pw.close();
f.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
Log.i(TAG, "******* File not found. Did you" +
" add a WRITE_EXTERNAL_STORAGE permission to the manifest?");
} catch (IOException e) {
e.printStackTrace();
}
totalc.append("\n\nFile written to "+file);
}
我尝试输入 price[1],以测试它是否有效,但无效。它在 LogCat 中给了我以下错误:
06-13 21:23:43.525: E/AndroidRuntime(25345): FATAL EXCEPTION: main
06-13 21:23:43.525: E/AndroidRuntime(25345): java.lang.ArrayIndexOutOfBoundsException: length=0; index=1
06-13 21:23:43.525: E/AndroidRuntime(25345): at com.example.testlayout.MainActivity.writeToSDFile(MainActivity.java:89)
所以 ?如何将这些值发送到我的文件?谢谢 !
编辑:这是我声明数组的位置和方式:
private String[] cant = new String[allcant.size()];
private String[] pret = new String[allpret.size()];
private String[] prod = new String[allpret.size()];
public void calculeaza() {
totaltest = 0;
String[] prod = new String[allprod.size()];
for (int m = 0; m < allprod.size(); m++) {
prod[m] = allcant.get(m).getText().toString();
if (prod[m].matches("")) {
// Toast.makeText(this,
// "Ati omis cantitatea de pe pozitia " + (m + 1),
// Toast.LENGTH_SHORT).show();
prod[m] = Float.toString(0);
}
}
String[] cant = new String[allcant.size()];
for (int j = 0; j < allcant.size(); j++) {
cant[j] = allcant.get(j).getText().toString();
if (cant[j].matches("")) {
// Toast.makeText(this,
// "Ati omis cantitatea de pe pozitia " + (j + 1),
// Toast.LENGTH_SHORT).show();
cant[j] = Float.toString(0);
}
}
String[] pret = new String[allpret.size()];
for (int k = 0; k < allpret.size(); k++) {
pret[k] = allpret.get(k).getText().toString();
if (pret[k].matches("")) {
//Toast.makeText(this,
// "Ati omis pretul de pe pozitia " + (k + 1),
// Toast.LENGTH_SHORT).show();
pret[k] = Float.toString(0);
}
}
for (int l = 0; l < allpret.size(); l++) {
Float temp = Float.parseFloat(cant[l]) * Float.parseFloat(pret[l]);
alltotal.add(temp);
totaltest = totaltest + temp;
TextView totalf = (TextView) findViewById(R.id.total);
totalf.setText(String.format("Total: %.2f", totaltest));
}
}
问题可能是我声明了两次?一次在方法外面,一次在里面?但是如果我不在里面声明它,它就会崩溃。谁能告诉我为什么?