private void getInfoFromServer() {
    DescriptionCallBack callBack = new DescriptionCallBack(this, getActivity());
    Call<DescriptionData> call =
        LykkeApplication_.getInstance()
            .getRestApi()
            .getDescription(
                Constants.PART_AUTHORIZATION + userPref.authToken().get(),
                Constants.USER_AGENT,
                assetPair.getId());
    call.enqueue(callBack);

    Call<OneAssetPairData> callAssetPair =
        LykkeApplication_.getInstance()
            .getRestApi()
            .getAssetPair(Constants.USER_AGENT, assetPair.getId());
    callAssetPair.enqueue(
        new Callback<OneAssetPairData>() {
          @Override
          public void onResponse(Call<OneAssetPairData> call, Response<OneAssetPairData> response) {
            assetPair = response.body().getResult().getAssetPairs();
            initViews();
          }

          @Override
          public void onFailure(Call<OneAssetPairData> call, Throwable t) {}
        });
  }
  private void loadMore() {
    if (nextPageUrl == null || nextPageUrl.isEmpty() || swipeRefreshLayout.isRefreshing()) {
      return;
    }
    swipeRefreshLayout.setRefreshing(true);
    Call<Reviews> newCall = service.getReviews(String.valueOf(currentPage + 1));
    newCall.enqueue(
        new Callback<Reviews>() {
          @Override
          public void onResponse(Response<Reviews> response) {
            if (!response.isSuccess()) {
              Toast.makeText(getContext(), "错误码:" + response.code(), Toast.LENGTH_SHORT).show();
              return;
            }
            Reviews reviews = response.body();
            currentPage = reviews.getCurrent_page();
            nextPageUrl = reviews.getNext_page_url();
            adapter.addAll(reviews.getData());
            swipeRefreshLayout.setRefreshing(false);
          }

          @Override
          public void onFailure(Throwable t) {
            swipeRefreshLayout.setRefreshing(false);
          }
        });
  }
  @Override
  protected void load() {
    swipeRefreshLayout.setRefreshing(true);
    Call<Reviews> reviewsCall = service.getReviews(null);
    reviewsCall.enqueue(
        new Callback<Reviews>() {
          @Override
          public void onResponse(Response<Reviews> response) {
            if (!response.isSuccess()) {
              Toast.makeText(getContext(), "错误码:" + response.code(), Toast.LENGTH_SHORT).show();
              return;
            }
            Reviews reviews = response.body();
            currentPage = reviews.getCurrent_page();
            nextPageUrl = reviews.getNext_page_url();
            adapter.reset(reviews.getData());
            swipeRefreshLayout.setRefreshing(false);
          }

          @Override
          public void onFailure(Throwable t) {
            swipeRefreshLayout.setRefreshing(false);
          }
        });
  }
  public void testDirectionAsyncQuery() throws IOException {
    Retrofit retrofit =
        new Retrofit.Builder()
            .baseUrl(MapApiService.API_URL)
            .addConverterFactory(GsonConverterFactory.create())
            .build();
    MapApiService.DirectionApi directionApi = retrofit.create(MapApiService.DirectionApi.class);
    String key = mContext.getString(R.string.google_maps_server_key);
    String origin = "place_id:ChIJAx7UL8xyhlQR86Iqc-fUncc";
    String destination = "place_id:ChIJNbea5OF2hlQRDfHhEXerrAM";
    Call<MapApiService.TransitRoutes> call = directionApi.getDirections(origin, destination, key);

    call.enqueue(
        new Callback<MapApiService.TransitRoutes>() {
          @Override
          public void onResponse(
              Call<MapApiService.TransitRoutes> call,
              Response<MapApiService.TransitRoutes> response) {
            if (response.isSuccess()) {
              MapApiService.TransitRoutes transitRoutes = response.body();
              assertTrue(
                  LOG_TAG + ": retrofit query direction status return: " + transitRoutes.status,
                  transitRoutes.status.equals("OK"));
            }
          }

          @Override
          public void onFailure(Call<MapApiService.TransitRoutes> call, Throwable t) {
            Timber.d("Error %s", t.getMessage());
          }
        });
  }
Exemplo n.º 5
0
 /**
  * Put complex types with array property which is empty.
  *
  * @param complexBody Please put an empty array
  * @param serviceCallback the async ServiceCallback to handle successful and failed responses.
  * @throws IllegalArgumentException thrown if callback is null
  * @return the {@link Call} object
  */
 public ServiceCall putEmptyAsync(
     ArrayWrapper complexBody, final ServiceCallback<Void> serviceCallback)
     throws IllegalArgumentException {
   if (serviceCallback == null) {
     throw new IllegalArgumentException("ServiceCallback is required for async calls.");
   }
   if (complexBody == null) {
     serviceCallback.failure(
         new IllegalArgumentException("Parameter complexBody is required and cannot be null."));
     return null;
   }
   Validator.validate(complexBody, serviceCallback);
   Call<ResponseBody> call = service.putEmpty(complexBody);
   final ServiceCall serviceCall = new ServiceCall(call);
   call.enqueue(
       new ServiceResponseCallback<Void>(serviceCallback) {
         @Override
         public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
           try {
             serviceCallback.success(putEmptyDelegate(response));
           } catch (ErrorException | IOException exception) {
             serviceCallback.failure(exception);
           }
         }
       });
   return serviceCall;
 }
 /**
  * POST method with subscriptionId modeled in credentials. Set the credential subscriptionId to
  * '1234-5678-9012-3456' to succeed.
  *
  * @param serviceCallback the async ServiceCallback to handle successful and failed responses.
  * @throws IllegalArgumentException thrown if callback is null
  * @return the {@link Call} object
  */
 public ServiceCall postSwaggerGlobalValidAsync(final ServiceCallback<Void> serviceCallback)
     throws IllegalArgumentException {
   if (serviceCallback == null) {
     throw new IllegalArgumentException("ServiceCallback is required for async calls.");
   }
   if (this.client.getSubscriptionId() == null) {
     serviceCallback.failure(
         new IllegalArgumentException(
             "Parameter this.client.getSubscriptionId() is required and cannot be null."));
     return null;
   }
   Call<ResponseBody> call =
       service.postSwaggerGlobalValid(
           this.client.getSubscriptionId(), this.client.getAcceptLanguage());
   final ServiceCall serviceCall = new ServiceCall(call);
   call.enqueue(
       new ServiceResponseCallback<Void>(serviceCallback) {
         @Override
         public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
           try {
             serviceCallback.success(postSwaggerGlobalValidDelegate(response));
           } catch (ErrorException | IOException exception) {
             serviceCallback.failure(exception);
           }
         }
       });
   return serviceCall;
 }
Exemplo n.º 7
0
  public static boolean verify(final Context context, final String username, String password) {

    boolean verifyResult = false;
    final ATIPUser user = new ATIPUser();
    user.setUserName(username);
    user.setPwd(password);

    ATIPRestInterface service = ATIPRestService.getInstance(context);

    Call<Boolean> call = service.verify(user);
    call.enqueue(
        new Callback<Boolean>() {
          @Override
          public void onResponse(Call<Boolean> call, Response<Boolean> response) {
            if (response.body()) {
              login(context, username);
            }
          }

          @Override
          public void onFailure(Call<Boolean> call, Throwable t) {
            Log.v("LoginUtils", t.getMessage());
          }
        });

    return verifyResult;
  }
  public void getLeague(int leagueId) {
    Call<SoccerSeason> call = mApiService.getSoccerSeason(leagueId);
    call.enqueue(
        new Callback<SoccerSeason>() {
          @Override
          public void onResponse(
              Call<SoccerSeason> call, retrofit2.Response<SoccerSeason> response) {
            int statusCode = response.code();

            Log.d(LOG_TAG, "getLeague statusCode #" + statusCode);

            if (statusCode != 200) {
              return;
            }
            SoccerSeason season = response.body();
            mContext
                .getContentResolver()
                .insert(AppProvider.Seasons.withId(season.getId()), season.getContentValues());
            Log.d(LOG_TAG, "getLeague Complete league ID: " + season.getId());
            updateWidgets(mContext);
          }

          @Override
          public void onFailure(Call<SoccerSeason> call, Throwable t) {
            // Log error here since request failed
            // TODO log unable fetch league
            Log.e(LOG_TAG, "getLeague onFailure", t);
          }
        });
  }
  public void getTeam(final int teamId) {
    Call<Team> call = mApiService.getTeam(teamId);
    call.enqueue(
        new Callback<Team>() {
          @Override
          public void onResponse(Call<Team> call, retrofit2.Response<Team> response) {
            int statusCode = response.code();
            Log.d(LOG_TAG, "getTeam statusCode #" + statusCode);
            if (statusCode != 200) {
              return;
            }
            Team team = response.body();
            if (team.getCrestUrl().length() > 0) {
              GlideHelper.preloadTeamCrest(mContext, mHttpClient, team.getCrestUrl(), team.getId());

              File internalFile = mContext.getFileStreamPath("crestTeam" + teamId + ".png");
              Uri internal = Uri.fromFile(internalFile);
              team.setCrestUrl(internal.toString());
            }

            mContext
                .getContentResolver()
                .insert(AppProvider.Teams.withId(team.getId()), team.getContentValues());
            Log.d(LOG_TAG, "getTeam Complete team ID: " + team.getId());
            updateWidgets(mContext);
          }

          @Override
          public void onFailure(Call<Team> call, Throwable t) {
            // Log error here since request failed
            // TODO log unable fetch league
            Log.e(LOG_TAG, "getTeam onFailure", t);
          }
        });
  }
  public void fetchFixtures(String timeFrame, String league) {
    Map<String, String> options = new HashMap<>();
    options.put(QUERY_TIME_FRAME, timeFrame);
    if (league != null) {
      options.put(QUERY_LEAGUE, league);
    }
    Call<FixtureCollection> call = mApiService.getFixtures(options);

    call.enqueue(
        new Callback<FixtureCollection>() {
          @Override
          public void onResponse(
              Call<FixtureCollection> call, retrofit2.Response<FixtureCollection> response) {
            int statusCode = response.code();
            Log.d(LOG_TAG, "fetchFixtures statusCode #" + statusCode);

            if (statusCode != 200) {
              // TODO set status
              return;
            }

            FixtureCollection fixtureCollection = response.body();
            Log.d(LOG_TAG, "Count #" + fixtureCollection.getCount());
            Log.d(LOG_TAG, "Time Frame Start " + fixtureCollection.getTimeFrameStart());
            Log.d(LOG_TAG, "Time Frame End " + fixtureCollection.getTimeFrameEnd());

            Vector<ContentValues> values = new Vector<>(fixtureCollection.getFixtures().size());
            for (Fixture fixture : fixtureCollection.getFixtures()) {
              try {
                values.add(fixture.getContentValues());
                Log.v(LOG_TAG, fixture.getContentValues().toString());
              } catch (ParseException e) {
                e.printStackTrace();
              }
            }
            int inserted_data;
            ContentValues[] insert_data = new ContentValues[values.size()];
            values.toArray(insert_data);
            inserted_data =
                mContext
                    .getContentResolver()
                    .bulkInsert(AppProvider.Fixtures.CONTENT_URI, insert_data);
            Log.i(LOG_TAG, "fetchMovieItems Complete. " + inserted_data + " Inserted");

            // fetch look up data
            LookupSyncAdapter.syncNow(mContext);
            updateWidgets(mContext);
          }

          @Override
          public void onFailure(Call<FixtureCollection> call, Throwable t) {
            // Log error here since request failed
            Log.e(LOG_TAG, "fetchFixtures onFailure", t);
          }
        });
  }
Exemplo n.º 11
0
 private void getRates() {
   if (isShouldContinue) {
     AssetPairRateCallBack callBack = new AssetPairRateCallBack(this, getActivity());
     Call<RateData> call =
         LykkeApplication_.getInstance()
             .getRestApi()
             .getAssetPairsRate(
                 Constants.PART_AUTHORIZATION + userPref.authToken().get(),
                 Constants.USER_AGENT,
                 assetPair.getId());
     call.enqueue(callBack);
   }
 }
Exemplo n.º 12
0
  private void doInscri(
      String firstNameValue, String lastNameValue, String emailValue, String passwordValue) {
    hideButton();
    progressBar.setVisibility(View.VISIBLE);
    // github sign in
    Call<ResponseBody> call =
        gitHubService.storeUser(firstNameValue, lastNameValue, emailValue, passwordValue);
    Log.d("user", firstNameValue + " " + lastNameValue + " " + emailValue + " " + passwordValue);
    call.enqueue(
        new Callback<ResponseBody>() {
          @Override
          public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
            progressBar.setVisibility(View.GONE);
            JSONObject jsonObject = null;
            User user = null;
            try {
              jsonObject = new JSONObject(response.body().string());
              String result = jsonObject.getString("success");
              if (result.equals("User exist")) {
                email.setError("User email exist !");
                emailConfirmed.getEditText().setText("");
                email.requestFocus();
                mdperreur();
              } else {
                JSONObject userJson = jsonObject.getJSONObject("user");
                user =
                    new User(
                        userJson.getString("id_User"),
                        userJson.getString("login"),
                        userJson.getString("nom") + " " + userJson.getString("prenom"));
                AuthUtils.saveUser(InscriptionActivity.this, user);
                succ();
              }
            } catch (JSONException | IOException | NullPointerException e) {
              e.printStackTrace();
              mdperreur();
            }
            // AuthUtils.saveToken(InscriptionActivity.this, token);
            AuthUtils.saveUser(InscriptionActivity.this, user);
            Log.d("success", "last one");
          }

          @Override
          public void onFailure(Call<ResponseBody> call, Throwable t) {
            progressBar.setVisibility(View.GONE);
            Toast.makeText(InscriptionActivity.this, "Unable to conenect", Toast.LENGTH_SHORT)
                .show();
            mdperreur();
          }
        });
  }
Exemplo n.º 13
0
  @AfterViews
  public void afterViews() {
    Call<AppInfoData> call = LykkeApplication_.getInstance().getRestApi().getAppInfo();
    ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);

    NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
    boolean isConnected = false;
    if (activeNetwork == null) {
      isConnected = false;
    } else {
      isConnected = activeNetwork.isConnectedOrConnecting();
    }
    if (isConnected) {
      call.enqueue(
          new Callback<AppInfoData>() {
            @Override
            public void onResponse(Call<AppInfoData> call, Response<AppInfoData> response) {
              AppInfoResult.setInstance(response.body().getResult());
              new Handler()
                  .postDelayed(
                      new Runnable() {
                        @Override
                        public void run() {
                          if (userPref.authToken().get().isEmpty()) {
                            Intent intent = new Intent();
                            intent.setClass(getApplicationContext(), SignInActivity_.class);
                            startActivity(intent);
                            finish();
                          } else {
                            Intent intent = new Intent();
                            intent.setClass(getApplicationContext(), RestoreActivity_.class);
                            finish();
                            startActivity(intent);
                          }
                        }
                      },
                      Constants.DELAY_500);
            }

            @Override
            public void onFailure(Call<AppInfoData> call, Throwable t) {}
          });
    } else {
      Intent intent = new Intent();
      intent.setClass(getApplicationContext(), SignInActivity_.class);
      startActivity(intent);
      finish();
    }
  }
Exemplo n.º 14
0
  public void onPokemonClicked(int pokeNum) {
    final Call<Pokemon> pokeCall = pokeApiService.getPokemon(pokeNum);
    pokeCall.enqueue(
        new Callback<Pokemon>() {
          @Override
          public void onResponse(Call<Pokemon> call, Response<Pokemon> response) {
            final Pokemon pokemon = response.body();
            mListener.onPokemonSelected(pokemon);
          }

          @Override
          public void onFailure(Call<Pokemon> call, Throwable t) {
            t.getCause();
          }
        });
  }
  public void onLogin(View view) throws InterruptedException {

    rotateLoading.start();

    String login = email.getText().toString().isEmpty() ? " " : email.getText().toString();
    String password = pass.getText().toString().isEmpty() ? " " : pass.getText().toString();

    Call<LoginResponse> call = API.login(login, password);

    call.enqueue(
        new Callback<LoginResponse>() {

          @Override
          public void onResponse(Call<LoginResponse> call, Response<LoginResponse> response) {
            Log.d("loginresponse", String.valueOf(response.body()));
            LoginResponse loginresponse = response.body();
            if (loginresponse.success()) {

              Log.d("loginresponse.getId()", String.valueOf(loginresponse.getId()));

              SharedPreferences.Editor editor = mSettings.edit();
              editor.putBoolean(APP_PREFERENCES_AUTH, true);
              editor.putInt(APP_PREFERENCES_UID, loginresponse.getId());
              editor.apply();

              Intent intent = new Intent(MainActivity.this, LanguagesActivity.class);
              startActivity(intent);
            } else {
              rotateLoading.stop();
              Toast toast =
                  Toast.makeText(
                      getApplicationContext(), "Неправильный логин или пароль", Toast.LENGTH_LONG);
              toast.show();
            }
          }

          @Override
          public void onFailure(Call<LoginResponse> call, Throwable t) {
            Log.d("onFailureLogin", "onFailureLogin");
            rotateLoading.stop();
            Toast toast =
                Toast.makeText(
                    getApplicationContext(), "Неправильный логин или пароль", Toast.LENGTH_LONG);
            toast.show();
          }
        });
  }
  @Override
  public int onStartCommand(Intent intent, int flags, int startId) {

    if (intent == null) {
      Log.d(this, "Oh noes, intent is null");
    }
    mAllWidgetIds = intent.getIntArrayExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS);

    mContext = this;

    Log.d(this, "About to call radar");
    MetClient client = ServiceGenerator.createService(MetClient.class);
    Call<Radar> call = client.getRadar();
    call.enqueue(this);

    return super.onStartCommand(intent, flags, startId);
  }
Exemplo n.º 17
0
  public static void login(Context context, String username) {

    ATIPRestInterface service = ATIPRestService.getInstance(context);

    Call<ATIPUser> call = service.getUserByUsername(username);
    call.enqueue(
        new Callback<ATIPUser>() {
          @Override
          public void onResponse(Call<ATIPUser> call, Response<ATIPUser> response) {
            ATIPUser user = response.body();
            SessionUser.getInstance().setUser(user);
          }

          @Override
          public void onFailure(Call<ATIPUser> call, Throwable t) {
            Log.v("LoginUtils", t.getMessage());
          }
        });
  }
  @Override
  public void onViewCreated(View view, Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);
    if (savedInstanceState == null && mQueryResult == null) {
      RequestBody shopId =
          RequestBody.create(MediaType.parse("multipart/form-data"), String.valueOf(getShopId()));
      File imageFile = new File(mImageFileName);
      File scaledImageDir = new File(imageFile.getParentFile(), "downsized");
      File f = new File(scaledImageDir, imageFile.getName());
      //            File f = new File(mImageFileName);
      RequestBody file = RequestBody.create(MediaType.parse("multipart/form-data"), f);
      String str = FileUtils.readTextFile(new File(mImageMetaFileName));
      str = "{\"image\": {\"meta\": " + str + "}}";
      RequestBody json = RequestBody.create(MediaType.parse("multipart/form-data"), str);
      Call<ImageQueryResult> call =
          RestClient.getSharedInstance().getApiService().getAnnotationsOnImage(file, shopId, json);
      mProgressDialog = new ProgressDialog(getActivity(), R.style.AppTheme_Dark_Dialog);
      mProgressDialog.setIndeterminate(true);
      mProgressDialog.setMessage("Searching...");
      mProgressDialog.show();
      call.enqueue(
          new Callback<ImageQueryResult>() {
            @Override
            public void onResponse(
                Call<ImageQueryResult> call, Response<ImageQueryResult> response) {
              mProgressDialog.hide();
              mQueryResult = response.body();
              mAnnotationList.clear();
              mAnnotationList.addAll(mQueryResult.annotations);
              mAnnotationAdaptor.notifyDataSetChanged();
              mLinearLayoutManager.scrollToPosition(3);
              drawAnnotations();
            }

            @Override
            public void onFailure(Call<ImageQueryResult> call, Throwable t) {
              mProgressDialog.hide();
              Toast.makeText(getActivity(), "Failed to fetch annotations.", Toast.LENGTH_LONG)
                  .show();
            }
          });
    }
  }
Exemplo n.º 19
0
  @Override
  public void loadMore(int page) {
    init();
    final Call<AndroidData> androidDataCall = mGankioService.getAndroidData(page);
    androidDataCall.enqueue(
        new Callback<AndroidData>() {
          @Override
          public void onResponse(Call<AndroidData> call, Response<AndroidData> response) {
            mAndroidData = response.body();
            setAvatarUrlAndShow(mAndroidData);
          }

          @Override
          public void onFailure(Call<AndroidData> call, Throwable t) {
            mGankView.finishRefresh();
            mGankView.showSnackBar();
          }
        });
  }
Exemplo n.º 20
0
 /**
  * Get complex types with array property.
  *
  * @param serviceCallback the async ServiceCallback to handle successful and failed responses.
  * @throws IllegalArgumentException thrown if callback is null
  * @return the {@link Call} object
  */
 public ServiceCall getValidAsync(final ServiceCallback<ArrayWrapper> serviceCallback)
     throws IllegalArgumentException {
   if (serviceCallback == null) {
     throw new IllegalArgumentException("ServiceCallback is required for async calls.");
   }
   Call<ResponseBody> call = service.getValid();
   final ServiceCall serviceCall = new ServiceCall(call);
   call.enqueue(
       new ServiceResponseCallback<ArrayWrapper>(serviceCallback) {
         @Override
         public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
           try {
             serviceCallback.success(getValidDelegate(response));
           } catch (ErrorException | IOException exception) {
             serviceCallback.failure(exception);
           }
         }
       });
   return serviceCall;
 }
  private void populateClubs() {
    Call<Clubs> call = service.getClubs();
    call.enqueue(
        new Callback<Clubs>() {
          @Override
          public void onResponse(Call<Clubs> call, Response<Clubs> response) {
            if (response.body() != null) {
              adapter.setClubs(response.body().getClubs());
              list.setAdapter(adapter);
            }
            swipeRefreshLayout.setRefreshing(false);
          }

          @Override
          public void onFailure(Call<Clubs> call, Throwable t) {
            Toast.makeText(getActivity(), "Failed!   " + t, Toast.LENGTH_SHORT).show();
            swipeRefreshLayout.setRefreshing(false);
          }
        });
  }
Exemplo n.º 22
0
  @Override
  public void onResume() {
    super.onResume();
    Call<MainFeed> mainFeedCall = reqCall.mainFeed(AppPreferences.getAccessToken());
    mainFeedCall.enqueue(
        new Callback<MainFeed>() {
          @Override
          public void onResponse(Call<MainFeed> call, Response<MainFeed> response) {

            mainFeed = response.body();
            getActivity()
                .getSupportLoaderManager()
                .initLoader(1, null, FeedFragment.this)
                .forceLoad();
          }

          @Override
          public void onFailure(Call<MainFeed> call, Throwable t) {}
        });
    mTracker.setScreenName("Feed Fragment");
    mTracker.send(new HitBuilders.ScreenViewBuilder().build());
  }
  /** <b>MUST BE CALLED FROM BACKGROUND THREAD</b> Uses {@link GceAuthController#getAuthHeader()} */
  @WorkerThread
  public void suggest(String teamKey, int year, String link, String deletehash) {
    String authHeader = mGceAuthController.getAuthHeader();
    ModelsMobileApiMessagesMediaSuggestionMessage message =
        buildSuggestionMessage(teamKey, year, link, deletehash);
    Call<ModelsMobileApiMessagesBaseResponse> request =
        mTeamMediaApi.suggestion(authHeader, message);
    request.enqueue(
        new Callback<ModelsMobileApiMessagesBaseResponse>() {
          @Override
          public void onResponse(
              Call<ModelsMobileApiMessagesBaseResponse> call,
              Response<ModelsMobileApiMessagesBaseResponse> response) {
            // TODO stuff
          }

          @Override
          public void onFailure(Call<ModelsMobileApiMessagesBaseResponse> call, Throwable t) {
            // TODO stuff
          }
        });
  }
Exemplo n.º 24
0
 /**
  * Gets the current usage count and the limit for the resources under the subscription.
  *
  * @param serviceCallback the async ServiceCallback to handle successful and failed responses.
  * @throws IllegalArgumentException thrown if callback is null
  * @return the {@link Call} object
  */
 public ServiceCall listAsync(final ServiceCallback<UsageListResultInner> serviceCallback)
     throws IllegalArgumentException {
   if (serviceCallback == null) {
     throw new IllegalArgumentException("ServiceCallback is required for async calls.");
   }
   if (this.client.subscriptionId() == null) {
     serviceCallback.failure(
         new IllegalArgumentException(
             "Parameter this.client.subscriptionId() is required and cannot be null."));
     return null;
   }
   if (this.client.apiVersion() == null) {
     serviceCallback.failure(
         new IllegalArgumentException(
             "Parameter this.client.apiVersion() is required and cannot be null."));
     return null;
   }
   Call<ResponseBody> call =
       service.list(
           this.client.subscriptionId(),
           this.client.apiVersion(),
           this.client.acceptLanguage(),
           this.client.userAgent());
   final ServiceCall serviceCall = new ServiceCall(call);
   call.enqueue(
       new ServiceResponseCallback<UsageListResultInner>(serviceCallback) {
         @Override
         public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
           try {
             serviceCallback.success(listDelegate(response));
           } catch (CloudException | IOException exception) {
             serviceCallback.failure(exception);
           }
         }
       });
   return serviceCall;
 }
Exemplo n.º 25
0
  public static void gatherFromAddress(
      String address, final OnLocationGathered onLocationGathered) {

    Call<JsonElement> parsed = GeocoderHelper.getService().parse(address);
    parsed.enqueue(
        new Callback<JsonElement>() {
          @Override
          public void onResponse(Response<JsonElement> response) {
            if (response.body() == null) {
              if (onLocationGathered != null) {
                onLocationGathered.onGathered(null);
              }

              return;
            }

            Location location = new Location();

            try {
              JsonObject json = response.body().getAsJsonObject();
              JsonObject result = json.getAsJsonArray("results").get(0).getAsJsonObject();
              JsonArray address = result.getAsJsonArray("address_components");

              for (int i = 0; i < address.size(); i++) {
                JsonObject obj = address.get(i).getAsJsonObject();
                JsonArray types = obj.getAsJsonArray("types");

                for (int j = 0; j < types.size(); j++) {
                  String type = types.get(j).getAsString();

                  if (type.equals("street_number")) {
                    location.number = obj.get("long_name").getAsString();
                    break;
                  } else if (type.equals("route")) {
                    location.street = obj.get("long_name").getAsString();
                    break;
                  } else if (type.equals("postal_code")) {
                    location.zipCode = obj.get("long_name").getAsString();
                    break;
                  }
                }
              }

              JsonObject geometry = result.getAsJsonObject("geometry");
              JsonObject loc = geometry.getAsJsonObject("location");

              location.latitude = loc.get("lat").getAsDouble();
              location.longitude = loc.get("lng").getAsDouble();
            } catch (Exception e) {
              e.printStackTrace();
            }

            if (onLocationGathered != null) {
              onLocationGathered.onGathered(location);
            }
          }

          @Override
          public void onFailure(Throwable t) {
            if (onLocationGathered != null) {
              onLocationGathered.onGathered(null);
            }
          }
        });
  }
Exemplo n.º 26
0
  @Override
  public View onCreateView(
      LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment_log, container, false);
    // set title
    switch (mCategoryId) {
      case 1:
        getActivity().setTitle(getString(R.string.fragment_me_log_login));
        break;
      case 2:
        getActivity().setTitle(getString(R.string.fragment_me_log_operation));
        break;
    }

    if (view instanceof RecyclerView) {
      Context context = view.getContext();
      RecyclerView recyclerView = (RecyclerView) view;
      if (mColumnCount <= 1) {
        recyclerView.setLayoutManager(new LinearLayoutManager(context));
      } else {
        recyclerView.setLayoutManager(new GridLayoutManager(context, mColumnCount));
      }
      // Divider between Items in RecyclerView.
      recyclerView.addItemDecoration(
          new DividerItemDecoration(getContext(), R.drawable.shape_divider));

      // set Adapter
      mListLog = new ArrayList<Log>();
      mLogRecyclerViewAdapter = new LogRecyclerViewAdapter(mListLog);
      recyclerView.setAdapter(mLogRecyclerViewAdapter);

      // request for log data. set dataset for RecyclerViewAdapater.
      User user = (User) GlobalData.getObjectForKey("user");
      LogService logService =
          ServiceGenerator.createService(LogService.class, user.getName(), user.getPassword());
      Call<JSONApiObject> call = logService.getLog(user.getId(), mCategoryId);
      call.enqueue(
          new Callback<JSONApiObject>() {
            @Override
            public void onResponse(
                Call<JSONApiObject> call, retrofit2.Response<JSONApiObject> response) {
              List<Resource> resources = ResponseUtil.parseResponse(response, getContext());
              if (resources != null) {
                DateFormat dateParser = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
                DateFormat dateFormater = new SimpleDateFormat("yy-MM-dd HH:mm:ss");
                for (Resource resource : resources) {
                  Log log = (Log) resource;
                  // date translate
                  try {
                    Date date = dateParser.parse(log.getCreated());
                    log.setCreated(dateFormater.format(date));
                  } catch (ParseException e) {
                    System.out.println(e);
                  }
                  mListLog.add(log);
                }
                mLogRecyclerViewAdapter.notifyDataSetChanged();
              }
            }

            @Override
            public void onFailure(Call<JSONApiObject> call, Throwable t) {
              Toast.makeText(getContext(), R.string.error_network, Toast.LENGTH_SHORT).show();
              System.out.println(t.getMessage());
            }
          });
    }
    return view;
  }
Exemplo n.º 27
0
  @Override
  public void onResume() {
    ConnectionDetector cd = new ConnectionDetector(getActivity());
    if (!cd.isConnectingToInternet()) {
      Intent intent = new Intent();
      intent.setClass(getActivity(), NoInternetActivity.class);
      intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
      startActivity(intent);
    }
    pDialog.show();
    paused = false;
    String key = b.getString(Constants.MOVIE_URL_API_KEY);
    topRatedMovies = ApiClientMoviedb.getInterface().getTopRatedMovie(key);
    topRatedMovies.enqueue(
        new Callback<Movie>() {
          @Override
          public void onResponse(Call<Movie> call, Response<Movie> response) {
            if (response.isSuccessful()) {
              Movie movie = response.body();
              MovieLinearLayoutFragment mf = new MovieLinearLayoutFragment();
              Bundle b = new Bundle();
              b.putSerializable(Constants.MOVIE_TO_LINEAR_LAYOUT_FRAGMENT, movie);
              mf.setArguments(b);
              if (paused == false)
                getFragmentManager()
                    .beginTransaction()
                    .replace(R.id.frameLayoutTopRatedMovies, mf)
                    .commit();
            } else {
              Toast.makeText(getActivity(), response.code() + response.message(), Toast.LENGTH_LONG)
                  .show();
            }
            b1 = true;
            if (b2) pDialog.dismiss();
          }

          @Override
          public void onFailure(Call<Movie> call, Throwable t) {
            // Toast.makeText(getActivity(), "You are not connected to Internet",
            // Toast.LENGTH_LONG).show();
            b1 = true;
            if (b2) pDialog.dismiss();
          }
        });

    popularMovies = ApiClientMoviedb.getInterface().getPopularMovie(key);
    popularMovies.enqueue(
        new Callback<Movie>() {
          @Override
          public void onResponse(Call<Movie> call, Response<Movie> response) {
            if (response.isSuccessful()) {
              Movie movie = response.body();
              MovieLinearLayoutFragment mf = new MovieLinearLayoutFragment();
              Bundle b = new Bundle();
              b.putSerializable(Constants.MOVIE_TO_LINEAR_LAYOUT_FRAGMENT, movie);
              mf.setArguments(b);
              if (paused == false)
                getFragmentManager()
                    .beginTransaction()
                    .replace(R.id.frameLayoutPopularMovies, mf)
                    .commit();
            } else {
              Toast.makeText(getActivity(), response.code() + response.message(), Toast.LENGTH_LONG)
                  .show();
            }
            b2 = true;
            if (b1) pDialog.dismiss();
          }

          @Override
          public void onFailure(Call<Movie> call, Throwable t) {
            // Toast.makeText(getActivity(), "You are not connected to Internet",
            // Toast.LENGTH_LONG).show();
            b2 = true;
            if (b1) pDialog.dismiss();
          }
        });
    super.onResume();
  }