private void SetCounts() {
   int numRespondents = surveys.getRespondentList().size();
   int completedRespondents = dbAdapter.getCompletedRespondents(surveys.getId());
   incompleteCount = dbAdapter.getIncompleteResponse(surveys.getId());
   completeCount = dbAdapter.getCompleteResponse(surveys.getId());
   incompleteTv.setText(Integer.toString(incompleteCount + numRespondents - completedRespondents));
   completeTv.setText(Integer.toString(completeCount));
 }
  private void doTaskResponseUploading() {
    if (asynTaskCheck) {
      appController.showToast("Something went wrong , please try again");
      progressDialog.dismiss();
    } else {
      completedResponseIds = dbAdapter.getCompleteResponsesIds(surveyId);
      for (int i = 0; i < completedResponseIds.size(); i++) {
        answers = new ArrayList<>();
        completedResponseIds.get(i);
        answers = null;
        answers = dbAdapter.getAnswerByResponseId(completedResponseIds.get(i));
        String lat =
            dbAdapter.getLatitudeFromResponseIDAndSurveyID(completedResponseIds.get(i), surveyId);
        String lon =
            dbAdapter.getLongitudeFromResponseIDAndSurveyID(completedResponseIds.get(i), surveyId);
        JSONObject obj = new JSONObject();
        JSONObject localJsonObject = CommonUtil.getAnswerJsonObject(answers, dbAdapter);
        String mobilId =
            dbAdapter.getMobileIDFromResponseIDAndSurveyID(completedResponseIds.get(i), surveyId);
        try {
          obj.put("status", "complete");
          obj.put("survey_id", surveys.getId());
          obj.put("updated_at", timestamp);
          obj.put("longitude", lon);
          obj.put("latitude", lat);
          obj.put("user_id", appController.getPreferences().getUserId());
          obj.put("organization_id", appController.getPreferences().getOrganizationId());
          obj.put("access_token", appController.getPreferences().getAccessToken());
          obj.put("mobile_id", mobilId);
          obj.put("answers_attributes", localJsonObject);

        } catch (JSONException e) {
          e.printStackTrace();
        }

        new UploadResponse()
            .execute(
                localJsonObject.toString(),
                obj.toString(),
                surveys.getId() + "",
                timestamp,
                lat + "",
                lon + "",
                mobilId,
                completedResponseIds.get(i) + "");
      }
    }
  }
  public void generateRecordId() {

    for (int i = 0; i < completedResponseIds.size(); i++) {
      int responseId = completedResponseIds.get(i);
      Cursor localRecordCursor = dbAdapter.getRecordIdsByResponseId(responseId);
      localRecordCursor.moveToFirst();

      if (localRecordCursor.getCount() > 0) {
        for (int l = 0; l < localRecordCursor.getCount(); l++) {

          int webId =
              localRecordCursor.getInt(localRecordCursor.getColumnIndex(DBAdapter.DBhelper.WEB_ID));
          int recordId =
              localRecordCursor.getInt(localRecordCursor.getColumnIndex(DBAdapter.DBhelper.ID));
          int categoryId =
              localRecordCursor.getInt(
                  localRecordCursor.getColumnIndex(DBAdapter.DBhelper.CATEGORY_ID));
          if (webId == 0) {
            // default url
            Integer[] params = {categoryId, responseId, recordId};
            getWebIdFromServer(params);
          } else {
            // dynamic url
            Integer[] params = {categoryId, recordId, responseId};
            getWebIdFromServerCaseTwo(params);
          }
          localRecordCursor.moveToNext();
        }
      }

      localRecordCursor.close();
    }
  }
  public void getWebIdFromServerCaseTwo(Integer[] integer) {
    int webId;
    int responseId = integer[2];

    webId = integer[1];
    String recordsyncString = "";
    JSONObject jsonObject = new JSONObject();
    try {
      jsonObject.put("category_id", integer[0]);
    } catch (JSONException e) {
      e.printStackTrace();
    }
    HttpClient httpclient = new DefaultHttpClient();

    HttpPut httppost = new HttpPut(baseUrl + "/api/records/" + webId + ".json");
    // attributes for survey sync
    try {
      httppost.addHeader("access_token", appController.getPreferences().getAccessToken());
      httppost.setEntity(createStringEntity(jsonObject));
      HttpResponse httpResponse = httpclient.execute(httppost);
      HttpEntity httpEntity = httpResponse.getEntity();
      recordsyncString = EntityUtils.toString(httpEntity);

    } catch (UnsupportedEncodingException e) {
      e.printStackTrace();
    } catch (ClientProtocolException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }
    int recordId = jsonParser.parseRecordIdResult(recordsyncString);
    if (recordId != 0) {
      dbAdapter.updateRecordsTable(recordId, responseId);
      dbAdapter.updateAnswerTable(responseId, recordId, webId);
    } else {
      asynTaskCheck = true;
    }
  }
 @Override
 protected void onLocationReceived(Object parm) {
   if (getIntent().hasExtra(IntentConstants.SURVEY)) {
     responses.setSurveyId(surveys.getId());
     responses.setStatus("incomplete");
     responses.setMobileId(UUID.randomUUID().toString());
     responses.setLatitude(CommonUtil.getValidLatitude(appController));
     responses.setLongitude(CommonUtil.getValidLongitude(appController));
     Intent intent = new Intent(SurveyDetailsActivity.this, NewResponseActivity.class);
     intent.putExtra(IntentConstants.SURVEY, surveys);
     startActivity(intent);
   }
   dbAdapter.insertDataResponsesTable(responses);
   finish();
 }
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    enableLocation = true; // <- must be before super.onCreate
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_survey_details);
    actionBar = getActionBar();
    if (appController.getPreferences().getBaseUrl() == null) {
      baseUrl = SurveyDetailsActivity.this.getResources().getString(R.string.server_url);
    } else baseUrl = appController.getPreferences().getBaseUrl();
    uploadUrl = baseUrl + uploadUrl;
    recordUrl = baseUrl + recordUrl;
    jsonParser = new JSONParser();
    completedResponseIds = new ArrayList<>();

    if (getIntent().hasExtra(IntentConstants.SURVEY)) {
      surveys = new Surveys();
      surveys = (Surveys) getIntent().getExtras().getSerializable(IntentConstants.SURVEY);
      actionBar.setTitle(surveys.getName());
    } else actionBar.setTitle("Survey Detail");
    surveyId = surveys.getId();
    // setting up actionbar
    actionBar.setDisplayHomeAsUpEnabled(true);
    // actionBar.setHomeAsUpIndicator(R.drawable.ic_action_ic_back);
    actionBar.setDisplayShowTitleEnabled(true);
    // setting up views
    uploadButton = (RelativeLayout) findViewById(R.id.upload_button);
    surveyTitleText = (RobotoRegularTextView) findViewById(R.id.survey_title_text);
    surveyDescriptionText = (RobotoRegularTextView) findViewById(R.id.survey_description_text);
    endDateText = (RobotoLightTextView) findViewById(R.id.end_date_text);
    completeTv = (RobotoRegularTextView) findViewById(R.id.complete_response);
    incompleteTv = (RobotoRegularTextView) findViewById(R.id.incomplete_response);
    incompleteResponsesLinearLayout =
        (LinearLayout) findViewById(R.id.incomplete_response_container);
    completeResponsesLinearLayout = (LinearLayout) findViewById(R.id.complete_response_container);
    responses = new Responses();
    dbAdapter = new DBAdapter(SurveyDetailsActivity.this);

    // if no response which is complete hide upload button
    if (dbAdapter.getCompleteResponse(surveys.getId()) == 0) {
      uploadButton.setVisibility(View.GONE);
    }

    // ##
    uploadButton.setEnabled(false);
    // ##

    if (getIntent().hasExtra(IntentConstants.SURVEY)) {

      surveyTitleText.setText(surveys.getName());
      surveyDescriptionText.setText(surveys.getDescription());
      endDateText.setText(surveys.getExpiryDate());
    }

    addResponsesButton = (RobotoRegularButton) findViewById(R.id.add_responses_button);
    incompleteResponsesLinearLayout.setOnClickListener(
        new View.OnClickListener() {
          @Override
          public void onClick(View view) {

            appController.getPreferences().setBackPressed(false);
            Intent intent =
                new Intent(SurveyDetailsActivity.this, IncompleteResponseActivity.class);
            intent.putExtra(IntentConstants.SURVEY, surveys);
            startActivity(intent);
            finish();
          }
        });

    // on upload button click
    uploadButton.setOnClickListener(
        new View.OnClickListener() {
          @Override
          public void onClick(View view) {

            surveyUploadCount = 0;
            surveyUploadFailedCount = 0;
            asynTaskCheck = false;
            Long tsLong = System.currentTimeMillis() / 1000;
            timestamp = tsLong.toString();

            if (completeCount > 0) {
              progressDialog = new ProgressDialog(SurveyDetailsActivity.this);
              progressDialog.setCancelable(false);
              progressDialog.setIndeterminate(true);
              progressDialog.setMessage("Sync in Progress");

              completedResponseIds = dbAdapter.getCompleteResponsesIds(surveyId);

              if (NetworkUtil.iSConnected(getApplicationContext()) == NetworkUtil.TYPE_CONNECTED) {
                progressDialog.show();
                new UploadingMultiRecordResponse().execute();
              } else {
                appController.showToast("Please check your internet connection");
              }
            }
          }
        });

    completeResponsesLinearLayout.setOnClickListener(
        new View.OnClickListener() {
          @Override
          public void onClick(View view) {
            Intent i = new Intent(SurveyDetailsActivity.this, CompleteResponsesActivity.class);
            i.putExtra(IntentConstants.SURVEY, surveys);
            startActivity(i);
          }
        });

    SetCounts();
    addResponsesButton.setOnClickListener(
        new View.OnClickListener() {
          @Override
          public void onClick(View view) {
            requestLocation(null);
          }
        });
  }
 @Override
 protected void onDestroy() {
   super.onDestroy();
   dbAdapter.close();
 }