0

我有以下代码:(基本上它创建了各种 JSONObjects(受益人)并将它们全部放在另一个 JSONObject(proposta)中。我没有在这里展示它,但我之前创建了游标(ppt,c)

            if (ppt.getString(45).equals("0")) {
                int i = 0;

                c.moveToFirst();
                JSONObject ben = new JSONObject();
                try {
                    while (c.isAfterLast() == false) 
                    {
                        i++;
                        ben.put("b_nome" + i, c.getString(1));
                        ben.put("b_telefone" + i, c.getString(2));
                        ben.put("b_nif" + i, c.getString(3));
                        ben.put("b_bi" + i, c.getString(4));
                        ben.put("b_codigopostal" + i, c.getString(5));
                        ben.put("b_localidade" + i, c.getString(6));
                        ben.put("b_morada" + i, c.getString(7));                        
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                proposta.put("beneficiario" + i, ben);
            }

它给出了一个内存不足的错误,我想那是因为我在主线程上运行它。你能给我一个帮助/一些代码来使用线程或异步任务来做吗?

4

2 回答 2

3

c.moveToNext();在你的While循环中使用。你Cursor正在运行无限。

于 2012-07-17T12:15:00.680 回答
0

使用类似这样的异步任务:

// You must provide types for the three generic parameters before the code will compile.          
// For more details, see http://developer.android.com/reference/android/os/AsyncTask.html 
 private class MoveOutOfUIthread extends AsyncTask<
                Params, // one or more values of this type are passed to doInBackground()
                Progress, // the type of the progress units published during background crunching.
                Result // the type of the result returned by doInBackground()
                > 
 {

         protected Integer doInBackground(Params... p1, p2, p3) {
             // your background task here
             Result result = new Result();
             return result;
         }

         protected void onPostExecute(Result r) {
             // this gets the object returned by doInBackground, and executes on the UI thread
         }
 }   

*像这样执行异步任务:*

new MoveOutOfUIthread().execute(p1, p2, p3);

传递参数不是代祷,你可以简单地这样做:

new MoveOutOfUIthread().execute();

注意:您不能在doInBackground. 您必须将代码放入onPreExecuteonPostExecute更改 UI。

更新 :

这是在后台线程中运行您的代码。根据您的 OutOfMemory 错误,我认为您应该c.moveToNext();在您的 while 循环中使用M Mohsin Naeem答案。

于 2012-07-17T12:20:18.320 回答