2014-10-19 73 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

相关问题