這裏是我的代碼第一:如何從EditText字段獲取值並將其存儲在雙變量中?
public class MainActivity extends AppCompatActivity
{
Spinner dropdown;
EditText e1; //user enters the bill amount before tip here
TextView tipped; //total tipped amount
TextView Bill; //the total amount of the bill including tax
String sdropdown;
double originalBill = 0; //amount that the user enters converted to a double
double result = 0; //result of multiplying bill and tax
String test1; //editText field has to be converted to a string value first
NumberFormat currencyFormat = NumberFormat.getCurrencyInstance(); //currency format object
//Create array of items
String tip [] = {"10%", "15%", "20%", "25%", "30%"};
//Create ArrayAdaptor
ArrayAdapter<String> adaptorTipAmount;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Create the element
dropdown = (Spinner) findViewById(R.id.tipAmount);
tipped = (TextView) findViewById(R.id.tipTotal);
Bill = (TextView) findViewById(R.id.billTotal);
e1 = (EditText) findViewById(R.id.billAmount);
tipped.setText(currencyFormat.format(0));
Bill.setText(currencyFormat.format(0));
//initialize and set adaptor
adaptorTipAmount = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, tip);
adaptorTipAmount.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
dropdown.setAdapter(adaptorTipAmount);
dropdown.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> adapter, View v,
int position, long id) {
// On selecting a spinner item
sdropdown = adapter.getItemAtPosition(position).toString();
//what editText field is initially stored in
test1 = e1.getText().toString();
//test1 string variable gets converted to a double
//originalBill = Double.parseDouble(test1);
//determines the tip amount and does the calculation based on the tip
/* if (sdropdown.equals("10%"))
{
result = originalBill * .10;
tipped.setText(Double.toString(result));
}
else if (sdropdown.equals("15%"))
{
result = originalBill * .15;
tipped.setText(Double.toString(result));
}
else if (sdropdown.equals("20%"))
{
result = originalBill * .20;
tipped.setText(Double.toString(result));
}
else if (sdropdown.equals("25%"))
{
result = originalBill * .25;
tipped.setText(Double.toString(result));
}
else if (sdropdown.equals("30%"))
{
result = originalBill * .30;
tipped.setText(Double.toString(result));
}
*/
tipped.setText("The tipped amount is: " + test1);
}
@Override
public void onNothingSelected(AdapterView<?> arg0)
{
// TODO Auto-generated method stub
}
});
}
}
我遇到的問題是,每當我試圖讓從的EditText字段中的值,並將其存儲在雙應用程序崩潰。我搜索瞭解決這個問題的方法,並且發現如果你先將字段存儲在一個字符串中,然後將其轉換爲一個可以工作的雙精度值,那麼它不會。我很確定這是我的錯誤,雖然我沒有想法如何解決。我也不想使用按鈕。任何幫助?由於
你能成爲一個更具體一點?在哪裏它崩潰,什麼是異常(如果有的話)。一般來說,我可以看到你做了很多findViewBy Id而沒有驗證結果。這是在尋求麻煩。將代碼包裝到try/catch塊中並檢查異常也有很大幫助。 –
這是崩潰的權利originalBill = parsedouble .... – Ryan
如果我發表評論,只是嘗試輸出test1這是一個字符串它會工作,但試圖輸出originalBill將無法正常工作 – Ryan