AsyncTask 不返回值

Posted

技术标签:

【中文标题】AsyncTask 不返回值【英文标题】:AsyncTask not returning value 【发布时间】:2019-07-20 15:16:18 【问题描述】:

代码 1 在主 Activity 上运行时有效,但在访问 SQL 数据库时会创建一个短暂的黑屏。

为防止出现黑屏,我将 SQL 任务移至 AsyncTask,但从查询中获得的数据并未传递给适配器。 我没有得到任何结果(代码 2)。 我不知道出了什么问题。 请帮忙。

代码 1

public class CommentsView extends AppCompatActivity 

ArrayList<CommentObject> datamodels;
ListView listview;
ConnectionClassBatchRecord connectionClassBR;
String rcomments,rdoneby,rdateby,stepid,z;
private static CommentsListAdapter commentsAdapter;

@Override
protected void onCreate(Bundle savedInstanceState) 
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_comments_view);
    connectionClassBR = new ConnectionClassBatchRecord();
    datamodels=new ArrayList<>();
    String step_Id = (String) getIntent().getExtras().get("Step_Id");
    stepid=step_Id;

    try 
        Connection con = connectionClassBR.CONN();
        if (con == null) 
            Log.v(TAG,"Error in connection with SQL server");
         else 

            String query ="SELECT * FROM comments WHERE Step_Id='"+stepid+"'";
            PreparedStatement preparedStatement = con.prepareStatement(query);
            ResultSet rs =preparedStatement.executeQuery();

            while (rs.next()) 
                rcomments = rs.getString("Comment");
                rdoneby=rs.getString("DoneBy");
                rdateby=rs.getString("DoneByDate");
                CommentObject commentobject=new CommentObject(rcomments,rdoneby,rdateby);
                datamodels.add(commentobject);


            
        
     catch (Exception ex) 
        //z = "Exceptions";
        z=ex.getMessage();
        Log.v(TAG,"Exceptionmessage"+z);
    

    listview = (ListView) findViewById(R.id.commentslist);
    CommentsListAdapter commentsadapter = new CommentsListAdapter(this, datamodels);
    listview.setAdapter(commentsadapter);


代码 2

public class CommentsView extends AppCompatActivity 

ArrayList<CommentObject> datamodels;
ListView listview;
ConnectionClassBatchRecord connectionClassBR;
String rcomments,rdoneby,rdateby,stepid,z;
private static CommentsListAdapter commentsAdapter;

@Override
protected void onCreate(Bundle savedInstanceState) 
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_comments_view);
    connectionClassBR = new ConnectionClassBatchRecord();
    datamodels=new ArrayList<>();
    String step_Id = (String) getIntent().getExtras().get("Step_Id");
    stepid=step_Id;

    FindcommentsAsyncTask findcommentsAsyncTask=new FindcommentsAsyncTask(this);
    findcommentsAsyncTask.execute(stepid);

    listview = (ListView) findViewById(R.id.commentslist);
    CommentsListAdapter commentsadapter = new CommentsListAdapter(this, datamodels);
    listview.setAdapter(commentsadapter);



private class FindcommentsAsyncTask extends AsyncTask<String,Void,ArrayList<CommentObject>> 

    String z,comm,sid;
    ResultSet result_rs;

    private ProgressDialog dialog;
    private Context context;
    private Activity activity;
    public FindcommentsAsyncTask(Activity activity) 
        this.activity = activity;
        this.context = activity;
        this.dialog = new ProgressDialog(context);
    

    @Override
    protected void onPreExecute() 
        this.dialog.setMessage("Retrieving Data");
        this.dialog.show();
    

    @Override
    protected ArrayList<CommentObject> doInBackground(String... params) 

        sid=params[0];

        try 
            Connection con = connectionClassBR.CONN();
            if (con == null) 
                Log.v(TAG,"Error in connection with SQL server");
             else 

                String query ="SELECT * FROM comments WHERE Step_Id='"+sid+"'";
                PreparedStatement preparedStatement = con.prepareStatement(query);
                ResultSet rs =preparedStatement.executeQuery();

                while (rs.next()) 
                    rcomments = rs.getString("Comment");
                    rdoneby=rs.getString("DoneBy");
                    rdateby=rs.getString("DoneByDate");
                    CommentObject commentobject=new CommentObject(rcomments,rdoneby,rdateby);
                    datamodels.add(commentobject);


                
            
         catch (Exception ex) 
            //z = "Exceptions";
            z=ex.getMessage();
            Log.v(TAG,"Exceptionmessage"+z);
        

        return datamodels;
    

    @Override
    protected void onPostExecute(ArrayList<CommentObject> mresult_rs)
    
        passdata(mresult_rs);
        if (dialog.isShowing()) 
            dialog.dismiss();
        
    


private void passdata(ArrayList<CommentObject> mresult_rs)

    if (mresult_rs == null) 
        Toast.makeText(getApplication(), "No comments Found", Toast.LENGTH_LONG).show();
     else 
        datamodels=mresult_rs;
    

【问题讨论】:

【参考方案1】:

问题是 onPostExecute 接收的是一个空数组?或者 listView 永远不会被填充? 我在这里看到的是线程竞赛,当您的 AsyncTask 仍在获取信息时,适配器正在使用一个空数组来填充列表。当 Asynctask 完成时,它会将结果加载到数据模型上,但不会通知适配器数据已更改。 要么在 passdata 上调用适配器的更新,要么在 passdata 中创建适配器,然后一切都会正常工作。

【讨论】:

感谢桑德里托。我将适配器创建和 setadapter 步骤移至 passdata 函数,它解决了问题。

以上是关于AsyncTask 不返回值的主要内容,如果未能解决你的问题,请参考以下文章

如何获取AsyncTask 异步处理的返回值

android AsyncTask 怎么返回值给UI线程

android AsyncTask 怎么返回值给UI线程

android AsyncTask 怎么返回值给UI线程

AsyncTask:doInBackground() 的返回值去哪了?

无法从 AsyncTask 返回值;使用接口和委托;