【发布时间】:2025-11-24 09:10:01
【问题描述】:
我在异步任务的 onPreExecute 方法中有一个进度对话框,但在异步任务从数据库中获取数据时它不会立即显示。您能否建议在单击按钮时立即显示进度对话框的内容。在当前场景中,屏幕在获取数据时会冻结。获取后,它会移动到下一个屏幕,但同时它不会显示我的进度对话框。 下面是异步任务
public class waitAsync extends AsyncTask<String, Void, String> {
ResultSet rs=null;
private ProgressDialog processingDialog;
static Connection conn=null;
Statement stmt;
// waitThread wt= new waitThread();
@Override
protected void onPreExecute() {
// ProgressDialog processingDialog;
super.onPreExecute();
processingDialog = new ProgressDialog(MainActivity.mCon);
processingDialog.show();
processingDialog.setContentView(R.layout.activity_wait);
//processingDialog.setMessage("Loading...");
}
@Override
protected String doInBackground(String... params) {
try {
String driver = "net.sourceforge.jtds.jdbc.Driver";
String ip = "mfb.dfsdfsdf.ap-north-1.rds.amazonaws.com";
String classs = "net.sourceforge.jtds.jdbc.Driver";
String db = "MyDatabase";
String un = "xxxwww";
String password = "xxxxxx";
Class.forName(classs);
String ConnURL = null;
ConnURL = "jdbc:jtds:sqlserver://" + ip + ";"
+ "databaseName=" + db + ";user=" + un + ";password="
+ password + ";";
conn = DriverManager.getConnection(ConnURL);
stmt = conn.createStatement(
ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);
rs=stmt.executeQuery(params[0]);
int size = 0;
//conn.close();
MainActivity.getdata=rs;
MainActivity.flag=1;
//Thread.sleep(5000);
} catch (Exception e)
{
Log.w("Error connection", "" + e.getMessage());
}
return null;
}
@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
processingDialog.dismiss();
// wt.interrupted();
}
}
从 Main_Activity 调用异步任务
Getdata(String bookid)
{
String SQL="Select eb.book_name,eb.AuthorID,ma.Name,eb.GenreID_M,eb.GenreID_D,gm.Genre_MN+'- '+gd.Genre_DN as Genre,isnull(eb.pubDate,'') pubDate,isnull(eb.book_Loc,'') book_Loc,\n" +
" eb.Price,eb.ico_Loc,eb.Descrip from Master_ebook eb inner join Master_Author ma on eb.AuthorID=ma.Author_ID\n" +
" inner join Master_Genre_M gm on eb.GenreID_M=gm.Genre_MID\n" +
"inner join Master_Genre_D gd on eb.GenreID_D= gd.Genre_DID where eb.bookID=" + bookid;
new waitAsync().execute(SQL);
int c=0;
while(MainActivity.flag==0)
{
c++;
}
if(MainActivity.flag==1)
{
MainActivity.flag=0;
//processingDialog.dismiss();
}
ResultSet rs=MainActivity.getdata;
}
【问题讨论】:
-
因为显然你已经用
while(MainActivity.flag==0) { c++; }阻塞了 UI 线程 .... 此代码使 AsyncTask 无用 -
我还能做什么?你能建议吗?我将不得不等到我的异步任务获取我的数据,因为我将在主要活动 getdata 方法中立即需要该数据
-
我认为我在您的 asynctask 中所做的更改就足够了
-
我试过了,它没有任何影响。 @Maharith
标签: java android multithreading android-asynctask