Android程序未启动即崩溃,请求SQL Server数据库连接调试帮助
Fixing Your Android SQL Server Connection Crash Issues
Hey there, let's break down why your app is crashing before it even runs and fix those issues step by step:
Key Issues Causing the Crash
- Early View Initialization: You're calling
findViewByIddirectly in the Activity's member variable section, but the layout hasn't been loaded yet (this happens inonCreate). This meansedtMedisnullright away, triggering a NullPointerException—the main reason your app crashes on launch. - Stale Input Value:
ConsulMedis set once when the Activity is created, not when the user actually enters text. It won't reflect any input the user types later. - Main Thread Network Operation: You're running SQL Server connection and query code directly on the main thread. Android blocks this to keep the UI responsive, which will throw a NetworkOnMainThreadException even if the initial crash is fixed.
- Missing Connection Details: Your
DriverManager.getConnectioncall doesn't include SQL Server credentials (username/password), and you haven't explicitly loaded the JDBC driver, which is required for most setups. - Unclosed Resources: You don't close
Connection,Statement, orResultSetafter use, leading to resource leaks over time.
Corrected Code Example
Here's a revised version of your code that fixes all these issues, using AsyncTask to handle the database work off the main thread:
import android.os.AsyncTask; import android.os.Bundle; import android.view.View; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.Statement; public class Farmaciapp extends AppCompatActivity { // Declare views as member variables, but don't initialize them yet private EditText edtMed; private TextView mltExplic; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_farmaciapp); // Initialize views AFTER setting the layout edtMed = findViewById(R.id.edtMedicamento); mltExplic = findViewById(R.id.mltExplic); } public void Meds(View v) { // Get the input text WHEN the button is clicked, not on Activity creation String consulMed = edtMed.getText().toString().trim(); if (consulMed.isEmpty()) { Toast.makeText(this, "Please enter a medicine name", Toast.LENGTH_SHORT).show(); return; } // Run database operations in a background thread new DatabaseQueryTask().execute(consulMed); } // AsyncTask to handle background database work private class DatabaseQueryTask extends AsyncTask<String, Void, String> { @Override protected String doInBackground(String... params) { String medicamentoDescripcion = null; Connection conexion = null; Statement state = null; ResultSet resultado = null; try { // Load the JDBC driver explicitly Class.forName("net.sourceforge.jtds.jdbc.Driver"); // Update URL with your SQL Server username and password String url = "jdbc:jtds:sqlserver://192.168.1.69;databaseName=Medicamentos;user=YOUR_USERNAME;password=YOUR_PASSWORD;"; String query = "SELECT Descripcion FROM Medicina WHERE Nombre = '" + params[0] + "'"; conexion = DriverManager.getConnection(url); state = conexion.createStatement(); resultado = state.executeQuery(query); if (resultado.next()) { medicamentoDescripcion = resultado.getString("Descripcion"); } } catch (Exception e) { e.printStackTrace(); return "Error: " + e.getMessage(); } finally { // Close all resources to prevent leaks try { if (resultado != null) resultado.close(); if (state != null) state.close(); if (conexion != null) conexion.close(); } catch (Exception e) { e.printStackTrace(); } } return medicamentoDescripcion; } @Override protected void onPostExecute(String result) { super.onPostExecute(result); if (result != null && !result.startsWith("Error")) { mltExplic.setText(result); } else { Toast.makeText(Farmaciapp.this, result != null ? result : "No medicine found", Toast.LENGTH_SHORT).show(); } } } }
Additional Notes
- Replace
YOUR_USERNAMEandYOUR_PASSWORDwith your actual SQL Server credentials. - Make sure you've added the JTDS JDBC driver dependency to your project (check your
build.gradlefile forimplementation 'net.sourceforge.jtds:jtds:1.3.1'or similar). - Ensure your Android device and SQL Server are on the same local network, and that SQL Server is configured to allow remote connections and uses the correct port (default is 1433).
- For newer Android versions, consider using
Coroutinesinstead ofAsyncTask(since AsyncTask is deprecated), but AsyncTask is simpler for beginners to understand.
内容的提问来源于stack exchange,提问作者Daniel Urbina
相关产品推荐
相关产品推荐

