繁体   English   中英

Android studio:发生错误

[英]Android studio: An error has occured

我正在编写一个 android 应用程序。 但是,只要我想在模拟器中测试我的应用程序,就会立即出现错误。

这是我的代码。

public class MainActivity extends Activity implements View.OnClickListener {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    requestWindowFeature(Window.FEATURE_NO_TITLE);
    setContentView(R.layout.activity_main);

    Button toPech = (Button)findViewById(R.id.toPech);
    toPech.setOnClickListener(this);
    ImageButton toInfo = (ImageButton)findViewById(R.id.toInfo);
    toInfo.setOnClickListener(this);
    //this button is not in the same layoutactivity as the other 2.
    ImageButton backPech = (ImageButton)findViewById(R.id.backPech);
    backPech.setOnClickListener(this);
}

@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_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();

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

    return super.onOptionsItemSelected(item);
}

@Override
public void onClick(View v) {
    switch(v.getId()) {
        case R.id.toPech:
            startActivity(new Intent(getApplicationContext(), LocationActivity.class));
            break;
        case R.id.toInfo:
            startActivity(new Intent(getApplicationContext(), InfoActivity.class));
            break;
        case R.id.backPech:
            startActivity(new Intent(getApplicationContext(), MainActivity.class));
            break;
    }
}

我想知道出了什么问题,以便我可以。

从您的评论行:

//此按钮与其他 2 个按钮不在同一个 layoutactivity 中。

我认为你有一个NullPointerException

虽然Button “backPech”不在activity_main.xml ,所以调用findViewById(R.id.backPech); 将返回一个null对象( backPech将为空)。

并调用setOnClickListener(this); 指向null对象将导致 NullPointerException。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM