動的に作成された EditText から取得した値をファイルに書き込もうとしています。EditText は配列リストにあり、それらの値を取得して文字列 [] に入れます。次に、これらの値を次のようなファイルに入れる必要があります。
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));
}
}
問題は、2回宣言することでしょうか? メソッドの外側に一度、内側に?しかし、内部で宣言しないとクラッシュします。理由を教えてもらえますか?