StackOverflowError when calling a class

1
public class MainActivity extends ActionBarActivity{

Conexao c = new Conexao();

public void tela(){

  c.CriaBanco();


  }
}

public class Conexao extends MainActivity{
  String NomeBanco = "Cadastro";
  SQLiteDatabase BancoDados = null;

  public void CriaBanco(){
        try{
            BancoDados = openOrCreateDatabase(NomeBanco, MODE_WORLD_READABLE, null);
            String SQL = "CREATE TABLE IF NOT EXIST tabCadastro ( _id INTEGER PRIMARY KEY, nome TEXT, telefone TEXT) ";
            BancoDados.execSQL(SQL);
            MensagemAlerta("Banco de Dados", "Banco Criado com Sucesso");
        }catch(Exception erro){
            MensagemAlerta("Erro Banco de Dados", "Não foi possivel criar o Banco" + erro);
        }
        finally {
            BancoDados.close();
        }
    }
    public void MensagemAlerta(String TituloAlerta, String MensagemAlerta){
    AlertDialog.Builder Mensagem = new AlertDialog.Builder(MainActivity.this);
    Mensagem.setTitle(TituloAlerta);
    Mensagem.setMessage(MensagemAlerta);
    Mensagem.setNeutralButton("Ok", null);
    Mensagem.show();

}



}

Calling a class on android gives this error:

07-02 18:50:18.090 21687-21687/? E/memtrack﹕ Couldn't load memtrack module (No such file or directory)
07-02 18:50:18.090 21687-21687/? E/android.os.Debug﹕ failed to load memtrack module: -2
07-02 18:50:18.160 21687-21695/? E/cutils-trace﹕ Error opening trace file: No such file or directory (2)
07-02 18:50:18.800 21703-21703/? E/memtrack﹕ Couldn't load memtrack module (No such file or directory)
07-02 18:50:18.800 21703-21703/? E/android.os.Debug﹕ failed to load memtrack module: -2
07-02 18:50:21.450 21713-21713/? E/AndroidRuntime﹕ in writeCrashedAppName, pkgName :com.example.gabrielbonatto.oficial
07-02 18:50:22.070 21713-21713/? E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.example.gabrielbonatto.oficial, PID: 21713
java.lang.StackOverflowError
    
asked by anonymous 03.07.2015 / 16:35

2 answers

3

Your class conexão extends MainActivity . When a new instance of class Conexão is created, it has a member Conexão , inherited from MainActivity . This member, when created, will contain another member Conexão , so on.

You end up creating endless instances of Connection, one within another. Infinite ? No, because the stack bursts before, and that's the error you get.

    
03.07.2015 / 17:00
-1

As in your MainActivity you extends ActionBarActivty you need to implement the onCreate method >

    @Override
    public void onCreate(Bundle savedInstanceState) {
         super.onCreate(savedInstanceState);
         // Seu código aqui que chama o Conexao
    }

When you do this in your Connection Class, you can remove and extend MainActvity and leave it as follows:

    public class Conexao {
        public void criaBanco(){
        // Seu código de criação do banco
        }
    }
    
03.07.2015 / 16:58