Have to tap 2 times in a button to have a result
public void calcul () { final EditText vol; final EditText kil; final EditText cons; context = getApplicationContext(); vol = (EditText) findViewById(R.id.volume2); kil= (EditText) findViewById(R.id.kilometrage2); cons= (EditText) findViewById(R.id.consom2);
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*/)
{
开发者_StackOverflow 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 method:
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();
}
}
}
How is the snippet of code being called? What are value1/value2? If this is the on click event, it's possible that value1 or value2 are null values on the first click, preventing any settings from being changed.
精彩评论