0

我有一个远程调用,我想知道把这个处理代码放在哪里更好:

        if ( result == null )
        {       
            Toast.makeText(getApplicationContext(), "Some error message", Toast.LENGTH_LONG).show();                                

        }
        else
        if ( result.equals( "all_problems_db_error" ))
        {
        Log.d( "AllBusinessesActivity" , "result: " + result )                                      
        }
        else
        {
            // Unwrap the stuff from the JSON string                
            String problem_title = null;
            String problem_id = null;

            try
            {
                JSONArray obj = new JSONArray(result);

                if ( obj != null )
                {
                    problems.clear();

                    for ( int i = 0; i < obj.length(); i++ )
                    {
                        JSONObject o = obj.getJSONObject(i);

                        problem_title = o.getString("problem_title");
                        problem_id = o.getString("problem_id");

                        Problem p = new Problem ( );
                        p.setProblemId(problem_id);                         
                        p.setProblemName(problem_title);

                        problems.add( p );
                    }

                    adapter.notifyDataSetChanged();             

                }                                   
            }
            catch ( Exception e )
            {
           // Do something :)
            }               
        }

将它放在 onPostExecute() 或末尾或 doInBackground() 中更好吗?

我现在在 onPostExecute() 中执行此操作,但有时我会遇到一些缓慢,并且我一直在阅读,在 doInBackground 中执行此操作可能会更好。

有人可以向我解释一下区别吗?如果我在 doInBackground() 中执行此操作,那么使用 onPostExecute 方法的目的是什么?

4

2 回答 2

2

当您需要在 UI 线程上做一些事情时,该onPostExecute方法很有用。实际上,您无法doInBackground在方法 中对 UI 进行任何操作。

因此,请尝试在该方法中进行所有计算/数据下载等doInBackground,并且仅在该方法中操作您的 UI onPostExecute

于 2012-06-12T18:08:45.220 回答
0

Is it better to have it in the onPostExecute()

由于在您的情况下没有任何 UI 组件的操作,您可以将代码放在doInBackground(). 但是,由于您toast在结果为时显示 a ,因此null您可以检查结果doInBackground(),如果结果不为 null 您可以result在同一函数中对其进行剩余处理,否则您可以传递到onPostExecute()可以显示toast.

at the end or doInBackground() 是的。您可以在末尾使用此代码,doInBackground()因为此方法在非 UI 线程上运行,这肯定会减少您遇到的缓慢。

这两种方法之间的区别doInBackground()只是onPostExecute()前者在非 UI 线程上运行,而后者在 UI-Thread 上运行。

And if I do this in the doInBackground() then what is the purpose of having the onPostExecute method

通常doInBackground()用于执行耗时的操作。这些操作可能包括调用 Web 服务或从服务器获取图像等活动。在这种情况下(例如从服务器获取图像),您希望这些图像显示在您的屏幕(即您的 UI)上。获取这些资源后,您将数据传递到onPostExecute()您可以更新 UI 的地方,因为它在您的 UI 线程上运行。

希望这个解释能消除你的疑惑。

于 2012-06-12T18:25:35.633 回答