2014-10-19 77 views
0

每當我嘗試運行我的應用程序時,LogCat中都會顯示一個錯誤。這是我在MainActivity.javaE/AndroidRuntime:致命例外:main

package com.practice.bludworth.practiceapp; 

import android.app.Activity; 
import android.os.Bundle; 
import android.view.Menu; 
import android.view.MenuItem; 
import android.widget.EditText; 


public class MainActivity extends Activity { 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 

    EditText ageInput = (EditText) findViewById(R.id.ageReceived); 
    int input = Integer.parseInt(ageInput.getText().toString()); 

} 


@Override 
public boolean onCreateOptionsMenu(Menu menu) { 
    // Inflate the menu; this adds items to the action bar if it is present. 
    getMenuInflater().inflate(R.menu.main, menu); 
    return true; 
} 

@Override 
public boolean onOptionsItemSelected(MenuItem item) { 
    // Handle action bar item clicks here. The action bar will 
    // automatically handle clicks on the Home/Up button, so long 
    // as you specify a parent activity in AndroidManifest.xml. 
    int id = item.getItemId(); 
    if (id == R.id.action_settings) { 
     return true; 
    } 
    return super.onOptionsItemSelected(item); 
    } 
} 

代碼logcat的錯誤說這是:

Caused by: java.lang.NumberFormatException: Invalid int: "" 

很困惑,因爲我一般是新的節目。謝謝

回答

0

問題是,你試圖解析一個整數在應用程序的開始,因爲onCreate是運行你的EditText字段沒有價值的第一種方法。

import android.app.Activity; 
import android.os.Bundle; 
import android.util.Log; 
import android.view.View; 
import android.widget.Button; 
import android.widget.EditText; 

public class MyActivity extends Activity implements View.OnClickListener 
{ 
    private EditText ageInput; 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 

     // A button on your xml layout 
     Button button = (Button) findViewById(R.id.button); 

     // set the on click listener to this class, notice that MyActivity implements View.OnClickListener 
     button.setOnClickListener(this); 

     // This retrieves the EditText control 
     ageInput = (EditText) findViewById(R.id.ageReceived); 
    } 

    // This method is called when your button is clicked. 

    @Override 
    public void onClick(View v) 
    { 


     // Switch cases are equivalent to if statements 
     switch (v.getId()) 
     { 
      // if your button was clicked. 
      case R.id.button: 
       // get the input 
       int input = Integer.parseInt(ageInput.getText().toString()); 

       // Print the input to the console 
       Log.d("DEBUG_TAG", String.valueOf(input)); 
       break; 

     } 
    } 
} 
+0

有意義。那麼我應該把這個代碼放在哪裏?對不起,這很新鮮。謝謝 – user3808555 2014-10-19 00:40:35

相關問題