我有一个连接到sql server的代码,在主线程上运行它时效果很好,但是因为线程在连接时冻结,所以我决定将代码放入异步任务。现在它卡在connection.getConnection(connectionURL)上。ANyone知道为什么吗?
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是async类的私有方法(用于下载后处理...)。
在此示例中,我从服务器获取了一个文件,然后将其保存在电话中。
在asynctask的调用实例中:
new GetGedFileFromServer().execute(file_url4Download,file_Name4Save,file_Path4Save);
我的asyncTask的名称是GetGedFileFromServer()
您唯一要做的就是创建一个呈现字符串file_url4Download ...,最后这只是您要发送文件或从服务器或...上分配的sql server中获取数据的示例代码。您可以自定义用于处理对话框的pre和post方法...
关于java - 与卡在asynctask中的数据库的连接,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/62018753/