public void calcul() FinalEditText vol; final EditText kil; final EditText缺点; context = getApplicationContext(); vol =(EditText)findViewById(R.id.volume2); kil =(EditText)findViewById(R.id.kilometrage2); cons =(EditText)findViewById(R.id.consom2);必须在按钮中点击2次以获得结果
final Button button = (Button) findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
String value1 = vol.getText().toString();
String value2 = kil.getText().toString();
if (value1 != null && /*value1.trim().length() > 0 &&*/ value2 != null /*&& value2.trim().length() > 0*/)
{
float q1=Float.parseFloat(vol.getText().toString());
float q2=Float.parseFloat(kil.getText().toString());
float x=((q1/q2)* 100);
String y= Float.toString(x);
cons.setText(y);
SimpleDateFormat format = new SimpleDateFormat("dd/MM");
String date = format.format(new Date());
data = date + " : " + y + "L/100KM"+ " " + value1 + "L "+ value2 + "KM\n";
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
if (data != "") {
String fileName = getResources().getString(R.string.fileName);
String fileDir = ""+ preferences.getString("login", "") + "."+ preferences.getString("marque", "") + ".";
myIO.WriteSettings(context, fileDir + fileName, data);
data = "";
Toast.makeText(carburant.this, "Donnée ajoutée!", Toast.LENGTH_SHORT).show();
}
}
else
{
Toast.makeText(carburant.this, "Veuillez vérifier les deux champs", Toast.LENGTH_SHORT).show();
}
}
});
WriteSettings方法:
public class myIO {
public static void WriteSettings(Context context, String nom, String data) {
FileOutputStream fOut = null;
OutputStreamWriter osw = null;
try {
fOut = context.openFileOutput(nom, Context.MODE_APPEND);
osw = new OutputStreamWriter(fOut);
osw.write(data);
osw.flush();
osw.close();
fOut.close();
} catch (Exception e) {
Toast.makeText(context, "Echec", Toast.LENGTH_SHORT).show();
} finally {
try {
osw.close();
fOut.close();
} catch (IOException e) {
Toast.makeText(context, "Echec", Toast.LENGTH_SHORT).show();
}
}
}
你是否正在写入文件? – 2011-03-17 15:09:39
是的,我会在第一篇文章中添加WriteSettings方法。 – androniennn 2011-03-17 15:13:31