Android Retrofit + ProgressDialog在获取大数据时冻结

时间:2016-09-29 10:15:47

标签: android retrofit android-contentprovider retrofit2

我创建了一个有100k +记录的api。我已经完成了我的工作,每个请求获得数万个记录块。

根据逻辑部分如果我得到 flag = true 它将再次发送请求。

CODE:

创建ProgressDialog:

/**
 * First Sync Progressbar
 */
progressDialog = new ProgressDialog(NavigationActivity.this);
progressDialog.setTitle("Please wait...");
progressDialog.setMessage("Synchronizing...");
progressDialog.setCancelable(false);

首次同步功能:

private void doFirstSync(final String authToken) {
    try {

        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (progressDialog != null && !progressDialog.isShowing())
                    progressDialog.show();
            }
        });

        Cursor tableCursor = getContentResolver().query(KOOPSContentProvider.CONTENT_URI_TABLES, null, null, null, null);

        JSONArray array = new JSONArray();

        if (tableCursor != null) {

            JSONObject object = new JSONObject();

            if (tableCursor.getCount() > 0) {
                while (tableCursor.moveToNext()) {

                    object.put(TTables.TABLE_NAME,
                            tableCursor.getString(tableCursor.getColumnIndex(TABLE_NAME)));
                    object.put(TTables.TABLE_UTP,
                            tableCursor.isNull(tableCursor.getColumnIndex(TABLE_UTP)) ? ""
                                    : tableCursor.getString(tableCursor.getColumnIndex(TABLE_UTP)));
                    object.put(TTables.TABLE_LAST_ID,
                            tableCursor.isNull(tableCursor.getColumnIndex(TABLE_LAST_ID)) ? ""
                                    : tableCursor.getString(tableCursor.getColumnIndex(TABLE_LAST_ID)));

                    array.put(object);
                    object = new JSONObject();
                }
            }

            Log.d(TAG, "Array of Table : " + array.toString());

            tableCursor.close();
        }

        firstSyncCall = retrofitInterfaces.firstSync(authToken, array.toString(), KOOPS.getDeviceId(getApplicationContext()));
        firstSyncCall.enqueue(new MyCallback<FirstSync>(NavigationActivity.this) {
            @Override
            public void onSuccess(final FirstSync firstSync) {

                boolean isSendAgain = firstSync.getFlag();

                /**
                 * Start Time
                 */
                long lStartTime = new Date().getTime();

                /**
                 *
                 * Getting Tables Array and based on this will
                 * get data from all tables
                 *
                 */
                List<Table> tables = firstSync.getTables();

                /**** FIRST SYNC ****/
                for (int tableIndex = 0; tableIndex < tables.size(); tableIndex++) {

                    String tableName = tables.get(tableIndex).getName();
                    String tableUTP = tables.get(tableIndex).getUtp();
                    int tableLastID = tables.get(tableIndex).getLastId();

                    switch (tableName) {
                        case TProductCategory.TABLE_PRODUCT_CATEGORY:
                            /** Product Category **/
                            List<ProductCategory> productCategory = firstSync.getData().getProductCategory();

                            int productCategorySize = productCategory.size();
                            Log.d(TAG, "Product Category Size : " + productCategorySize);
                            if (productCategorySize > 0) {
                                ContentValues[] productCategoryContentValues = new ContentValues[productCategorySize];
                                for (int pIndex = 0; pIndex < productCategorySize; pIndex++) {
                                    productCategoryContentValues[pIndex] = productCategory.get(pIndex).getContentValues();
                                }
                                getContentResolver().bulkInsert(KOOPSContentProvider.CONTENT_URI_PRODUCT_CATEGORY, productCategoryContentValues);
                                Log.d(TAG, "Product Category Inserted..." + productCategorySize);
                            }
                            break;
                        case TProduct.TABLE_PRODUCT:
                            /**
                             * Product Insert
                             */
                            List<Product> products = firstSync.getData().getProduct();
                            int productSize = products.size();
                            Log.d(TAG, "Product Size : " + productSize);
                            if (productSize > 0) {
                                ContentValues[] productContentValues = new ContentValues[productSize];
                                for (int pIndex = 0; pIndex < productSize; pIndex++) {
                                    productContentValues[pIndex] = products.get(pIndex).getContentValues();
                                }
                                getContentResolver().bulkInsert(KOOPSContentProvider.CONTENT_URI_PRODUCT, productContentValues);
                                Log.d(TAG, "Product Inserted..." + productSize);
                            }
                            break;
                        case TProductUnit.TABLE_PRODUCT_UNIT:
                            /**
                             * Product Unit
                             */
                            List<ProductUnit> productUnit = firstSync.getData().getProductUnit();

                            int productUnitSize = productUnit.size();
                            Log.d(TAG, "Product Unit Size : " + productUnitSize);
                            if (productUnitSize > 0) {
                                ContentValues[] productUnitContentValues = new ContentValues[productUnitSize];
                                for (int pIndex = 0; pIndex < productUnitSize; pIndex++) {
                                    productUnitContentValues[pIndex] = productUnit.get(pIndex).getContentValues();
                                }
                                getContentResolver().bulkInsert(KOOPSContentProvider.CONTENT_URI_PRODUCT_UNIT, productUnitContentValues);
                                Log.d(TAG, "Product Unit Inserted..." + productUnitSize);
                            }
                            break;
                        case TProductImage.TABLE_PRODUCT_IMAGE:
                            /**
                             * Product Image Insert
                             */
                            List<ProductImage> productsImages = firstSync.getData().getProductImages();
                            int productImageSize = productsImages.size();
                            Log.d(TAG, "Product Image Size : " + productImageSize);
                            if (productImageSize > 0) {
                                ContentValues[] productImageContentValues = new ContentValues[productImageSize];
                                for (int pIndex = 0; pIndex < productImageSize; pIndex++) {
                                    productImageContentValues[pIndex] = productsImages.get(pIndex).getContentValues();
                                }
                                getContentResolver().bulkInsert(KOOPSContentProvider.CONTENT_URI_PRODUCT_IMAGES, productImageContentValues);
                                Log.d(TAG, "Product Image Inserted..." + productImageSize);
                            }
                            break;
                        case TProductDescription.TABLE_PRODUCT_DESCRIPTION:
                            /**
                             * Product Description Insert
                             */
                            List<ProductDescription> productDescription = firstSync.getData().getProductDescription();
                            int productDescSize = productDescription.size();
                            Log.d(TAG, "Product Desc Size : " + productDescSize);
                            if (productDescSize > 0) {
                                ContentValues[] productDescContentValues = new ContentValues[productDescSize];
                                for (int pIndex = 0; pIndex < productDescSize; pIndex++) {
                                    productDescContentValues[pIndex] = productDescription.get(pIndex).getContentValues();
                                }
                                getContentResolver().bulkInsert(KOOPSContentProvider.CONTENT_URI_PRODUCT_DESC, productDescContentValues);
                                Log.d(TAG, "Product Desc Inserted..." + productDescSize);
                            }
                            break;
                    }

                    /**
                     * Update Tables.... with UTP and Last ID
                     */
                    ContentValues tableValues = new ContentValues();

                    if (tableLastID == 0)
                        tableValues.putNull(TABLE_LAST_ID);
                    else
                        tableValues.put(TABLE_LAST_ID, tableLastID);

                    tableValues.put(TABLE_UTP, tableUTP);

                    getContentResolver().update(
                            KOOPSContentProvider.CONTENT_URI_TABLES,
                            tableValues,
                            TABLE_NAME + "=?",
                            new String[]{tableName});
                }

                long lEndTime = new Date().getTime();
                Log.d(TAG, "Taken Time : " + (lEndTime - lStartTime));

                if (isSendAgain) {
                    /**
                     * Sending Again for new Data
                     */
                    doFirstSync(authToken);
                } else {
                    /**
                     * Finally First Sync Over....
                     */
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            progressDialog.dismiss();
                        }
                    });
                }
            }

            @Override
            public void onFailure(Call<FirstSync> call, Throwable t) {
                super.onFailure(call, t);
                progressDialog.dismiss();
            }

            @Override
            public void onFailed(Call<FirstSync> call, Response<FirstSync> response) {
                super.onFailed(call, response);
                progressDialog.dismiss();
            }
        });
    } catch (Exception e) {
        LOGE("Error First Sync : " + e.getLocalizedMessage());
    }
}

RetrofitService:

public class RetrofitClient {

    public static final String BASE_URL = "my_url....";

    /**
     * Get Retrofit with config of Interceptor
     */
    public static Retrofit getRetrofit() {

        OkHttpClient.Builder httpClient = new OkHttpClient.Builder();

        if(Log.isLoggable(LogUtils.TAG, Log.DEBUG)) {
            HttpLoggingInterceptor logging = new HttpLoggingInterceptor();

            // set your desired log level
            logging.setLevel(HttpLoggingInterceptor.Level.BODY);

            // add logging as last interceptor
            httpClient.addInterceptor(logging);
        }

        httpClient.addInterceptor(new Interceptor() {
            @Override
            public Response intercept(Chain chain) throws IOException {
                Request original = chain.request();
                HttpUrl originalHttpUrl = original.url();

                HttpUrl url = originalHttpUrl.newBuilder()
                        .addQueryParameter("request_from", "custAppAnd")
                        .build();

                // Request customization: add request headers
                Request.Builder requestBuilder = original.newBuilder()
                        .url(url);

                Request request = requestBuilder.build();
                return chain.proceed(request);
            }
        });

        return new Retrofit.Builder()
                .baseUrl(BASE_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .client(httpClient.build())
                .build();
    }

    /**
     * Get API Service
     *
     * @return API Service
     */
    public static RetrofitInterfaces getApiService() {
        return getRetrofit().create(RetrofitInterfaces.class);
    }
}

enter image description here

我的JSON示例:

{
  "data": {
    "product_category": [
      {
        "id": 1,
        "name": "Category 1",
        "priority": 0,
        "is_saleable": 0,
        "is_purchasable": 0,
        "status": 0,
        "itp": "2016-09-20 14:55:55",
        "utp": "2016-09-21 12:22:53"
      }
    ],
    "product_unit": [
      {
        "id": 1,
        "name": "Liter",
        "status": 0,
        "itp": "2015-03-23 16:44:28",
        "utp": "2015-12-15 18:23:50"
      },
      {
        "id": 2,
        "name": "Kilogram",
        "status": 0,
        "itp": "2015-03-23 16:46:04",
        "utp": "2015-12-15 18:23:44"
      }
    ],
    "product": [
      {
        "id": 96,
        "name": "Product 96",
        "code": "PRO 96",
        "product_category_id": 4,
        "product_unit_id": 4,
        "priority": 0,
        "is_saleable": 0,
        "is_purchasable": 0,
        "is_new": 0,
        "status": 0,
        "itp": "2016-09-21 11:09:28",
        "utp": "2016-09-21 11:09:28",
        "rate": "25.00",
        "discount": "2.00",
        "offer_discount": "10.00"
      }
    ]
  },
  "tables": [
    {
      "name": "product_category",
      "utp": "2016-09-29 10:09:51",
      "last_id": 200
    },
    {
      "name": "product_unit",
      "utp": "2016-09-29 10:09:51",
      "last_id": 7
    },
    {
      "name": "product",
      "utp": "2016-09-29 10:09:52",
      "last_id": 236
    },
    {
      "name": "product_image",
      "utp": "2016-09-29 10:09:53",
      "last_id": 9688
    }
  ],
  "flag": true
}

问题:

  1. 在加载/获取/插入数据时冻结ProgerssBar。
  2. 使用ContentProvider *进行批量插入是否有其他最佳方法,因为插入10000条记录也需要150秒?

0 个答案:

没有答案