[英]How to convert String taken from a TextField view to an int
我在布局中有一個TextField
,我想檢索它並將其轉換為整數以放入數據庫中。 我使用了以下代碼,但是它一直給我一些例外
EditText agefield = (EditText) findViewById(R.id.agefield);
int age = Integer.parseInt(agefield.getText().toString());
如果Java這行
int age = Integer.parseInt(agefield.getText().toString());
可以重寫為
int age = Integer.parseInt(agefield.getText());
嗨,要在android中實現; 您的確切問題已在此處回答。
另外,我建議您仔細檢查一下是否已針對相關活動調用了setContentView(R.layout.main),即在嘗試調用EditText agefield =之前,確保已將包含agefield edittext的xml文件設置為contentview。 (EditText)findViewById(R.id.agefield)。 如果還沒有,則您將獲得一個空指針,因為您的edittext字段將為空。 確認后,請確保edittext中的值是有效數字並且不為空。
我認為setContentView是問題,因為我最近有類似的經歷。
如果此回答您的問題,請隨意將其標記為答案。 希望這有幫助,祝你好運!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.