Android Studio中的空指针异常

时间:2015-03-28 20:56:47

标签: java android nullpointerexception

这里的Android新手。看看其他答案,但仍然无法弄清楚出了什么问题...希望能在这里得到一些帮助。 :)

Android Studio说第28行有一个空对象引用,即login.setOnClick ...行。

再次,对不起,如果这段代码很乱,我有点啰嗦!

提前致谢!

public class LoginScreen extends ActionBarActivity {

    // EditText mEdit;
    // TextView mText;

    private static String artist = "Artist";

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

        Button login = (Button) findViewById(R.id.button1);
        final EditText user = (EditText) findViewById(R.id.userName);

        login.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                // mText = (TextView)findViewById(R.id.welcome);
                // mText.setText("Welcome "+mEdit.getText().toString()+"!");

                artist = user.getText().toString();

                Intent intent = new Intent(getApplicationContext(), SongSelection.class);
                startActivity(intent);
            }
        });
    }

    public static String getArtist(){
        return artist;
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_login_screen, 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();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}

1 个答案:

答案 0 :(得分:0)

如果findViewById()缺少已传递ID的视图,则

Activity方法返回null。检查您的布局activity_login_screen是否包含ID为button1

的视图