2011-03-17 66 views
0

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(); 
     } 
    } 
} 
+0

你是否正在寫入文件? – 2011-03-17 15:09:39

+0

是的,我會在第一篇文章中添加WriteSettings方法。 – androniennn 2011-03-17 15:13:31

回答

0

如何將代碼段被調用?什麼是value1/value2?如果這是單擊事件,則可能是第一次單擊時value1或value2爲空值,從而阻止更改任何設置。

+0

我認爲它是一個監聽器的onClick事件的內部,因爲他有});在底部,但他沒有看到頂部。 – FoamyGuy 2011-03-17 15:07:15

+0

@DMags,@Tim:我用整個功能編輯了我的第一篇文章!謝謝你試圖幫助我:)。 – androniennn 2011-03-17 15:10:14

+0

不客氣:)你確定你應該在GetText()之後使用toString()函數作爲value1/value2嗎?我相信這是爲了獲取類名,而不是轉換爲字符串類型(儘管如果函數被重載,我可能是錯的)。另外,vol和kil的值是多少? – DMags 2011-03-17 15:13:09