I'm having some problems trying to navigate between screens im my Android Project. I'm not creating other Activities classes yet, I'm just trying to open other XML files by the SetContentView(R.layout.XXX). Here is my main Activity:
package com.android.eduardo.navegacao;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class NavegacaoActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
chamaTelaPrincipal();
Button btCadastro = (Button) findViewById(R.id.btCadastro);
btCadastro.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
chamaCadastro();
}
});
Button btConsulta = (Button) findViewById(R.id.btConsulta);
btConsulta.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
chamaConsulta();
}
});
Button btVoltar1 = (Button) findViewById(R.id.btVoltar);
btVoltar1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
chamaTelaPrincipal();
}
});
}
public void chamaCadastro(){
setContentView(R.layout.activity_cadastro);
}
public void chamaConsulta(){
setContentView(R.layout.activity_consulta);
}
public void chamaTelaPrincipal(){
setContentView(R.layout.activity_navegacao);
}
}
As you can see, the "R.layout.activity_navegacao" is my main layout. When I try to execute this code the application closes and I receive a NullPointerException error, indicating some problems on SetContentView.
When I cut the code of the last setOnClickListener (the button "btVoltar") it works and I can open the two other screens. The button "btVoltar" is being used by the other XML to return to the main screen (activity_navegacao).
I already checked the id of the XML on the R class, and it's ok. I also don't receive any error notifications until I execute the project. Sorry for the bad english, if you guys can help me, I appreciate.
You are getting the
NullPointerException
because you are referencing a button that is on an XML layout which has not been displayed. (ie, the button is not found onactivity_navegacao.xml
).For this reason, you should not call
setContentView
multiple times to change the view, like you are doing in this code. Instead, you should consider either making each screen a different activity (and callingsetContentView
only once per activity), or look into Fragments and FragmentTransactions. Fragments will allow you to replace the view, like you are attempting to do here.