Help with connection to sql server 2008 and android database

Asked

Viewed 670 times

2

I made, following a tutorial, the connection of Android Studio with SQL Server 2008 R2 (already existing), with which I was able to make the connection normally, only I have a problem. I can make the connection with the bank if the connection with the bank is successful (port access, internet ok, etc). In case I can not access to the bank (access to the port denied or lack of internet on the server PC), the program enters a black screen as if trying to connect to the bank and only after a while it returns me an error.

Look at the code I use:

Conexão Dao

public class ConexaoDao {
    @SuppressLint("NewApi")
    public Connection dbConnect(ObjetoConexao objConexao) {
        StrictMode.ThreadPolicy policy = new
                StrictMode.ThreadPolicy.Builder().permitAll().build();
        StrictMode.setThreadPolicy(policy);
        Connection conn = null;
        String connectionUrl = null;
        try {
            Class.forName("net.sourceforge.jtds.jdbc.Driver");
            connectionUrl = "jdbc:jtds:sqlserver://" +
                    objConexao.db_connect_string + ";" +
                    "databaseName=" + objConexao.db_name + ";user="
                    + objConexao.db_userid +
                    ";password=" + objConexao.db_password + ";";
            conn = DriverManager.getConnection(connectionUrl);


            return conn;

        }


            catch(ClassNotFoundException cnf){
                System.out.println ("Classe JDBC Driver nao encontrada.");
                return null;
            }
            catch(SQLException sql){
                System.out.println ("Erro ao se conectar com o banco de dados.");


                return null;
            }
            catch(Exception e){
                System.out.println (e.getMessage());
                return null;

            }
    }
}

Class where I do the research

public class Dao_PcCampestre extends Context{



    public String nomeTabela()  {

        String nomeResTorres = "";
        ConexaoDao conexao = new ConexaoDao();
        ObjetoConexao objConexao = new ObjetoConexao();
        objConexao.db_connect_string = "ronaldesantos.hopto.org:1433";
        objConexao.db_name = "Barbacena2";
        objConexao.db_userid = "sa";
        objConexao.db_password = "flextelecom";
        Connection conn = conexao.dbConnect(objConexao);



        if (conn == null) {

            nomeResTorres = "Não foi possivel se conectar ao banco de dados";



        } else if (conn != null) try {
            Statement statement = conn.createStatement();
            String queryString = "select TOP 1 Area ,Source,Message from Alarmes Where AREA = 'POÇO CAMPESTRE' AND Source ='xo_Alarmes.Falta_Energia'  order By E3TimeStamp DESC ";
            ResultSet rs;

            rs = statement.executeQuery(queryString);

            if (rs.next()) {

                nomeResTorres = rs.getString("Message");



            }

            rs.close();


        } catch (SQLException e) {



            System.out.println (e.getMessage());
            return null;



        }


        return nomeResTorres;

    }




    public String nomeTabela2()  {
        String nomeResTorres2 = "";
        ConexaoDao conexao = new ConexaoDao();
        ObjetoConexao objConexao = new ObjetoConexao();
        objConexao.db_connect_string = "ronaldesantos.hopto.org:1433";
        objConexao.db_name = "Barbacena2";
        objConexao.db_userid = "sa";
        objConexao.db_password = "flextelecom";
        Connection conn = conexao.dbConnect(objConexao);


        if (conn == null)  {

            nomeResTorres2 = "Não foi possivel se conectar ao banco de dados";

            return ""+ nomeResTorres2;

        }else if (conn != null) try {
            Statement statement = conn.createStatement();
            String queryString = "select TOP 1 Code from Tbl_Comunicacao_Pc_Campestre where Situacao = 'Recepção (RX) - Aguardando' or Situacao =  'Recepção (RX) - OK' or Situacao =  'Recepção (RX) - Erro'   order By E3TimeStamp DESC ";
            ResultSet rs;

            rs = statement.executeQuery(queryString);


            if (rs.next()) {

                nomeResTorres2 = rs.getString("Code");

                if (nomeResTorres2.equals("255")) {

                    nomeResTorres2 = "Aguardando Recepção";


                } else if (nomeResTorres2.equals("0")) {

                    nomeResTorres2 = "Recepção OK";


                } else if (nomeResTorres2.equals("4")) {

                    nomeResTorres2 = "Recepção OK";


                } else if (nomeResTorres2.equals("1")) {

                    nomeResTorres2 = "Falha na Recepção";


                }

                rs.close();
            }
        } catch (SQLException e) {


            System.out.println (e.getMessage());
            return null;
        }
        return ""+ nomeResTorres2;


    }


    public String nomeTabela3()  {
        String nomeResTorres3 = "";
        ConexaoDao conexao = new ConexaoDao();
        ObjetoConexao objConexao = new ObjetoConexao();
        objConexao.db_connect_string = "ronaldesantos.hopto.org:1433";
        objConexao.db_name = "Barbacena2";
        objConexao.db_userid = "sa";
        objConexao.db_password = "flextelecom";
        Connection conn = conexao.dbConnect(objConexao);



        if (conn == null)  {

            nomeResTorres3 = "Não foi possivel se conectar ao banco de dados";

            return  ""+ nomeResTorres3;

        }else  if (conn != null) try {
            Statement statement = conn.createStatement();
            String queryString = "select TOP 1 Area,Source,Message from Alarmes Where AREA = 'POÇO CAMPESTRE' AND Source ='xo_Alarmes.Presenca'  order By E3TimeStamp DESC ";
            ResultSet rs;

            rs = statement.executeQuery(queryString);



            if (rs.next()) {

                nomeResTorres3 = rs.getString("Message");
            }

            rs.close();

        } catch (SQLException e) {

            System.out.println (e.getMessage());
            return null;

        }
        return ""+ nomeResTorres3;


    }




    public String nomeTabela5() {
        String nomeResTorres5 = "";
        ConexaoDao conexao = new ConexaoDao();
        ObjetoConexao objConexao = new ObjetoConexao();
        objConexao.db_connect_string = "ronaldesantos.hopto.org:1433";
        objConexao.db_name = "Barbacena2";
        objConexao.db_userid = "sa";
        objConexao.db_password = "flextelecom";
        Connection conn = conexao.dbConnect(objConexao);




        if (conn == null)  {

            nomeResTorres5 = "Não foi possivel se conectar ao banco de dados";

            return "" + nomeResTorres5;

        }       else if (conn != null) try {
            Statement statement = conn.createStatement();
            String queryString = "select TOP 1 Area ,Source,Message from Alarmes Where AREA = 'POÇO CAMPESTRE' AND Source ='xo_Alarmes.Sobrecarga'  order By E3TimeStamp DESC ";
            ResultSet rs;

            rs = statement.executeQuery(queryString);


            if (rs.next()) {

                nomeResTorres5 = rs.getString("Message");



            }

            rs.close();

        } catch (SQLException e) {



            System.out.println (e.getMessage());
            return null;

        }
        return "" + nomeResTorres5;

    }

    public String nomeTabela6() {
        String nomeResTorres6 = "";
        ConexaoDao conexao = new ConexaoDao();
        ObjetoConexao objConexao = new ObjetoConexao();
        objConexao.db_connect_string = "flexsas.hopto.org:1433";
        objConexao.db_name = "Barbacena2";
        objConexao.db_userid = "sa";
        objConexao.db_password = "flextelecom";
        Connection conn = conexao.dbConnect(objConexao);


        if (conn == null)  {

            nomeResTorres6 = "Não foi possivel se conectar ao banco de dados";

            return "" + nomeResTorres6;

        }else     if (conn != null) {
            try {
                Statement statement = conn.createStatement();
                String queryString = "select TOP 1 Estado  from Tbl_Acionamentos_Pc_Campestre  order By E3TimeStamp DESC ";
                ResultSet rs;

                rs = statement.executeQuery(queryString);


                if (rs.next()) {

                    nomeResTorres6 = rs.getString("Estado");
                }


                rs.close();

            } catch (SQLException e) {



                System.out.println (e.getMessage());
                return null;




            }
        }
        return "" + nomeResTorres6;

    }

In this case I click on a button that takes me to the results screen.

If there is a problem with the connection to the bank it is in processing as the monitoring in Android Studio (while it does not go through all the searches does not return me anything).

06-22 12:00:40.373 2371-2377/br.com.flextelecom.barbacena W/art: Suspending all threads took: 16.647ms
06-22 12:01:09.469 2371-2382/br.com.flextelecom.barbacena W/art: Suspending all threads took: 6.838ms
06-22 12:01:09.476 2371-2382/br.com.flextelecom.barbacena I/art: Background sticky concurrent mark sweep GC freed 7371(946KB) AllocSpace objects, 1(16KB) LOS objects, 23% free, 3MB/4MB, paused 10.003ms total 25.924ms
06-22 12:03:17.195 2371-2371/br.com.flextelecom.barbacena I/System.out: Erro ao se conectar com o banco de dados.
06-22 12:05:24.874 2371-2371/br.com.flextelecom.barbacena I/System.out: Erro ao se conectar com o banco de dados.
06-22 12:07:32.395 2371-2371/br.com.flextelecom.barbacena I/System.out: Erro ao se conectar com o banco de dados.
06-22 12:09:39.913 2371-2371/br.com.flextelecom.barbacena I/System.out: Erro ao se conectar com o banco de dados.
06-22 12:11:47.433 2371-2371/br.com.flextelecom.barbacena I/System.out: Erro ao se conectar com o banco de dados.
06-22 12:11:47.453 2371-2371/br.com.flextelecom.barbacena I/Choreographer: Skipped 38296 frames!  The application may be doing too much work on its main thread.
06-22 12:11:47.510 2371-2609/br.com.flextelecom.barbacena W/EGL_emulation: eglSurfaceAttrib not implemented
06-22 12:11:47.510 2371-2609/br.com.flextelecom.barbacena W/OpenGLRenderer: Failed to set EGL_SWAP_BEHAVIOR on surface 0x7f5184c0abc0, error=EGL_SUCCESS

Follows the main:

public class Act_Poco_Campestre extends AppCompatActivity implements View.OnClickListener {

    private Button btnFechar;
    private TextView tvNomeComunicacao;
    private ImageView ImgSinal;
    private ImageView ImgStatus;
    private TextView tvNomeStatus;
    private TextView tvNomePresenca;
    private ImageView ImgPresenca;
    private TextView tvNomeFalha;
    private ImageView Imgfalha;
    private TextView tvNomeEnergia;
    private ImageView ImgEnergia;


    String Aguardanando = "Aguardando Recepção";
    String Recepcao = "Recepção OK";
    String Falha = "Falha na Recepção";
    String PresencaAc = "Sensor Invasão Atuado";
    String PresencaN = "Sensor Invasão Desarmado";
    String FalhaAc = "Sobrecarga Motor";
    String FalhaN = "Rearme Sobrecarga";
    String StatusAc = "Ligado";
    String StatusN = "Desligado";
    String EnergiaAc = "Falta Enegia Eletrica";
    String EnergiaN = "Enegia Eletrica Restabelecida";
    String FalhaCon = "Não foi possivel se conectar ao banco de dados";


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


        btnFechar = (Button) findViewById(R.id.btnFechar);
        btnFechar.setOnClickListener(this);
        tvNomeComunicacao = (TextView) findViewById(R.id.tvNomeComunicacao);
        ImgSinal = (ImageView) findViewById(R.id.ImgSinal);
        ImgStatus = (ImageView) findViewById(R.id.ImgStatus);
        ImgPresenca = (ImageView) findViewById(R.id.ImgPresenca);
        tvNomePresenca = (TextView) findViewById(R.id.tvNomePresenca);
        Imgfalha = (ImageView) findViewById(R.id.ImgFalha);
        tvNomeFalha = (TextView) findViewById(R.id.tvNomeFalha);
        tvNomeStatus = (TextView) findViewById(R.id.tvNomeEstado);
        ImgEnergia = (ImageView) findViewById(R.id.ImgEnergia);
        tvNomeEnergia = (TextView) findViewById(R.id.tvNomeEnergia);
        Dao_PcCampestre  dao_pcCampestre1= new Dao_PcCampestre();
        Dao_PcCampestre  dao_pcCampestre2= new Dao_PcCampestre();
        Dao_PcCampestre  dao_pcCampestre3= new Dao_PcCampestre();
        Dao_PcCampestre  dao_pcCampestre4= new Dao_PcCampestre();
        Dao_PcCampestre  dao_pcCampestre5= new Dao_PcCampestre();


        String nomeEnergia = dao_pcCampestre1.nomeTabela();
        String nomeComunicacao = dao_pcCampestre2.nomeTabela2();
        String nomePresenca = dao_pcCampestre3.nomeTabela3();
        String nomeFalha = dao_pcCampestre4.nomeTabela5();
        String nomeAcionamento = dao_pcCampestre5.nomeTabela6();

        if (nomeComunicacao.equals(Aguardanando)) {

            tvNomeComunicacao.setTextColor(Color.parseColor("#FFFEED04"));
            tvNomeComunicacao.setText("" + "Aguardando Recepção");
            ImgSinal.setImageResource(R.drawable.samarelo);


        } else if (nomeComunicacao.equals(Recepcao)) {

            tvNomeComunicacao.setTextColor(Color.parseColor("#FF60FB07"));
            tvNomeComunicacao.setText("" + " Recepção OK");
            ImgSinal.setImageResource(R.drawable.sverde);

        } else if (nomeComunicacao.equals(Falha)) {

            tvNomeComunicacao.setTextColor(Color.parseColor("#FFFC120E"));
            tvNomeComunicacao.setText("" + "Falha na Recepção");
            ImgSinal.setImageResource(R.drawable.svermelho);


        } else if (nomeComunicacao.equals(FalhaCon)){

            tvNomeComunicacao.setTextColor(Color.parseColor("#FF60FB07"));
            tvNomeComunicacao.setText("" + " Não foi possivel se conectar ao banco de dados");


        }

        if (nomePresenca.equals(PresencaN)) {

            tvNomePresenca.setTextColor(Color.parseColor("#FF60FB07"));
            tvNomePresenca.setText("" + " Sensor Invasão Desarmado");
            ImgPresenca.setImageResource(R.drawable.presencaon);

        } else if (nomePresenca.equals(PresencaAc)) {

            tvNomePresenca.setTextColor(Color.parseColor("#FFFC120E"));
            tvNomePresenca.setText("" + "Sensor Invasão Atuado");
            ImgPresenca.setImageResource(R.drawable.presenca);


    } else if (nomePresenca.equals(FalhaCon)) {

            tvNomePresenca.setTextColor(Color.parseColor("#FF60FB07"));
            tvNomePresenca.setText("" + " Não foi possivel se conectar ao banco de dados");

        } else if (nomePresenca.isEmpty()) {

            tvNomePresenca.setTextColor(Color.parseColor("#FF60FB07"));
            tvNomePresenca.setText("" + " Sensor Invasão Desarmado");
            ImgPresenca.setImageResource(R.drawable.presencaon);

        }

        if (nomeFalha.equals(FalhaN)){

            tvNomeFalha.setTextColor(Color.parseColor("#FF60FB07"));
            tvNomeFalha.setText("" + " Rearme Falha");

        } else if (nomeFalha.equals(FalhaAc)) {

            tvNomeFalha.setTextColor(Color.parseColor("#FFFC120E"));
            tvNomeFalha.setText("" + "Falha Motor");
            Imgfalha.setImageResource(R.drawable.falhaon);


        }else if (nomeFalha.equals(FalhaCon)){

            tvNomeFalha.setTextColor(Color.parseColor("#FF60FB07"));
            tvNomeFalha.setText("" + " Não foi possivel se conectar ao banco de dados");


        }else if (nomeFalha.isEmpty()){

            tvNomeFalha.setTextColor(Color.parseColor("#FF60FB07"));
            tvNomeFalha.setText("" + " Rearme Falha");
        }


        if (nomeEnergia.equals(EnergiaN)){

            tvNomeEnergia.setTextColor(Color.parseColor("#FF60FB07"));
            tvNomeEnergia.setText("" + " Enegia Eletrica Ok");
            ImgEnergia.setImageResource(R.drawable.energiaon);

        } else if (nomeEnergia.equals(EnergiaAc)) {

            tvNomeEnergia.setTextColor(Color.parseColor("#FFFC120E"));
            tvNomeEnergia.setText("" + "Falta Enegia Eletrica");
            ImgEnergia.setImageResource(R.drawable.energiaoff);

        } else if (nomeEnergia.equals(FalhaCon)){

                tvNomeEnergia.setTextColor(Color.parseColor("#FF60FB07"));
                tvNomeEnergia.setText("" + " Não foi possivel se conectar ao banco de dados");

        } else if (nomeEnergia.isEmpty()){

            tvNomeEnergia.setTextColor(Color.parseColor("#FF60FB07"));
            tvNomeEnergia.setText("" + " Enegia Eletrica OK");
            ImgEnergia.setImageResource(R.drawable.energiaon);
        }


        if (nomeAcionamento.equals(StatusN)){

            tvNomeStatus.setTextColor(Color.parseColor("#FFFC120E"));
            tvNomeStatus.setText("" + " Poço Desligado");
            ImgStatus.setImageResource(R.drawable.pocooff);

        } else if (nomeAcionamento.equals(StatusAc)) {

            tvNomeStatus.setTextColor(Color.parseColor("#FF60FB07"));
            tvNomeStatus.setText("" + "Poço Ligado");
            ImgStatus.setImageResource(R.drawable.pocon);


        } else if (nomeAcionamento.equals(FalhaCon)){

            tvNomeStatus.setTextColor(Color.parseColor("#FF60FB07"));
            tvNomeStatus.setText("" + " Não foi possivel se conectar ao banco de dados");

        } else if (nomeAcionamento.isEmpty()){

            tvNomeStatus.setTextColor(Color.parseColor("#FFFC120E"));
            tvNomeStatus.setText("" + " Poço Desligado");
            ImgStatus.setImageResource(R.drawable.pocooff);
        }



    }




    @Override
    public void onClick (View v){
        finish();
    }
}
  • 2

    Wouldn’t a webservice be better? Note: Android-studio is just the IDE and nothing interferes with the logic of your code, as the question is not an issue with the IDE but with the development I edited the question. I recommend you learn how to use the right markup so the code doesn’t deform in the question and DON’T USE "CASH REGISTER" NEEDLESSLY.

  • Put the code of the Mainactivity class too, or better see other questions that have enough votes and see how they ask or read this link to learn how to expose your problem in a way that people understand: http://answall.com/help/mcve. otherwise it will be difficult for anyone to help you. Understand how constructive criticism

  • Guilherme I Am beginner and early cannot use webservice.

  • Use text markup correctly please, if not every issue your someone will have to fix.

1 answer

1

Regardless of the architecture (using webservices or not), the black screen is because you are not using a separate thread to perform network operations for example. When the answer is quick to be able to make the connection, queries your application works normally, when there are problems, even gives the interface delay because you are running it on the main UI thread, as we say.

In your Activity, you can create an Inner class that extends from Asynctask to perform this connection process and get better results. Avoid running your application in "Strict mode".

Example of using Asynctask to study better:

https://developer.android.com/reference/android/os/AsyncTask.html

Editing: Generic Practical Example (Adapt to your database need).

import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.Settings.System;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.view.View.OnClickListener;

public class AsyncTaskActivity extends Activity implements OnClickListener {

    private Button btn;
    private Integer total;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        btn = (Button) findViewById(R.id.button1);
        btn.setOnClickListener(this);
    }

    public void onClick(View view) {
        switch (view.getId()) {
        case R.id.button1:
            new ExemploAsync().execute();
            break;
        }
    }

    private class ExemploAsync extends AsyncTask<Void, Void, Void> {

        @Override
        protected Void doInBackground(Void... params) {
            for (int i = 1; i <= 5; i++) {
                try {
                    Thread.sleep(1000);
                    total = total * i;
                } catch (InterruptedException e) {
                    Thread.interrupted();
                }
            }
        }

        @Override
        protected void onPostExecute(String result) {
           //faça o que quiser com o total...
        }

        @Override
        protected void onPreExecute() {
            total = 1;
        }

        @Override
        protected void onProgressUpdate(Void... values) {}
    }
}
  • Matthew I’m quite a beginner . would be able to give me an example in this code that I have of how to do this, or at least for the application?

  • @Matthew an Asynctask with a progressibar, what do you think?

  • @Paulohenriqueneryoliveira in this case would not work. Measuring the packages trafficked between the bank and the application is a job that, in this context I would dispense.

  • @Ronaldosantos generic example for you to understand how it works and then adapt it to your need.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.