I want to know if this is the correct way of executing multiple MySQL prepared statements in Android Studio.
I have created two tables in a database, namely t1 and t2. I want to be able to update both tables when the user presses a button. When the user presses the button the following code is executed:
new Post_data_Delete(Picking.this, order_var, Client_Name,scanned_tag, new_cylinder_amount, quan_type).execute();
The code is the Async task that runs when the button is pressed. The code works, but is this the correct way of doing this?
private static class Post_data_Delete extends AsyncTask<Void, Void, Void> {
private final WeakReference<Picking> activityWeakReference;
String records = "";
String error = "";
String Order_number;
String Name_of_client;
String data;
String New_quanity;
Integer Quanity_type;
private Post_data_Delete(Picking activity,String order, String client, String scanned_data, Integer quanity, Integer quanity_type) {
activityWeakReference = new WeakReference<Picking>(activity);
Order_number = order;
Name_of_client = client;
data = scanned_data;
New_quanity = quanity.toString();
Quanity_type = quanity_type;
}
@RequiresApi(api = Build.VERSION_CODES.N)
@Override
protected Void doInBackground(Void... voids) {
try
{
Class.forName("com.mysql.jdbc.Driver");
Connection c = DriverManager.getConnection("jdbc:mysql://10.168.09.66:3306/db", "u", "p");
PreparedStatement update_cylinder = c.prepareStatement("UPDATE `db`.`t1` SET `IN` = ?, `CLIENT` = ? WHERE (`TAG` = ?)");
update_cylinder.setString(1,"OUT");
update_cylinder.setString(2,Name_of_client);
update_cylinder.setString(3,data);
update_cylinder.execute();
update_cylinder.close();
if(Quanity_type == 1)
{
PreparedStatement st = c.prepareStatement("UPDATE `db`.`t2` SET `QUANITY` = ? WHERE (`ORDER` = ?)");
st.setString(1,New_quanity);
st.setString(2, Order_number);
st.execute();
st.close();
}
else if(Quanity_type == 2)
{
PreparedStatement st = c.prepareStatement("UPDATE `db`.`t2` SET `QUANITY` = ? WHERE (`ORDER` = ?)");
st.setString(1,New_quanity);
st.setString(2, Order_number);
st.execute();
st.close();
}
else {}
c.close();
}
catch(Exception e)
{
error = e.toString();
}
return null;
}
@Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
Picking activity = activityWeakReference.get();
if(activity == null || activity.isFinishing()) {
return;
}
if(error != "") {
Toast.makeText(activity, error, Toast.LENGTH_SHORT).show();
}
else{
Toast.makeText(activity, "Successfully entered into database", Toast.LENGTH_LONG).show();
}
}
}