Android Studio, CRUD in SQL Server 2008

0

I am making an application in the company where I can do registration of condominiums and visitors of the place. I am making a connection to the SQL Server 2008 database quietly, but I can not do the CRUD in the application. I made the Add test a condominium, but when I hit the "Save" button, the ProgressBar just keeps running and nothing happens.

public class MegaPermanentes extends AppCompatActivity {

//Declarando as variáveis //
ConnectionClass connectionClass;
EditText editName, editDocument;
Button addButton, editButton, deleteButton;
ProgressBar progressBar;



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

    StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
    StrictMode.setThreadPolicy(policy);

    connectionClass = new ConnectionClass();
    editName = (EditText) findViewById(R.id.edtName);
    editDocument = (EditText) findViewById(R.id.edtDocumento);
    addButton = (Button) findViewById(R.id.addButton);
    editButton = (Button) findViewById(R.id.editButton);
    deleteButton = (Button) findViewById(R.id.removeButton);
    progressBar = (ProgressBar) findViewById(R.id.progBar);
    progressBar.setVisibility(View.GONE);

    addButton.setOnClickListener(new View.OnClickListener(){
        @Override
        public void onClick (View v){
            AddInfo addPro = new AddInfo();
            addPro.execute("");
            editName.setText("");
            editDocument.setText("");

        }
    });
}



public class AddInfo extends AsyncTask<String, String, String>{
    String z = "";
    Boolean isSucess = false;

    String infoName = editName.getText().toString();
    String infoDocu = editDocument.getText().toString();
    @Override
    protected  void onPreExecute()
    {
        progressBar.setVisibility(View.VISIBLE);
    }

    @Override
    protected String doInBackground(String... params) {
        if(infoName.trim().equals("") || infoDocu.trim().equals(""))
            z = "Por favor digite um nome e um documento";
        else{
            try{
                Connection con = connectionClass.CONN();
                if (con == null){
                    z = "Erro na conexão com o Banco de Dados";
                }
                else
                {
                    String query = "insert into usuarios (nome,endereco) values ('" + infoName + "','" +infoDocu + "')";
                    PreparedStatement preparedStatement = con.prepareStatement(query);
                    preparedStatement.executeUpdate();
                    z = "Cadastro inserido com sucesso";
                    isSucess = true;
                }
            }catch( Exception ex){
                isSucess = false;
                z = "Exceptions";
            }
        }

        return z;
    }
}

@SuppressLint("NewApi")
public Connection connectionclass (String user, String password, String database, String server)
{
    StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
    StrictMode.setThreadPolicy(policy);
    Connection connection = null;
    String ConnectionURL = null;
    try
    {
        Class.forName("net.sourceforge.jtds.jdbc.Driver");
        ConnectionURL = "jdbc:jtds:sqlserver://192.168.0.169/ANDROID_SQL;instance=MEGACONTROL;user=sa;password=@dm1n102030";
        //ConnectionURL = "jdbc:jtds:sqlserver://" + ip +"/"+ db +";""istance=MEGACONTROL""";user=" + un + ";password="+ password + ";";
        connection = DriverManager.getConnection(ConnectionURL);


    } catch (ClassNotFoundException e) {
        e.printStackTrace();
        Log.e("Error here 1", e.getMessage());
    } catch (SQLException e) {
        e.printStackTrace();
        Log.e("Error here 2", e.getMessage());
    }

    return connection;
 }
}
    
asked by anonymous 14.08.2017 / 21:42

1 answer

1

You are not using AsyncTask properly.

1) It does not have a onPostExecute() method that receives the return value of the doInBackground() method to at least wipe the ProgressBar or display an error. So it stays on the screen running, because you display it in onPreExecute() and then do nothing else with it, so database processing may have happened, but you do not do anything with the results. It could be something like this:

 // O sua classe deve estender AsyncTask<String, Void, String>
 // O valor z que você retorna no doInBackground() é entregue como o result abaixo
 @Override     
 protected void onPostExecute(String result) {
     progressBar.setVisibility(View.GONE);
     Toast.makeText(this, result, Toast.LENGTH_SHORT);
 }

2) You set your AsyncTask to have Inbound Strings, but run it by passing an empty value in execute() and then retrieving the EditTexts Strings within doInBackground . It got weird (and I do not even know if that works). The normal would be to have passed the data of your EditTexts as input parameters in execute () and retrieve the values in the variable params of doInBackGround() :

Ex:

String infoName = editName.getText().toString();
String infoDocu = editDocument.getText().toString();
addPro.execute(infoName, infoDocu);

...

@Override
protected String doInBackground(String... inputs) {
    if(inputs[0].trim().equals("") || inputs[1].trim().equals(""))
        z = "Por favor digite um nome e um documento";
  ...
}

Remembering that your class should extend from AsyncTask<String, Void, String>

3) Your AddInfo class has useless global variables:

  • z (Why did not you create it on doInBackground?)
  • isSuccess (Not useful for anything)
  • infoName and infoDocu (can be moved to the button listener, as I did in the step above)

It's worth taking a look at this documentation: link

    
14.08.2017 / 23:11