Android Studio, CRUD in SQL Server 2008

Asked

Viewed 443 times

0

I’m doing an application at the company where I can register for homeowners and visitors. I am making a connection to the SQL Server 2008 database quietly, but I cannot do CRUD in the application. I did the test of Add a joint owner, but when I press the "Save" button, 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;
 }
}

1 answer

1

You are not using Asynctask correctly.

1) Does not have a method onPostExecute() that receives the return value of the method doInBackground() to at least make Progressbar disappear or show some error. That’s why it stays on the screen running, because you display it on onPreExecute() And then you don’t do anything with it anymore, so the database processing may have even happened, but you don’t 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 Input Strings but run it by passing an empty value on execute() and then retrieves the Edittexts Strings inside the doInBackground. It got weird (and I don’t even know if it works). The normal would be to have passed the data of your Edittexts as input parameters in execute() and retrieve the values in 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 didn’t you create the site at)?
  • isSuccess (It’s no use at all)
  • infoName and infoDocu (can be moved to the button system, as I did in the above step)

Worth a look at this documentation: https://developer.android.com/reference/android/os/AsyncTask.html

  • Sorry for the delay in answering Márcio, I did what you said, but I can’t declare infoName and infoDocu in addPro.execute(). The Progressbar problem is gone, it no longer runs endlessly, but even then there is no Insert of the data.

  • You tried debugging the app to see if the execution reaches the Insert command. If it arrives, you have to see how are the variables infoName and infoDocu at this point, if they are with valid values. If you’re still not entering, then there’s some other problem with this Preparedstatement class that I don’t know about.

  • What other class is used to insert data into a bank? Forgive all the difficulty, I’m still at the beginning of the Mobile branch (Android)

  • I honestly do not know. So far only worked with local Sqlite database on the device.

  • Marty, he falls into if(con == null) and soon after he already falls into exceptions with the error: "java.lang.Runtimeexception: Can’t create Handler Inside thread that has not called Looper.prepare()". You know what would be?

  • Márcio, I got it. It was problem in the connectionClass. Thank you, of vdd.

Show 1 more comment

Browser other questions tagged

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