我有一个连接到sql server的代码,在主线程上运行它时它工作得很好,但是由于连接时线程卡住,我决定将代码放入异步任务中。现在它卡在了connection.getConnection(connectionURL)上..有人知道为什么吗?
public class ConnectionClass extends AsyncTask<Void,Void,Void> {
@Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog.setCancelable(false);
progressDialog.setTitle(getString(R.string.establishing_cnxtn));
progressDialog.setMessage(getString(R.string.connecting));
progressDialog.show();
}
@Override
protected Void doInBackground(Void... voids) {
connection = DatabaseHandler.getConnection(MainActivity.this);
return null;
}
@Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
progressDialog.dismiss();
if (connection == null)
Snackbar.make(layout, R.string.could_not_connect, Snackbar.LENGTH_LONG).show();
else {
try {
updateUI();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
这是数据库代码,但我知道问题不在于这段代码......
static Connection getConnection(Context context)
{
SharedPreferences sharedPreferences = context.getSharedPreferences("ip",MODE_PRIVATE);
//ip = sharedPreferences.getString("ip","");
ip = "PC-HASSANSHOUMA"; //database ip
db = "***"; //database name
un = "***"; //username to connect to db
pass = "***"; //password to connect to db
connectionURL = null;
port = "1433";
Log.i("jsbnkjnbsjkdjk","dfdfdfdfdfd");
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
Log.i("bjhbdjs","dfdfdfdfdfd");
if(connection == null)
{
try
{
Class.forName("net.sourceforge.jtds.jdbc.Driver");
Log.i("nbkjnjk","dfdfdfdfdfd");
connectionURL = "jdbc:jtds:sqlserver://"+"192.168.0.112"+"/"+db+";instance=SQL2014;user="+un+";"+"password="+pass+";";
Log.i("kjhknklnkl","dfdfdfdfdfd");
connection = DriverManager.getConnection(connectionURL);
Log.i("njknjknj","dfdfdfdfdfd");
statement = connection.createStatement();
Log.i("klklllk","dfdfdfdfdfd");
} catch (ClassNotFoundException | SQLException e) {
Log.i("nklnkl54564","dfdfdfdfdfd");
e.printStackTrace();
}
}
return connection;
}
最佳答案
protected String doInBackground(String... params) {
final String SERVICE_URL = params[0] ;
ConnectivityManager connMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnected()) {
try {
String result = downloadUrl(SERVICE_URL,params[1],params[2]);
z= result;
} catch (Exception e) {
z = "error";
onPostExecute(z);
}
}
return z;
}
并且在async的downloadUrl方法中:这是一个自定义方法
private String downloadUrl(String urlString,String iOutputFile,String iOutputPath) throws IOException {
InputStream inStream = null;
int len = 1000000; //Is not used
try {
URL url = new URL(urlString);
HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
conn.setReadTimeout(10000); // milliseconds
conn.setConnectTimeout(15000); // milliseconds
conn.setRequestMethod("GET");
conn.setDoInput(true);
conn.connect();
int response = conn.getResponseCode();
long lenghtOfFile = conn.getContentLength();
inStream = conn.getInputStream();
return saveIt(inStream,iOutputFile,iOutputPath,lenghtOfFile);
}
catch (IOException e)
{
return e.getMessage();
}
finally {
if (inStream != null) {
inStream.close();
}
}
}
saveit 也是执行任务后的自定义方法...saveit 是异步类的私有(private)方法(用于下载后处理...)。 在此示例中,我从服务器获取了一个文件,然后将其保存在手机中。
在调用 asynctask 实例时:
new GetGedFileFromServer().execute(file_url4Download,file_Name4Save,file_Path4Save);
我的 asyncTask 的名称是 GetGedFileFromServer()
您唯一要做的就是创建一个字符串呈现 file_url4Download ...最后,这只是您想要发送文件或从服务器上分配的 sql 服务器获取数据的示例代码或...。您可以自定义处理对话框的 pre 和 post 方法...
关于java - 与数据库的连接卡在 asynctask 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62018753/