2016-09-04 85 views
1

我的Parse.com查詢速度太慢,下面的代碼是1個網絡呼叫。因此,我想在並行執行3個查詢:Parse.com查詢速度太慢,需要更快

  1. 查詢行0 - 200
  2. 查詢行201 - 400
  3. 查詢行401 - 500

這是當前的代碼:

public static void readBusShelters() { 

      ParseQuery<ParseObject> query = ParseQuery.getQuery(BusShelter.TABLE_NAME); 
      query.setLimit(500); 
      query.findInBackground(new FindCallback<ParseObject>() { 
       @Override 
       public void done(List<ParseObject> list, ParseException e) { 

       } 
      }); 
    } 

一些幫助將不勝感激!

回答

1

使用回調將解析查詢包裝在AsyncTask中,並在線程池上執行以使任務能夠並行運行。

實施例:

public class MainActivity extends AppCompatActivity implements OnTaskCompleted { 

    @Override 
    public void onTaskCompleted(List<ParseObject> response) { 

    } 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); 
    setSupportActionBar(toolbar); 


    new FetchParseQueryTask(MainActivity.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, new PagingOptions(0, 200)); 
    new FetchParseQueryTask(MainActivity.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, new PagingOptions(1, 200)); 
    new FetchParseQueryTask(MainActivity.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, new PagingOptions(2, 200)); 
    } 
} 

回調:

public interface OnTaskCompleted { 
    void onTaskCompleted(List<ParseObject> response); 
} 

樣品實施FetchParseQueryTask類:

public class FetchParseQueryTask extends AsyncTask<PagingOptions, Void, List<ParseObject>> { 

    private OnTaskCompleted mTaskCompleted; 

    public FetchParseQueryTask(OnTaskCompleted activityContext){ 
    mTaskCompleted = activityContext; 
    } 

    @Override 
    protected List<ParseObject> doInBackground(PagingOptions... params) { 
    PagingOptions pagingOptions = params[0]; 
    ParseQuery<ParseObject> query = ParseQuery.getQuery("TABLE_NAME"); 

    query.setLimit(pagingOptions.getLimit()); 
    query.setSkip(pagingOptions.getPage() * pagingOptions.getLimit()); 

    try { 
     return query.find(); 
    } catch (ParseException e) { 
     e.printStackTrace(); 
    } 
    return null; 
    } 

    protected void onPostExecute(List<ParseObject> result) { 
    super.onPostExecute(result); 

    if (mTaskCompleted != null) { 
     mTaskCompleted.onTaskCompleted(result); 
    } 
    } 
} 

PagingOptions類:

public class PagingOptions { 

    private int mPage; 

    private int mLimit; 

    public PagingOptions(int page, int limit) 
    { 
    mPage = page; 
    mLimit = limit; 
    } 

    public int getPage() { 
    return mPage; 
    } 

    public void setPage(int mPage) { 
    this.mPage = mPage; 
    } 

    public int getLimit() { 
    return mLimit; 
    } 

    public void setLimit(int mLimit) { 
    this.mLimit = mLimit; 
    } 
} 
+0

親愛的克萊夫,非常感謝。我添加了一個帶有回調的構造函數到FetchParseQueryTask來獲得結果。這是正確的,對嗎? –

+0

是的,我已經用示例回調更新了答案 –

相關問題