E / AndroidRuntime:致命异常:主要

时间:2014-10-19 00:31:36

标签: java android runtime logcat

每当我尝试运行我的应用程序时,LogCat中都会显示错误。这是我在MainActivity.java中的代码

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: ""

非常困惑,因为我是一般的编程新手。感谢

1 个答案:

答案 0 :(得分:0)

问题是你试图在应用程序的开头解析一个Integer,因为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;

         }
    }
}