Example usage for android.widget LinearLayout getChildCount

List of usage examples for android.widget LinearLayout getChildCount

Introduction

In this page you can find the example usage for android.widget LinearLayout getChildCount.

Prototype

public int getChildCount() 

Source Link

Document

Returns the number of children in the group.

Usage

From source file:com.juick.android.MainActivity.java

@TargetApi(VERSION_CODES.ICE_CREAM_SANDWICH)
private void selectSourcesForCombined(final String prefix, final String[] codes) {
    final SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
    ScrollView v = new ScrollView(this);
    v.setLayoutParams(new ScrollView.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
            ViewGroup.LayoutParams.WRAP_CONTENT));
    final LinearLayout ll = new LinearLayout(this);
    ll.setLayoutParams(new ScrollView.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
            ViewGroup.LayoutParams.WRAP_CONTENT));
    ll.setOrientation(LinearLayout.VERTICAL);
    v.addView(ll);/*www  . j  a  va 2 s  .  c  om*/
    for (int i = 0; i < codes.length; i++) {
        final CompoundButton sw = VERSION.SDK_INT >= 14 ? new Switch(this) : new CheckBox(this);
        sw.setPadding(10, 10, 10, 10);
        sw.setLayoutParams(new ScrollView.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
                ViewGroup.LayoutParams.WRAP_CONTENT));
        sw.setText(codes[i]);
        sw.setChecked(sp.getBoolean(prefix + codes[i], true));
        ll.addView(sw);
    }

    new AlertDialog.Builder(MainActivity.this).setView(v).setCancelable(true)
            .setOnCancelListener(new DialogInterface.OnCancelListener() {
                @Override
                public void onCancel(DialogInterface dialogInterface) {
                    SharedPreferences.Editor e = sp.edit();
                    for (int i = 0; i < ll.getChildCount(); i++) {
                        CompoundButton cb = (CompoundButton) ll.getChildAt(i);
                        assert cb != null;
                        e.putBoolean(prefix + codes[i], cb.isChecked());
                    }
                    e.commit();
                }
            }).create().show();

}

From source file:com.thinkthinkdo.pff_appsettings.PermissionDetailFragment.java

private void displayApps(LinearLayout permListView, String permName) {
    List<PackageInfo> packs = mPm.getInstalledPackages(0);
    SortedMap<String, MyPermissionInfo> usedPerms = new TreeMap<String, MyPermissionInfo>();
    for (int i = 0; i < packs.size(); i++) {
        PackageInfo p = packs.get(i);/* ww  w  .j av  a 2 s  .  com*/
        PackageInfo pkgInfo;
        try {
            pkgInfo = mPm.getPackageInfo(p.packageName, PackageManager.GET_PERMISSIONS);
        } catch (NameNotFoundException e) {
            Log.w(TAG, "Couldn't retrieve permissions for package:" + p.packageName);
            continue;
        }
        // Extract all user permissions
        Set<MyPermissionInfo> permSet = new HashSet<MyPermissionInfo>();
        if ((pkgInfo.applicationInfo != null) && (pkgInfo.applicationInfo.uid != -1)) {
            if (localLOGV)
                Log.w(TAG, "getAllUsedPermissions package:" + p.packageName);
            getAllUsedPermissions(pkgInfo.applicationInfo.uid, permSet);
        }
        for (MyPermissionInfo tmpInfo : permSet) {
            if (localLOGV)
                Log.i(TAG, "tmpInfo package:" + p.packageName + ", tmpInfo.name=" + tmpInfo.name);
            if (tmpInfo.name.equalsIgnoreCase(permName)) {
                if (localLOGV)
                    Log.w(TAG, "Adding package:" + p.packageName);
                tmpInfo.packageName = p.packageName;
                usedPerms.put(tmpInfo.packageName, tmpInfo);
            }
        }
    }
    mUsedPerms = usedPerms;
    permListView.removeAllViews();
    /* add the All Entry                        */
    int spacing = (int) (8 * mContext.getResources().getDisplayMetrics().density);
    LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
            ViewGroup.LayoutParams.WRAP_CONTENT);
    int j = 0;
    for (Map.Entry<String, MyPermissionInfo> entry : usedPerms.entrySet()) {
        MyPermissionInfo tmpPerm = entry.getValue();
        if (tmpPerm.packageName.compareToIgnoreCase("com.thinkthinkdo.pff_appsettings") != 0) {
            if (localLOGV)
                Log.w(TAG, "usedPacks containd package:" + tmpPerm.packageName);
            View view = getAppItemView(mContext, mInflater, tmpPerm);
            lp = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                    ViewGroup.LayoutParams.WRAP_CONTENT);
            if (j == 0) {
                lp.topMargin = spacing;
            }
            if (permListView.getChildCount() == 0) {
                lp.topMargin *= 2;
            }
            permListView.addView(view, lp);
            j++;
        }
    }
}

From source file:im.vector.fragments.VectorSettingsPreferencesFragment.java

private void displayTextSizeSelection(final Activity activity) {
    AlertDialog.Builder builder = new AlertDialog.Builder(activity);
    LayoutInflater inflater = activity.getLayoutInflater();

    View layout = inflater.inflate(R.layout.text_size_selection, null);
    builder.setTitle(R.string.font_size);
    builder.setView(layout);// w ww  . j  av  a2s  .c  o m

    builder.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int id) {
        }
    });

    builder.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int id) {
        }
    });

    final AlertDialog dialog = builder.create();
    dialog.show();

    LinearLayout linearLayout = layout.findViewById(R.id.text_selection_group_view);

    int childCount = linearLayout.getChildCount();

    String scaleText = VectorApp.getFontScale();

    for (int i = 0; i < childCount; i++) {
        View v = linearLayout.getChildAt(i);

        if (v instanceof CheckedTextView) {
            final CheckedTextView checkedTextView = (CheckedTextView) v;
            checkedTextView.setChecked(TextUtils.equals(checkedTextView.getText(), scaleText));

            checkedTextView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    dialog.dismiss();
                    VectorApp.updateFontScale(checkedTextView.getText().toString());
                    activity.startActivity(activity.getIntent());
                    activity.finish();
                }
            });
        }
    }
}

From source file:com.mdlive.sav.MDLiveProviderDetails.java

/**
 *  Successful Response Handler for Load Provider Info.Here the Profile image of
 *  the Particular provider will be displayed.Along with that the Provider's
 *  speciality,about the Provider , license and the languages will also be
 *  displayed.Along with this Provider's affilitations will also be displayed
 *
 *//*ww w.  j ava  2 s  .  c o m*/
private void handleSuccessResponse(JSONObject response) {
    // DEBUGGING.  o.uwechue
    Log.d("MDLProviderDetails", "*********\nHTTP Response: " + response);
    try {
        //Fetch Data From the Services
        Log.d("Response details", "******************\n*******************\n" + response.toString());
        JsonParser parser = new JsonParser();
        JsonObject responObj = (JsonObject) parser.parse(response.toString());
        JsonObject profileobj = responObj.get("doctor_profile").getAsJsonObject();
        JsonObject providerdetObj = profileobj.get("provider_details").getAsJsonObject();

        JsonObject appointment_slot = profileobj.get("appointment_slot").getAsJsonObject();
        JsonArray available_hour = appointment_slot.get("available_hour").getAsJsonArray();

        boolean isDoctorWithPatient = false;
        LinearLayout layout = (LinearLayout) findViewById(R.id.panelMessageFiles);
        String str_timeslot = ""; /*str_phys_avail_id = "",*/
        SharedPreferences sharedpreferences = getSharedPreferences(PreferenceConstants.MDLIVE_USER_PREFERENCES,
                Context.MODE_PRIVATE);
        str_Availability_Type = sharedpreferences
                .getString(PreferenceConstants.PROVIDER_AVAILABILITY_TYPE_PREFERENCES, "");
        String str_avail_status = sharedpreferences
                .getString(PreferenceConstants.PROVIDER_AVAILABILITY_STATUS_PREFERENCES, "");
        if (str_avail_status.equalsIgnoreCase("true")) {
            if (str_Availability_Type.equalsIgnoreCase("video or phone")) {
                isDoctorAvailableNow = true;
            } else if (str_Availability_Type.equalsIgnoreCase("phone")) {
                isDoctorAvailableNow = true;
            } else if (str_Availability_Type.equalsIgnoreCase("video")) {
                isDoctorAvailableNow = true;
            }

            else if (str_Availability_Type.equalsIgnoreCase("With Patient")) {
                isDoctorAvailableNow = false;
            } else {
                isDoctorAvailableNow = false;
            }
        } else {
            isDoctorAvailableNow = false;
        }

        if (layout.getChildCount() > 0) {
            layout.removeAllViews();
        }
        videoList.clear();
        phoneList.clear();

        for (int i = 0; i < available_hour.size(); i++) {
            JsonObject availabilityStatus = available_hour.get(i).getAsJsonObject();
            String str_availabilityStatus = "";

            if (MdliveUtils.checkJSONResponseHasString(availabilityStatus, "status")) {
                str_availabilityStatus = availabilityStatus.get("status").getAsString();
                if (str_availabilityStatus.equals("Available")) {
                    JsonArray timeSlotArray = availabilityStatus.get("time_slot").getAsJsonArray();
                    for (int j = 0; j < timeSlotArray.size(); j++) {
                        JsonObject timeSlotObj = timeSlotArray.get(j).getAsJsonObject();

                        if (MdliveUtils.checkJSONResponseHasString(timeSlotObj, "appointment_type")
                                && MdliveUtils.checkJSONResponseHasString(timeSlotObj, "timeslot")) {
                            str_appointmenttype = timeSlotObj.get("appointment_type").getAsString();
                            str_timeslot = timeSlotObj.get("timeslot").getAsString();
                            selectedTimestamp = timeSlotObj.get("timeslot").getAsString();
                            Log.d("***TIMESLOT***", "****\n****\nTimeslot: [" + selectedTimestamp + "]");

                            if (MdliveUtils.checkJSONResponseHasString(timeSlotObj, "phys_availability_id")) {
                                str_phys_avail_id = timeSlotObj.get("phys_availability_id").getAsString();
                            } else {
                                str_phys_avail_id = null;
                            }

                            HashMap<String, String> map = new HashMap<String, String>();
                            map.put("timeslot", str_timeslot);
                            map.put("phys_id", (str_phys_avail_id == null) ? "" : str_phys_avail_id + "");
                            map.put("appointment_type", str_appointmenttype);

                            timeSlotListMap.add(map);
                            if (str_timeslot.equals("0")) {
                                if (!str_Availability_Type.equalsIgnoreCase("With Patient")) {
                                    final int density = (int) getBaseContext().getResources()
                                            .getDisplayMetrics().density;

                                    final Button myText = new Button(MDLiveProviderDetails.this);
                                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                                        myText.setElevation(0f);
                                    }
                                    isDoctorAvailableNow = true;
                                    LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
                                            LinearLayout.LayoutParams.WRAP_CONTENT,
                                            LinearLayout.LayoutParams.WRAP_CONTENT);
                                    params.setMargins(4 * density, 4 * density, 4 * density, 4 * density);
                                    myText.setLayoutParams(params);
                                    myText.setGravity(Gravity.CENTER);
                                    myText.setTextColor(Color.WHITE);
                                    myText.setTextSize(16);
                                    myText.setPadding(8 * density, 4 * density, 8 * density, 4 * density);
                                    myText.setBackgroundResource(R.drawable.timeslot_white_rounded_corner);
                                    myText.setText("Now");
                                    myText.setBackgroundResource(R.drawable.timeslot_blue_rounded_corner);
                                    myText.setClickable(true);
                                    previousSelectedTv = myText;
                                    if (str_appointmenttype.toLowerCase().contains("video")) {
                                        videoList.add(myText);
                                    }
                                    if (str_appointmenttype.toLowerCase().contains("phone")) {
                                        phoneList.add(myText);
                                    }
                                    LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
                                            LinearLayout.LayoutParams.WRAP_CONTENT,
                                            LinearLayout.LayoutParams.WRAP_CONTENT);
                                    lp.setMargins(4 * density, 4 * density, 4 * density, 4 * density);
                                    myText.setLayoutParams(lp);
                                    myText.setTag("Now");
                                    defaultNowTextPreferences(myText, str_appointmenttype);
                                    selectedTimeslot = true;
                                    clickEventForHorizontalText(myText, str_timeslot, str_phys_avail_id);
                                    layout.addView(myText);
                                    //layout.addView(line, 1);
                                }
                            } else {
                                setHorizontalScrollviewTimeslots(layout, str_timeslot, j, str_phys_avail_id);
                            }
                        }
                    }
                } else if (str_availabilityStatus.equalsIgnoreCase("With patient")) {
                    isDoctorWithPatient = true;
                }
            }
        }

        //with patient
        if (isDoctorWithPatient) {
            if (layout.getChildCount() >= 1) {
                // Req Future Appmt

                enableOrdisableProviderDetails(str_Availability_Type);
            } else if (layout.getChildCount() < 1) {
                //Make future appointment
                onlyWithPatient();

            }
        }

        /*This is for Status is available and the timeslot is Zero..Remaining all
            the status were not available.*/
        //Available now only
        else if (isDoctorAvailableNow && layout.getChildCount() < 1) {

            horizontalscrollview.setVisibility(View.GONE);
            findViewById(R.id.dateTxtLayout).setVisibility(View.GONE);
            if (str_Availability_Type.equalsIgnoreCase("video")) {
                onlyVideo();

            } else if (str_Availability_Type.equalsIgnoreCase("video or phone")) {
                VideoOrPhoneNotAvailable();
            } else if (str_Availability_Type.equalsIgnoreCase("phone")) {
                onlyPhone();
            } else if (str_Availability_Type.equalsIgnoreCase("With Patient")) {
                onlyWithPatient();
            }

        }

        //Available now and later
        //Part1 ----> timeslot zero followed by many timeslots
        else if (isDoctorAvailableNow && layout.getChildCount() >= 1) {
            enableOrdisableProviderDetails(str_Availability_Type);

        }
        //part 2 available ly later
        //Part2 ----> timeslot not zero followed by many timeslots
        else if (!isDoctorAvailableNow && layout.getChildCount() >= 1) {
            availableOnlyLater(str_Availability_Type);

        }

        //not available

        else if (layout.getChildCount() == 0 && str_Availability_Type.equals("not available")) {
            if (str_appointmenttype.equals("1")) {
                notAvailable();
            } else if (str_appointmenttype.equals("2")) {
                notAvailable();
            } else {
                notAvailable();
            }
        }

        //not available
        else if (layout.getChildCount() == 0) {
            horizontalscrollview.setVisibility(View.GONE);
            findViewById(R.id.dateTxtLayout).setVisibility(View.GONE);
            if (str_Availability_Type.equalsIgnoreCase("video")) {
                onlyVideo();

            } else if (str_Availability_Type.equalsIgnoreCase("video or phone")) {
                VideoOrPhoneNotAvailable();
            } else if (str_Availability_Type.equalsIgnoreCase("phone")) {
                onlyPhone();
            } else if (str_Availability_Type.equalsIgnoreCase("With patient")) {
                onlyWithPatient();
            } else if (str_Availability_Type.equalsIgnoreCase("not available")) {
                //Make future appointment only
                notAvailable();
            }
        }

        setResponseQualificationDetails(providerdetObj, str_Availability_Type);

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

}

From source file:usbong.android.likha_collection_1.UsbongDecisionTreeEngineActivity.java

public void processNextButtonPressed() {
    wasNextButtonPressed = true;/*from  w ww  .jav a2s .  com*/
    hasUpdatedDecisionTrackerContainer = false;

    //edited by Mike, 20160417
    if ((mTts != null) && (mTts.isSpeaking())) {
        mTts.stop();
    }
    //edited by Mike, 20160417
    if ((myMediaPlayer != null) && (myMediaPlayer.isPlaying())) {
        myMediaPlayer.stop();
    }

    if (currAudioRecorder != null) {
        try {
            //if stop button is pressable
            if (stopButton.isEnabled()) {
                currAudioRecorder.stop();
            }
            if (currAudioRecorder.isPlaying()) {
                currAudioRecorder.stopPlayback();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        String path = currAudioRecorder.getPath();
        //               System.out.println(">>>>>>>>>>>>>>>>>>>currAudioRecorder: "+currAudioRecorder);
        if (!attachmentFilePaths.contains(path)) {
            attachmentFilePaths.add(path);
            //                  System.out.println(">>>>>>>>>>>>>>>>adding path: "+path);
        }
    }

    //END_STATE_SCREEN = last screen
    if (currScreen == UsbongConstants.END_STATE_SCREEN) {
        int usbongAnswerContainerSize = usbongAnswerContainer.size();
        StringBuffer outputStringBuffer = new StringBuffer();
        for (int i = 0; i < usbongAnswerContainerSize; i++) {
            outputStringBuffer.append(usbongAnswerContainer.elementAt(i));
        }

        myOutputDirectory = UsbongUtils.getDateTimeStamp() + "/";
        if (UsbongUtils.STORE_OUTPUT) {
            try {
                UsbongUtils.createNewOutputFolderStructure();
            } catch (Exception e) {
                e.printStackTrace();
            }
            UsbongUtils.storeOutputInSDCard(
                    UsbongUtils.BASE_FILE_PATH + myOutputDirectory + UsbongUtils.getDateTimeStamp() + ".csv",
                    outputStringBuffer.toString());
        } else {
            UsbongUtils.deleteRecursive(new File(UsbongUtils.BASE_FILE_PATH + myOutputDirectory));
        }

        //wasNextButtonPressed=false; //no need to make this true, because this is the last node
        hasUpdatedDecisionTrackerContainer = true;

        /*
        //send to server
        UsbongUtils.performFileUpload(UsbongUtils.BASE_FILE_PATH + myOutputDirectory + UsbongUtils.getTimeStamp() + ".csv");
                 
        //send to email
        Intent emailIntent = UsbongUtils.performEmailProcess(UsbongUtils.BASE_FILE_PATH + myOutputDirectory + UsbongUtils.getTimeStamp() + ".csv", attachmentFilePaths);
        emailIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        //                emailIntent.addFlags(RESULT_OK);
        startActivityForResult(Intent.createChooser(emailIntent, "Email:"),EMAIL_SENDING_SUCCESS);
        */

        //added by Mike, Sept. 10, 2014
        UsbongUtils.clearTempFolder();

        //added by Mike, 20160415
        if (UsbongUtils.IS_IN_AUTO_LOOP_MODE) {
            //added by Mike, 20161118
            AppRater.showRateDialog(this);

            isAutoLoopedTree = true;
            initParser(myTree);
            return;
        } else {
            //return to main activity
            finish();
            //added by Mike, 20161118
            Intent toUsbongMainActivityIntent = new Intent(UsbongDecisionTreeEngineActivity.this,
                    UsbongMainActivity.class);
            toUsbongMainActivityIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            toUsbongMainActivityIntent.putExtra("completed_tree", "true");
            startActivity(toUsbongMainActivityIntent);
        }
    } else {
        if (currScreen == UsbongConstants.YES_NO_DECISION_SCREEN) {
            RadioButton myYesRadioButton = (RadioButton) findViewById(R.id.yes_radiobutton);
            RadioButton myNoRadioButton = (RadioButton) findViewById(R.id.no_radiobutton);

            if (myYesRadioButton.isChecked()) {
                currUsbongNode = nextUsbongNodeIfYes;

                UsbongUtils.addElementToContainer(usbongAnswerContainer, "Y;", usbongAnswerContainerCounter);
                usbongAnswerContainerCounter++;

                initParser();
            } else if (myNoRadioButton.isChecked()) {
                currUsbongNode = nextUsbongNodeIfNo;
                //                     usbongAnswerContainer.addElement("N;");                                             
                UsbongUtils.addElementToContainer(usbongAnswerContainer, "N;", usbongAnswerContainerCounter);
                usbongAnswerContainerCounter++;

                initParser();
            } else { //if no radio button was checked                       
                if (!UsbongUtils.IS_IN_DEBUG_MODE) {
                    if (!isAnOptionalNode) {
                        showRequiredFieldAlert(PLEASE_CHOOSE_AN_ANSWER_ALERT_TYPE);
                        wasNextButtonPressed = false;
                        hasUpdatedDecisionTrackerContainer = true;
                        return;
                    }
                }
                currUsbongNode = nextUsbongNodeIfYes; //nextUsbongNodeIfNo will also do, since this is "Any"
                UsbongUtils.addElementToContainer(usbongAnswerContainer, "A;", usbongAnswerContainerCounter);
                usbongAnswerContainerCounter++;

                initParser();
            }
        } else if (currScreen == UsbongConstants.SEND_TO_WEBSERVER_SCREEN) {
            RadioButton myYesRadioButton = (RadioButton) findViewById(R.id.yes_radiobutton);
            RadioButton myNoRadioButton = (RadioButton) findViewById(R.id.no_radiobutton);

            if (myYesRadioButton.isChecked()) {
                currUsbongNode = nextUsbongNodeIfYes;
                //                     usbongAnswerContainer.addElement("Y;");         
                UsbongUtils.addElementToContainer(usbongAnswerContainer, "Y;", usbongAnswerContainerCounter);
                usbongAnswerContainerCounter++;

                decisionTrackerContainer.addElement(usbongAnswerContainer.lastElement());
                //                     wasNextButtonPressed=false; //no need to make this true, because "Y;" has already been added to decisionTrackerContainer
                hasUpdatedDecisionTrackerContainer = true;

                //edited by Mike, March 4, 2013
                //"save" the output into the SDCard as "output.txt"
                //                      int usbongAnswerContainerSize = usbongAnswerContainer.size();
                int usbongAnswerContainerSize = usbongAnswerContainerCounter;

                StringBuffer outputStringBuffer = new StringBuffer();
                for (int i = 0; i < usbongAnswerContainerSize; i++) {
                    outputStringBuffer.append(usbongAnswerContainer.elementAt(i));
                }

                myOutputDirectory = UsbongUtils.getDateTimeStamp() + "/";
                try {
                    UsbongUtils.createNewOutputFolderStructure();
                } catch (Exception e) {
                    e.printStackTrace();
                }
                UsbongUtils.storeOutputInSDCard(UsbongUtils.BASE_FILE_PATH + myOutputDirectory
                        + UsbongUtils.getDateTimeStamp() + ".csv", outputStringBuffer.toString());

                //send to server
                UsbongUtils.performFileUpload(UsbongUtils.BASE_FILE_PATH + myOutputDirectory
                        + UsbongUtils.getDateTimeStamp() + ".csv");
            } else if (myNoRadioButton.isChecked()) {
                currUsbongNode = nextUsbongNodeIfNo;
                //                     usbongAnswerContainer.addElement("N;");                                             
                UsbongUtils.addElementToContainer(usbongAnswerContainer, "N;", usbongAnswerContainerCounter);
                usbongAnswerContainerCounter++;
            } else { //if no radio button was checked                       
                if (!UsbongUtils.IS_IN_DEBUG_MODE) {
                    if (!isAnOptionalNode) {
                        showRequiredFieldAlert(PLEASE_CHOOSE_AN_ANSWER_ALERT_TYPE);
                        wasNextButtonPressed = false;
                        hasUpdatedDecisionTrackerContainer = true;
                        return;
                    }
                }
                //                       else {
                currUsbongNode = nextUsbongNodeIfYes; //nextUsbongNodeIfNo will also do, since this is "Any"
                UsbongUtils.addElementToContainer(usbongAnswerContainer, "A;", usbongAnswerContainerCounter);
                usbongAnswerContainerCounter++;
                //                      initParser();            
            }
            initParser();
        } else if (currScreen == UsbongConstants.SEND_TO_CLOUD_BASED_SERVICE_SCREEN) {
            RadioButton myYesRadioButton = (RadioButton) findViewById(R.id.yes_radiobutton);
            RadioButton myNoRadioButton = (RadioButton) findViewById(R.id.no_radiobutton);

            if (myYesRadioButton.isChecked()) {
                currUsbongNode = nextUsbongNodeIfYes;
                //                     usbongAnswerContainer.addElement("Y;");                                             
                UsbongUtils.addElementToContainer(usbongAnswerContainer, "Y;", usbongAnswerContainerCounter);
                usbongAnswerContainerCounter++;

                decisionTrackerContainer.addElement(usbongAnswerContainer.lastElement());
                //                     wasNextButtonPressed=false; //no need to make this true, because "Y;" has already been added to decisionTrackerContainer
                hasUpdatedDecisionTrackerContainer = true;

                StringBuffer sb = new StringBuffer();
                for (int i = 0; i < decisionTrackerContainer.size(); i++) {
                    sb.append(decisionTrackerContainer.elementAt(i));
                }
                Log.d(">>>>>>>>>>>>>decisionTrackerContainer", sb.toString());

                //edited by Mike, March 4, 2013
                //"save" the output into the SDCard as "output.txt"
                //                      int usbongAnswerContainerSize = usbongAnswerContainer.size();
                int usbongAnswerContainerSize = usbongAnswerContainerCounter;

                StringBuffer outputStringBuffer = new StringBuffer();
                for (int i = 0; i < usbongAnswerContainerSize; i++) {
                    outputStringBuffer.append(usbongAnswerContainer.elementAt(i));
                }

                myOutputDirectory = UsbongUtils.getDateTimeStamp() + "/";
                try {
                    UsbongUtils.createNewOutputFolderStructure();
                } catch (Exception e) {
                    e.printStackTrace();
                }
                UsbongUtils.storeOutputInSDCard(UsbongUtils.BASE_FILE_PATH + myOutputDirectory
                        + UsbongUtils.getDateTimeStamp() + ".csv", outputStringBuffer.toString());

                //send to cloud-based service
                Intent sendToCloudBasedServiceIntent = UsbongUtils
                        .performSendToCloudBasedServiceProcess(UsbongUtils.BASE_FILE_PATH + myOutputDirectory
                                + UsbongUtils.getDateTimeStamp() + ".csv", attachmentFilePaths);
                /*emailIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                */
                //                      emailIntent.addFlags(RESULT_OK);
                //                      startActivityForResult(Intent.createChooser(emailIntent, "Email:"),EMAIL_SENDING_SUCCESS);
                //answer from Llango J, stackoverflow
                //Reference: http://stackoverflow.com/questions/7479883/problem-with-sending-email-goes-back-to-previous-activity;
                //last accessed: 22 Oct. 2012
                startActivity(
                        Intent.createChooser(sendToCloudBasedServiceIntent, "Send to Cloud-based Service:"));
            } else if (myNoRadioButton.isChecked()) {
                currUsbongNode = nextUsbongNodeIfNo;
                //                     usbongAnswerContainer.addElement("N;");                                             
                UsbongUtils.addElementToContainer(usbongAnswerContainer, "N;", usbongAnswerContainerCounter);
                usbongAnswerContainerCounter++;
            } else { //if no radio button was checked                       
                if (!UsbongUtils.IS_IN_DEBUG_MODE) {
                    if (!isAnOptionalNode) {
                        showRequiredFieldAlert(PLEASE_CHOOSE_AN_ANSWER_ALERT_TYPE);
                        wasNextButtonPressed = false;
                        hasUpdatedDecisionTrackerContainer = true;
                        return;
                    }
                }
                //                       else {
                currUsbongNode = nextUsbongNodeIfYes; //nextUsbongNodeIfNo will also do, since this is "Any"
                UsbongUtils.addElementToContainer(usbongAnswerContainer, "A;", usbongAnswerContainerCounter);
                usbongAnswerContainerCounter++;
                //                      initParser();            

                /*
                                       if (!isAnOptionalNode) {
                  showRequiredFieldAlert(PLEASE_CHOOSE_AN_ANSWER_ALERT_TYPE);
                 wasNextButtonPressed=false;
                 hasUpdatedDecisionTrackerContainer=true;
                         
                 return;
                                       }
                                       else {
                 currUsbongNode = nextUsbongNodeIfYes; //nextUsbongNodeIfNo will also do, since this is "Any"
                //                        usbongAnswerContainer.addElement("A;");                                             
                 UsbongUtils.addElementToContainer(usbongAnswerContainer, "A;", usbongAnswerContainerCounter);
                usbongAnswerContainerCounter++;
                        
                initParser();            
                                       }
                */
            }
            /*                    
                              currUsbongNode = nextUsbongNodeIfYes; //nextUsbongNodeIfNo will also do, since this is "Any"
                              usbongAnswerContainer.addElement("Any;");                                             
            */
            initParser();
        } else if (currScreen == UsbongConstants.MULTIPLE_CHECKBOXES_SCREEN) {
            //                   requiredTotalCheckedBoxes   
            LinearLayout myMultipleCheckboxesLinearLayout = (LinearLayout) findViewById(
                    R.id.multiple_checkboxes_linearlayout);
            StringBuffer sb = new StringBuffer();
            int totalCheckedBoxes = 0;
            int totalCheckBoxChildren = myMultipleCheckboxesLinearLayout.getChildCount();
            //begin with i=1, because i=0 is for checkboxes_textview
            for (int i = 1; i < totalCheckBoxChildren; i++) {
                if (((CheckBox) myMultipleCheckboxesLinearLayout.getChildAt(i)).isChecked()) {
                    totalCheckedBoxes++;
                    sb.append("," + (i - 1)); //do a (i-1) so that i starts with 0 for the checkboxes (excluding checkboxes_textview) to maintain consistency with the other components
                }
            }

            if (totalCheckedBoxes >= requiredTotalCheckedBoxes) {
                currUsbongNode = nextUsbongNodeIfYes;
                sb.insert(0, "Y"); //insert in front of stringBuffer
                sb.append(";");
            } else {
                currUsbongNode = nextUsbongNodeIfNo;
                sb.delete(0, sb.length());
                sb.append("N,;"); //make sure to add the comma
            }
            //                   usbongAnswerContainer.addElement(sb.toString());
            UsbongUtils.addElementToContainer(usbongAnswerContainer, sb.toString(),
                    usbongAnswerContainerCounter);
            usbongAnswerContainerCounter++;

            initParser();
        } else if (currScreen == UsbongConstants.MULTIPLE_RADIO_BUTTONS_SCREEN) {
            currUsbongNode = nextUsbongNodeIfYes; //nextUsbongNodeIfNo will also do, since this is "Any"
            RadioGroup myRadioGroup = (RadioGroup) findViewById(R.id.multiple_radio_buttons_radiogroup);

            //                   if (UsbongUtils.IS_IN_DEBUG_MODE==false) {
            if (myRadioGroup.getCheckedRadioButtonId() == -1) { //no radio button checked
                if (!UsbongUtils.IS_IN_DEBUG_MODE) {
                    if (!isAnOptionalNode) {
                        showRequiredFieldAlert(PLEASE_CHOOSE_AN_ANSWER_ALERT_TYPE);
                        wasNextButtonPressed = false;
                        hasUpdatedDecisionTrackerContainer = true;
                        return;
                    }
                }
                //                          else {
                currUsbongNode = nextUsbongNodeIfYes; //nextUsbongNodeIfNo will also do, since this is "Any"
                UsbongUtils.addElementToContainer(usbongAnswerContainer, "A;", usbongAnswerContainerCounter);
                usbongAnswerContainerCounter++;

                initParser();
                //                          }
            } else {
                //                         usbongAnswerContainer.addElement(myRadioGroup.getCheckedRadioButtonId()+";");
                UsbongUtils.addElementToContainer(usbongAnswerContainer,
                        myRadioGroup.getCheckedRadioButtonId() + ";", usbongAnswerContainerCounter);
                usbongAnswerContainerCounter++;

                initParser();
            }
            //                   }
            /*                   
                               else {
            //                      usbongAnswerContainer.addElement(myRadioGroup.getCheckedRadioButtonId()+";");
              UsbongUtils.addElementToContainer(usbongAnswerContainer, myRadioGroup.getCheckedRadioButtonId()+";", usbongAnswerContainerCounter);
             usbongAnswerContainerCounter++;
                      
              initParser();                      
                               }
            */
        } else if (currScreen == UsbongConstants.MULTIPLE_RADIO_BUTTONS_WITH_ANSWER_SCREEN) {
            currUsbongNode = nextUsbongNodeIfYes; //nextUsbongNodeIfNo will also do, since this is "Any"
            RadioGroup myRadioGroup = (RadioGroup) findViewById(R.id.multiple_radio_buttons_radiogroup);

            /*                   if (UsbongUtils.IS_IN_DEBUG_MODE==false) {
             */
            if (myRadioGroup.getCheckedRadioButtonId() == -1) { //no radio button checked                                                  
                if (!UsbongUtils.IS_IN_DEBUG_MODE) {
                    if (!isAnOptionalNode) {
                        showRequiredFieldAlert(PLEASE_CHOOSE_AN_ANSWER_ALERT_TYPE);
                        wasNextButtonPressed = false;
                        hasUpdatedDecisionTrackerContainer = true;
                        return;
                    }
                }
                //                          else {
                currUsbongNode = nextUsbongNodeIfYes; //choose Yes if "Any"
                UsbongUtils.addElementToContainer(usbongAnswerContainer,
                        "A," + myRadioGroup.getCheckedRadioButtonId() + ";", usbongAnswerContainerCounter);
                usbongAnswerContainerCounter++;

                initParser();
                //                          }
            } else {
                if (myMultipleRadioButtonsWithAnswerScreenAnswer
                        .equals("" + myRadioGroup.getCheckedRadioButtonId())) {
                    currUsbongNode = nextUsbongNodeIfYes;
                    UsbongUtils.addElementToContainer(usbongAnswerContainer,
                            "Y," + myRadioGroup.getCheckedRadioButtonId() + ";", usbongAnswerContainerCounter);
                } else {
                    currUsbongNode = nextUsbongNodeIfNo;
                    UsbongUtils.addElementToContainer(usbongAnswerContainer,
                            "N," + myRadioGroup.getCheckedRadioButtonId() + ";", usbongAnswerContainerCounter);
                }

                usbongAnswerContainerCounter++;
                initParser();
            }
        } else if (currScreen == UsbongConstants.LINK_SCREEN) {
            RadioGroup myRadioGroup = (RadioGroup) findViewById(R.id.multiple_radio_buttons_radiogroup);

            try {
                currUsbongNode = UsbongUtils.getLinkFromRadioButton(
                        radioButtonsContainer.elementAt(myRadioGroup.getCheckedRadioButtonId()));
            } catch (Exception e) {
                //if the user hasn't ticked any radio button yet
                //put the currUsbongNode to default
                //                currUsbongNode = UsbongUtils.getLinkFromRadioButton(nextUsbongNodeIfYes); //nextUsbongNodeIfNo will also do, since this is "Any"
                //of course, showPleaseAnswerAlert() will be called                        
                //edited by Mike, 20160613
                //don't change the currUsbongNode anymore if no radio button has been ticked                
            }

            //                   Log.d(">>>>>>>>>>currUsbongNode",currUsbongNode);
            if (myRadioGroup.getCheckedRadioButtonId() == -1) { //no radio button checked
                //                         if (!UsbongUtils.IS_IN_DEBUG_MODE) {
                if (!isAnOptionalNode) {
                    showRequiredFieldAlert(PLEASE_CHOOSE_AN_ANSWER_ALERT_TYPE);
                    wasNextButtonPressed = false;
                    hasUpdatedDecisionTrackerContainer = true;

                    return;
                }
                //                         }
                //                          else {
                currUsbongNode = nextUsbongNodeIfYes; //nextUsbongNodeIfNo will also do, since this is "Any"
                UsbongUtils.addElementToContainer(usbongAnswerContainer, "A;", usbongAnswerContainerCounter);
                usbongAnswerContainerCounter++;

                initParser();
                //                          }
            } else {
                //                         usbongAnswerContainer.addElement(myRadioGroup.getCheckedRadioButtonId()+";");
                UsbongUtils.addElementToContainer(usbongAnswerContainer,
                        myRadioGroup.getCheckedRadioButtonId() + ";", usbongAnswerContainerCounter);
                usbongAnswerContainerCounter++;

                initParser();
            }
            /*                   }
                               else {
              usbongAnswerContainer.addElement(myRadioGroup.getCheckedRadioButtonId()+";");
               initParser();                      
                               }
            */
        } else if ((currScreen == UsbongConstants.TEXTFIELD_SCREEN)
                || (currScreen == UsbongConstants.TEXTFIELD_WITH_UNIT_SCREEN)
                || (currScreen == UsbongConstants.TEXTFIELD_NUMERICAL_SCREEN)) {
            currUsbongNode = nextUsbongNodeIfYes; //= nextIMCIQuestionIfNo will also do
            EditText myTextFieldScreenEditText = (EditText) findViewById(R.id.textfield_edittext);

            //                    if (UsbongUtils.IS_IN_DEBUG_MODE==false) {
            //if it's blank
            if (myTextFieldScreenEditText.getText().toString().trim().equals("")) {
                if (!UsbongUtils.IS_IN_DEBUG_MODE) {
                    if (!isAnOptionalNode) {
                        showRequiredFieldAlert(PLEASE_ANSWER_FIELD_ALERT_TYPE);
                        wasNextButtonPressed = false;
                        hasUpdatedDecisionTrackerContainer = true;
                        return;
                    }
                }
                //                          else {
                currUsbongNode = nextUsbongNodeIfYes; //nextUsbongNodeIfNo will also do, since this is "Any"
                //                           usbongAnswerContainer.addElement("A;");                                             
                UsbongUtils.addElementToContainer(usbongAnswerContainer, "A,;", usbongAnswerContainerCounter);
                usbongAnswerContainerCounter++;

                initParser();
                //                          }
            } else {
                //                        usbongAnswerContainer.addElement("A,"+myTextFieldScreenEditText.getText()+";");                     
                UsbongUtils.addElementToContainer(usbongAnswerContainer,
                        "A," + myTextFieldScreenEditText.getText() + ";", usbongAnswerContainerCounter);
                usbongAnswerContainerCounter++;

                initParser();
            }
        } else if (currScreen == UsbongConstants.TEXTFIELD_WITH_ANSWER_SCREEN) {
            currUsbongNode = nextUsbongNodeIfYes;
            EditText myTextFieldScreenEditText = (EditText) findViewById(R.id.textfield_edittext);
            //if it's blank
            if (myTextFieldScreenEditText.getText().toString().trim().equals("")) {
                if (!UsbongUtils.IS_IN_DEBUG_MODE) {
                    if (!isAnOptionalNode) {
                        showRequiredFieldAlert(PLEASE_ANSWER_FIELD_ALERT_TYPE);
                        wasNextButtonPressed = false;
                        hasUpdatedDecisionTrackerContainer = true;
                        return;
                    }
                }
                currUsbongNode = nextUsbongNodeIfYes; //choose Yes if "Any"
                UsbongUtils.addElementToContainer(usbongAnswerContainer,
                        "A," + myTextFieldScreenEditText.getText().toString().trim() + ";",
                        usbongAnswerContainerCounter);
                usbongAnswerContainerCounter++;

                initParser();
            } else {
                //added by Mike, Jan. 27, 2014
                Vector<String> myPossibleAnswers = new Vector<String>();
                StringTokenizer myPossibleAnswersStringTokenizer = new StringTokenizer(
                        myTextFieldWithAnswerScreenAnswer, "||");
                if (myPossibleAnswersStringTokenizer != null) {
                    while (myPossibleAnswersStringTokenizer.hasMoreTokens()) { //get last element (i.e. Mike in "textFieldWithAnswer~Who is the founder of Usbong (nickname)?Answer=Mike")
                        myPossibleAnswers.add(myPossibleAnswersStringTokenizer.nextToken());
                    }
                }
                int size = myPossibleAnswers.size();
                for (int i = 0; i < size; i++) {
                    if (myPossibleAnswers.elementAt(i)
                            .equals(myTextFieldScreenEditText.getText().toString().trim())) {
                        currUsbongNode = nextUsbongNodeIfYes;
                        UsbongUtils.addElementToContainer(usbongAnswerContainer,
                                "Y," + myTextFieldScreenEditText.getText().toString().trim() + ";",
                                usbongAnswerContainerCounter);
                        break;
                    }

                    if (i == size - 1) { //if this is the last element in the vector
                        currUsbongNode = nextUsbongNodeIfNo;
                        UsbongUtils.addElementToContainer(usbongAnswerContainer,
                                "N," + myTextFieldScreenEditText.getText().toString().trim() + ";",
                                usbongAnswerContainerCounter);
                    }
                }
                /*                        
                  if (myTextFieldWithAnswerScreenAnswer.equals(myTextFieldScreenEditText.getText().toString().trim())) {
                   currUsbongNode = nextUsbongNodeIfYes;    
                    UsbongUtils.addElementToContainer(usbongAnswerContainer, "Y,"+myTextFieldScreenEditText.getText().toString().trim()+";", usbongAnswerContainerCounter);
                  }
                  else {
                   currUsbongNode = nextUsbongNodeIfNo;                                               
                    UsbongUtils.addElementToContainer(usbongAnswerContainer, "N,"+myTextFieldScreenEditText.getText().toString().trim()+";", usbongAnswerContainerCounter);
                  }                    
                */
                usbongAnswerContainerCounter++;
                initParser();
            }
        } else if ((currScreen == UsbongConstants.TEXTAREA_SCREEN)) {
            currUsbongNode = nextUsbongNodeIfYes; //= nextIMCIQuestionIfNo will also do
            EditText myTextAreaScreenEditText = (EditText) findViewById(R.id.textarea_edittext);

            //                    if (UsbongUtils.IS_IN_DEBUG_MODE==false) {
            //if it's blank
            if (myTextAreaScreenEditText.getText().toString().trim().equals("")) {
                if (!UsbongUtils.IS_IN_DEBUG_MODE) {
                    if (!isAnOptionalNode) {
                        showRequiredFieldAlert(PLEASE_ANSWER_FIELD_ALERT_TYPE);
                        wasNextButtonPressed = false;
                        hasUpdatedDecisionTrackerContainer = true;
                        return;
                    }
                }
                //                          else {
                currUsbongNode = nextUsbongNodeIfYes; //nextUsbongNodeIfNo will also do, since this is "Any"
                UsbongUtils.addElementToContainer(usbongAnswerContainer, "A,;", usbongAnswerContainerCounter);
                usbongAnswerContainerCounter++;

                initParser();
                //                          }
            } else {
                //                        usbongAnswerContainer.addElement("A,"+myTextAreaScreenEditText.getText()+";");                     
                UsbongUtils.addElementToContainer(usbongAnswerContainer,
                        "A," + myTextAreaScreenEditText.getText() + ";", usbongAnswerContainerCounter);
                usbongAnswerContainerCounter++;

                initParser();
            }
        } else if (currScreen == UsbongConstants.TEXTAREA_WITH_ANSWER_SCREEN) {
            currUsbongNode = nextUsbongNodeIfYes;
            EditText myTextAreaScreenEditText = (EditText) findViewById(R.id.textarea_edittext);
            //if it's blank
            if (myTextAreaScreenEditText.getText().toString().trim().equals("")) {
                if (!UsbongUtils.IS_IN_DEBUG_MODE) {
                    if (!isAnOptionalNode) {
                        showRequiredFieldAlert(PLEASE_ANSWER_FIELD_ALERT_TYPE);
                        wasNextButtonPressed = false;
                        hasUpdatedDecisionTrackerContainer = true;
                        return;
                    }
                }
                currUsbongNode = nextUsbongNodeIfYes; //choose Yes if "Any"
                UsbongUtils.addElementToContainer(usbongAnswerContainer,
                        "A," + myTextAreaScreenEditText.getText().toString().trim() + ";",
                        usbongAnswerContainerCounter);
                usbongAnswerContainerCounter++;

                initParser();
            } else {
                /*                        
                  if (myTextAreaWithAnswerScreenAnswer.equals(myTextAreaScreenEditText.getText().toString().trim())) {
                   currUsbongNode = nextUsbongNodeIfYes;    
                    UsbongUtils.addElementToContainer(usbongAnswerContainer, "Y,"+myTextAreaScreenEditText.getText().toString().trim()+";", usbongAnswerContainerCounter);
                  }
                  else {
                   currUsbongNode = nextUsbongNodeIfNo;                                               
                    UsbongUtils.addElementToContainer(usbongAnswerContainer, "N,"+myTextAreaScreenEditText.getText().toString().trim()+";", usbongAnswerContainerCounter);
                  }                    
                */
                //added by Mike, Jan. 27, 2014
                Vector<String> myPossibleAnswers = new Vector<String>();
                StringTokenizer myPossibleAnswersStringTokenizer = new StringTokenizer(
                        myTextAreaWithAnswerScreenAnswer, "||");
                if (myPossibleAnswersStringTokenizer != null) {
                    while (myPossibleAnswersStringTokenizer.hasMoreTokens()) { //get last element (i.e. Mike in "textAreaWithAnswer~Who is the founder of Usbong (nickname)?Answer=Mike||mike")
                        myPossibleAnswers.add(myPossibleAnswersStringTokenizer.nextToken());
                    }
                }
                int size = myPossibleAnswers.size();
                for (int i = 0; i < size; i++) {
                    //                           Log.d(">>>>>>myPossibleAnswers: ",myPossibleAnswers.elementAt(i));
                    if (myPossibleAnswers.elementAt(i)
                            .equals(myTextAreaScreenEditText.getText().toString().trim())) {
                        currUsbongNode = nextUsbongNodeIfYes;
                        UsbongUtils.addElementToContainer(usbongAnswerContainer,
                                "Y," + myTextAreaScreenEditText.getText().toString().trim() + ";",
                                usbongAnswerContainerCounter);
                        break;
                    }

                    if (i == size - 1) { //if this is the last element in the vector
                        currUsbongNode = nextUsbongNodeIfNo;
                        UsbongUtils.addElementToContainer(usbongAnswerContainer,
                                "N," + myTextAreaScreenEditText.getText().toString().trim() + ";",
                                usbongAnswerContainerCounter);
                    }
                }
                usbongAnswerContainerCounter++;
                initParser();
            }
        } else if (currScreen == UsbongConstants.GPS_LOCATION_SCREEN) {
            currUsbongNode = nextUsbongNodeIfYes; //= nextIMCIQuestionIfNo will also do
            TextView myLongitudeTextView = (TextView) findViewById(R.id.longitude_textview);
            TextView myLatitudeTextView = (TextView) findViewById(R.id.latitude_textview);

            //                  usbongAnswerContainer.addElement(myLongitudeTextView.getText()+","+myLatitudeTextView.getText()+";");                     
            UsbongUtils.addElementToContainer(usbongAnswerContainer,
                    "A," + myLongitudeTextView.getText() + "," + myLatitudeTextView.getText() + ";",
                    usbongAnswerContainerCounter);
            usbongAnswerContainerCounter++;

            initParser();

        } else if (currScreen == UsbongConstants.SIMPLE_ENCRYPT_SCREEN) {
            EditText myPinEditText = (EditText) findViewById(R.id.pin_edittext);

            if (myPinEditText.getText().toString().length() != 4) {
                String message = "";
                if (currLanguageBeingUsed == UsbongUtils.LANGUAGE_FILIPINO) {
                    message = (String) getResources().getText(R.string.Usbong4DigitsPinAlertMessageFILIPINO);
                } else if (currLanguageBeingUsed == UsbongUtils.LANGUAGE_JAPANESE) {
                    message = (String) getResources().getText(R.string.Usbong4DigitsPinAlertMessageJAPANESE);
                } else { //if (udtea.currLanguageBeingUsed==UsbongUtils.LANGUAGE_ENGLISH) {
                    message = (String) getResources().getText(R.string.Usbong4DigitsPinAlertMessageENGLISH);
                }

                new AlertDialog.Builder(UsbongDecisionTreeEngineActivity.this).setTitle("Hey!")
                        .setMessage(message).setPositiveButton("OK", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                            }
                        }).show();
            } else {
                int yourKey = Integer.parseInt(myPinEditText.getText().toString());
                currUsbongNode = nextUsbongNodeIfYes; //= nextIMCIQuestionIfNo will also do

                UsbongUtils.addElementToContainer(usbongAnswerContainer, "A;", usbongAnswerContainerCounter);
                usbongAnswerContainerCounter++;

                //                  Log.d(">>>>>>>start encode","encode");
                for (int i = 0; i < usbongAnswerContainerCounter; i++) {
                    try {
                        usbongAnswerContainer.set(i, UsbongUtils.performSimpleFileEncrypt(yourKey,
                                usbongAnswerContainer.elementAt(i)));
                        //                        Log.d(">>>>>>"+i,""+usbongAnswerContainer.get(i));
                        //                        Log.d(">>>decoded"+i,""+UsbongUtils.performSimpleFileDecode(yourKey, usbongAnswerContainer.get(i)));
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }

                initParser();
            }
        } else if (currScreen == UsbongConstants.DATE_SCREEN) {
            currUsbongNode = nextUsbongNodeIfYes;
            //added by Mike, 13 Oct. 2015
            DatePicker myDatePicker = (DatePicker) findViewById(R.id.date_picker);
            UsbongUtils.addElementToContainer(usbongAnswerContainer, "A," + myDatePicker.getMonth()
                    + myDatePicker.getDayOfMonth() + "," + myDatePicker.getYear() + ";",
                    usbongAnswerContainerCounter);

            /*                   
                         Spinner dateMonthSpinner = (Spinner) findViewById(R.id.date_month_spinner);
                          Spinner dateDaySpinner = (Spinner) findViewById(R.id.date_day_spinner);
                          EditText myDateYearEditText = (EditText)findViewById(R.id.date_edittext);
            //             usbongAnswerContainer.addElement("A,"+monthAdapter.getItem(dateMonthSpinner.getSelectedItemPosition()).toString() +
            //                                      dayAdapter.getItem(dateDaySpinner.getSelectedItemPosition()).toString() + "," +
            //                                      myDateYearEditText.getText().toString()+";");                         
                         UsbongUtils.addElementToContainer(usbongAnswerContainer, "A,"+monthAdapter.getItem(dateMonthSpinner.getSelectedItemPosition()).toString() +
                              dayAdapter.getItem(dateDaySpinner.getSelectedItemPosition()).toString() + "," +
                              myDateYearEditText.getText().toString()+";", usbongAnswerContainerCounter);
            */
            usbongAnswerContainerCounter++;

            //             System.out.println(">>>>>>>>>>>>>Date screen: "+usbongAnswerContainer.lastElement());
            initParser();
        } else if (currScreen == UsbongConstants.TIMESTAMP_DISPLAY_SCREEN) {
            currUsbongNode = nextUsbongNodeIfYes;
            UsbongUtils.addElementToContainer(usbongAnswerContainer, timestampString + ";",
                    usbongAnswerContainerCounter);
            usbongAnswerContainerCounter++;

            initParser();
        } else if (currScreen == UsbongConstants.QR_CODE_READER_SCREEN) {
            currUsbongNode = nextUsbongNodeIfYes; //= nextIMCIQuestionIfNo will also do

            if (!myQRCodeContent.equals("")) {
                //                      usbongAnswerContainer.addElement("Y,"+myQRCodeContent+";");                     
                UsbongUtils.addElementToContainer(usbongAnswerContainer, "Y," + myQRCodeContent + ";",
                        usbongAnswerContainerCounter);
                usbongAnswerContainerCounter++;
            } else {
                //                      usbongAnswerContainer.addElement("N;");                                           
                UsbongUtils.addElementToContainer(usbongAnswerContainer, "N;", usbongAnswerContainerCounter);
                usbongAnswerContainerCounter++;
            }
            initParser();
        } else if ((currScreen == UsbongConstants.DCAT_SUMMARY_SCREEN)) {
            currUsbongNode = nextUsbongNodeIfYes; //= nextIMCIQuestionIfNo will also do
            /*
            LinearLayout myDCATSummaryLinearLayout = (LinearLayout)findViewById(R.id.dcat_summary_linearlayout);
            int total = myDCATSummaryLinearLayout.getChildCount();
                    
                              StringBuffer dcatSummary= new StringBuffer();
            for (int i=0; i<total; i++) {
               dcatSummary.append(((TextView) myDCATSummaryLinearLayout.getChildAt(i)).getText().toString());
            }
            */
            //                   UsbongUtils.addElementToContainer(usbongAnswerContainer, "dcat_end;", usbongAnswerContainerCounter);
            UsbongUtils.addElementToContainer(usbongAnswerContainer,
                    "dcat_end," + myDcatSummaryStringBuffer.toString() + ";", usbongAnswerContainerCounter);
            usbongAnswerContainerCounter++;

            initParser();
        }

        else { //TODO: do this for now                
            currUsbongNode = nextUsbongNodeIfYes; //nextUsbongNodeIfNo will also do, since this is "Any"
            //                  usbongAnswerContainer.addElement("A;");                                             
            UsbongUtils.addElementToContainer(usbongAnswerContainer, "A;", usbongAnswerContainerCounter);
            usbongAnswerContainerCounter++;

            initParser();
        }
    }
}

From source file:usbong.android.retrocc.UsbongDecisionTreeEngineActivity.java

public void processNextButtonPressed() {
    wasNextButtonPressed = true;/*from  w  w  w  .j ava2  s .c  o  m*/
    hasUpdatedDecisionTrackerContainer = false;

    //edited by Mike, 20160417
    if ((mTts != null) && (mTts.isSpeaking())) {
        mTts.stop();
    }
    //edited by Mike, 20160417
    if ((myMediaPlayer != null) && (myMediaPlayer.isPlaying())) {
        myMediaPlayer.stop();
    }

    if (currAudioRecorder != null) {
        try {
            //if stop button is pressable
            if (stopButton.isEnabled()) {
                currAudioRecorder.stop();
            }
            if (currAudioRecorder.isPlaying()) {
                currAudioRecorder.stopPlayback();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        String path = currAudioRecorder.getPath();
        //               System.out.println(">>>>>>>>>>>>>>>>>>>currAudioRecorder: "+currAudioRecorder);
        if (!attachmentFilePaths.contains(path)) {
            attachmentFilePaths.add(path);
            //                  System.out.println(">>>>>>>>>>>>>>>>adding path: "+path);
        }
    }

    //END_STATE_SCREEN = last screen
    if (currScreen == UsbongConstants.END_STATE_SCREEN) {
        int usbongAnswerContainerSize = usbongAnswerContainer.size();
        StringBuffer outputStringBuffer = new StringBuffer();
        for (int i = 0; i < usbongAnswerContainerSize; i++) {
            outputStringBuffer.append(usbongAnswerContainer.elementAt(i));
        }

        myOutputDirectory = UsbongUtils.getDateTimeStamp() + "/";
        if (UsbongUtils.STORE_OUTPUT) {
            try {
                UsbongUtils.createNewOutputFolderStructure();
            } catch (Exception e) {
                e.printStackTrace();
            }
            UsbongUtils.storeOutputInSDCard(
                    UsbongUtils.BASE_FILE_PATH + myOutputDirectory + UsbongUtils.getDateTimeStamp() + ".csv",
                    outputStringBuffer.toString());
        } else {
            UsbongUtils.deleteRecursive(new File(UsbongUtils.BASE_FILE_PATH + myOutputDirectory));
        }

        //wasNextButtonPressed=false; //no need to make this true, because this is the last node
        hasUpdatedDecisionTrackerContainer = true;

        /*
        //send to server
        UsbongUtils.performFileUpload(UsbongUtils.BASE_FILE_PATH + myOutputDirectory + UsbongUtils.getTimeStamp() + ".csv");
                 
        //send to email
        Intent emailIntent = UsbongUtils.performEmailProcess(UsbongUtils.BASE_FILE_PATH + myOutputDirectory + UsbongUtils.getTimeStamp() + ".csv", attachmentFilePaths);
        emailIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        //                emailIntent.addFlags(RESULT_OK);
        startActivityForResult(Intent.createChooser(emailIntent, "Email:"),EMAIL_SENDING_SUCCESS);
        */

        //added by Mike, Sept. 10, 2014
        UsbongUtils.clearTempFolder();

        //added by Mike, 20160415
        if (UsbongUtils.IS_IN_AUTO_LOOP_MODE) {
            //added by Mike, 20161117
            AppRater.showRateDialog(this);

            isAutoLoopedTree = true;
            initParser(myTree);
            return;
        } else {
            //return to main activity
            finish();
            //added by Mike, 20161117
            Intent toUsbongMainActivityIntent = new Intent(UsbongDecisionTreeEngineActivity.this,
                    UsbongMainActivity.class);
            toUsbongMainActivityIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            toUsbongMainActivityIntent.putExtra("completed_tree", "true");
            startActivity(toUsbongMainActivityIntent);
        }
    } else {
        if (currScreen == UsbongConstants.YES_NO_DECISION_SCREEN) {
            RadioButton myYesRadioButton = (RadioButton) findViewById(R.id.yes_radiobutton);
            RadioButton myNoRadioButton = (RadioButton) findViewById(R.id.no_radiobutton);

            if (myYesRadioButton.isChecked()) {
                currUsbongNode = nextUsbongNodeIfYes;

                UsbongUtils.addElementToContainer(usbongAnswerContainer, "Y;", usbongAnswerContainerCounter);
                usbongAnswerContainerCounter++;

                initParser();
            } else if (myNoRadioButton.isChecked()) {
                currUsbongNode = nextUsbongNodeIfNo;
                //                     usbongAnswerContainer.addElement("N;");                                             
                UsbongUtils.addElementToContainer(usbongAnswerContainer, "N;", usbongAnswerContainerCounter);
                usbongAnswerContainerCounter++;

                initParser();
            } else { //if no radio button was checked                       
                if (!UsbongUtils.IS_IN_DEBUG_MODE) {
                    if (!isAnOptionalNode) {
                        showRequiredFieldAlert(PLEASE_CHOOSE_AN_ANSWER_ALERT_TYPE);
                        wasNextButtonPressed = false;
                        hasUpdatedDecisionTrackerContainer = true;
                        return;
                    }
                }
                currUsbongNode = nextUsbongNodeIfYes; //nextUsbongNodeIfNo will also do, since this is "Any"
                UsbongUtils.addElementToContainer(usbongAnswerContainer, "A;", usbongAnswerContainerCounter);
                usbongAnswerContainerCounter++;

                initParser();
            }
        } else if (currScreen == UsbongConstants.SEND_TO_WEBSERVER_SCREEN) {
            RadioButton myYesRadioButton = (RadioButton) findViewById(R.id.yes_radiobutton);
            RadioButton myNoRadioButton = (RadioButton) findViewById(R.id.no_radiobutton);

            if (myYesRadioButton.isChecked()) {
                currUsbongNode = nextUsbongNodeIfYes;
                //                     usbongAnswerContainer.addElement("Y;");         
                UsbongUtils.addElementToContainer(usbongAnswerContainer, "Y;", usbongAnswerContainerCounter);
                usbongAnswerContainerCounter++;

                decisionTrackerContainer.addElement(usbongAnswerContainer.lastElement());
                //                     wasNextButtonPressed=false; //no need to make this true, because "Y;" has already been added to decisionTrackerContainer
                hasUpdatedDecisionTrackerContainer = true;

                //edited by Mike, March 4, 2013
                //"save" the output into the SDCard as "output.txt"
                //                      int usbongAnswerContainerSize = usbongAnswerContainer.size();
                int usbongAnswerContainerSize = usbongAnswerContainerCounter;

                StringBuffer outputStringBuffer = new StringBuffer();
                for (int i = 0; i < usbongAnswerContainerSize; i++) {
                    outputStringBuffer.append(usbongAnswerContainer.elementAt(i));
                }

                myOutputDirectory = UsbongUtils.getDateTimeStamp() + "/";
                try {
                    UsbongUtils.createNewOutputFolderStructure();
                } catch (Exception e) {
                    e.printStackTrace();
                }
                UsbongUtils.storeOutputInSDCard(UsbongUtils.BASE_FILE_PATH + myOutputDirectory
                        + UsbongUtils.getDateTimeStamp() + ".csv", outputStringBuffer.toString());

                //send to server
                UsbongUtils.performFileUpload(UsbongUtils.BASE_FILE_PATH + myOutputDirectory
                        + UsbongUtils.getDateTimeStamp() + ".csv");
            } else if (myNoRadioButton.isChecked()) {
                currUsbongNode = nextUsbongNodeIfNo;
                //                     usbongAnswerContainer.addElement("N;");                                             
                UsbongUtils.addElementToContainer(usbongAnswerContainer, "N;", usbongAnswerContainerCounter);
                usbongAnswerContainerCounter++;
            } else { //if no radio button was checked                       
                if (!UsbongUtils.IS_IN_DEBUG_MODE) {
                    if (!isAnOptionalNode) {
                        showRequiredFieldAlert(PLEASE_CHOOSE_AN_ANSWER_ALERT_TYPE);
                        wasNextButtonPressed = false;
                        hasUpdatedDecisionTrackerContainer = true;
                        return;
                    }
                }
                //                       else {
                currUsbongNode = nextUsbongNodeIfYes; //nextUsbongNodeIfNo will also do, since this is "Any"
                UsbongUtils.addElementToContainer(usbongAnswerContainer, "A;", usbongAnswerContainerCounter);
                usbongAnswerContainerCounter++;
                //                      initParser();            
            }
            initParser();
        } else if (currScreen == UsbongConstants.SEND_TO_CLOUD_BASED_SERVICE_SCREEN) {
            RadioButton myYesRadioButton = (RadioButton) findViewById(R.id.yes_radiobutton);
            RadioButton myNoRadioButton = (RadioButton) findViewById(R.id.no_radiobutton);

            if (myYesRadioButton.isChecked()) {
                currUsbongNode = nextUsbongNodeIfYes;
                //                     usbongAnswerContainer.addElement("Y;");                                             
                UsbongUtils.addElementToContainer(usbongAnswerContainer, "Y;", usbongAnswerContainerCounter);
                usbongAnswerContainerCounter++;

                decisionTrackerContainer.addElement(usbongAnswerContainer.lastElement());
                //                     wasNextButtonPressed=false; //no need to make this true, because "Y;" has already been added to decisionTrackerContainer
                hasUpdatedDecisionTrackerContainer = true;

                StringBuffer sb = new StringBuffer();
                for (int i = 0; i < decisionTrackerContainer.size(); i++) {
                    sb.append(decisionTrackerContainer.elementAt(i));
                }
                Log.d(">>>>>>>>>>>>>decisionTrackerContainer", sb.toString());

                //edited by Mike, March 4, 2013
                //"save" the output into the SDCard as "output.txt"
                //                      int usbongAnswerContainerSize = usbongAnswerContainer.size();
                int usbongAnswerContainerSize = usbongAnswerContainerCounter;

                StringBuffer outputStringBuffer = new StringBuffer();
                for (int i = 0; i < usbongAnswerContainerSize; i++) {
                    outputStringBuffer.append(usbongAnswerContainer.elementAt(i));
                }

                myOutputDirectory = UsbongUtils.getDateTimeStamp() + "/";
                try {
                    UsbongUtils.createNewOutputFolderStructure();
                } catch (Exception e) {
                    e.printStackTrace();
                }
                UsbongUtils.storeOutputInSDCard(UsbongUtils.BASE_FILE_PATH + myOutputDirectory
                        + UsbongUtils.getDateTimeStamp() + ".csv", outputStringBuffer.toString());

                //send to cloud-based service
                Intent sendToCloudBasedServiceIntent = UsbongUtils
                        .performSendToCloudBasedServiceProcess(UsbongUtils.BASE_FILE_PATH + myOutputDirectory
                                + UsbongUtils.getDateTimeStamp() + ".csv", attachmentFilePaths);
                /*emailIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                */
                //                      emailIntent.addFlags(RESULT_OK);
                //                      startActivityForResult(Intent.createChooser(emailIntent, "Email:"),EMAIL_SENDING_SUCCESS);
                //answer from Llango J, stackoverflow
                //Reference: http://stackoverflow.com/questions/7479883/problem-with-sending-email-goes-back-to-previous-activity;
                //last accessed: 22 Oct. 2012
                startActivity(Intent.createChooser(sendToCloudBasedServiceIntent, "Email Book Request:"));
            } else if (myNoRadioButton.isChecked()) {
                currUsbongNode = nextUsbongNodeIfNo;
                //                     usbongAnswerContainer.addElement("N;");                                             
                UsbongUtils.addElementToContainer(usbongAnswerContainer, "N;", usbongAnswerContainerCounter);
                usbongAnswerContainerCounter++;
            } else { //if no radio button was checked                       
                if (!UsbongUtils.IS_IN_DEBUG_MODE) {
                    if (!isAnOptionalNode) {
                        showRequiredFieldAlert(PLEASE_CHOOSE_AN_ANSWER_ALERT_TYPE);
                        wasNextButtonPressed = false;
                        hasUpdatedDecisionTrackerContainer = true;
                        return;
                    }
                }
                //                       else {
                currUsbongNode = nextUsbongNodeIfYes; //nextUsbongNodeIfNo will also do, since this is "Any"
                UsbongUtils.addElementToContainer(usbongAnswerContainer, "A;", usbongAnswerContainerCounter);
                usbongAnswerContainerCounter++;
                //                      initParser();            

                /*
                                       if (!isAnOptionalNode) {
                  showRequiredFieldAlert(PLEASE_CHOOSE_AN_ANSWER_ALERT_TYPE);
                 wasNextButtonPressed=false;
                 hasUpdatedDecisionTrackerContainer=true;
                         
                 return;
                                       }
                                       else {
                 currUsbongNode = nextUsbongNodeIfYes; //nextUsbongNodeIfNo will also do, since this is "Any"
                //                        usbongAnswerContainer.addElement("A;");                                             
                 UsbongUtils.addElementToContainer(usbongAnswerContainer, "A;", usbongAnswerContainerCounter);
                usbongAnswerContainerCounter++;
                        
                initParser();            
                                       }
                */
            }
            /*                    
                              currUsbongNode = nextUsbongNodeIfYes; //nextUsbongNodeIfNo will also do, since this is "Any"
                              usbongAnswerContainer.addElement("Any;");                                             
            */
            initParser();
        } else if (currScreen == UsbongConstants.MULTIPLE_CHECKBOXES_SCREEN) {
            //                   requiredTotalCheckedBoxes   
            LinearLayout myMultipleCheckboxesLinearLayout = (LinearLayout) findViewById(
                    R.id.multiple_checkboxes_linearlayout);
            StringBuffer sb = new StringBuffer();
            int totalCheckedBoxes = 0;
            int totalCheckBoxChildren = myMultipleCheckboxesLinearLayout.getChildCount();
            //begin with i=1, because i=0 is for checkboxes_textview
            for (int i = 1; i < totalCheckBoxChildren; i++) {
                if (((CheckBox) myMultipleCheckboxesLinearLayout.getChildAt(i)).isChecked()) {
                    totalCheckedBoxes++;
                    sb.append("," + (i - 1)); //do a (i-1) so that i starts with 0 for the checkboxes (excluding checkboxes_textview) to maintain consistency with the other components
                }
            }

            if (totalCheckedBoxes >= requiredTotalCheckedBoxes) {
                currUsbongNode = nextUsbongNodeIfYes;
                sb.insert(0, "Y"); //insert in front of stringBuffer
                sb.append(";");
            } else {
                currUsbongNode = nextUsbongNodeIfNo;
                sb.delete(0, sb.length());
                sb.append("N,;"); //make sure to add the comma
            }
            //                   usbongAnswerContainer.addElement(sb.toString());
            UsbongUtils.addElementToContainer(usbongAnswerContainer, sb.toString(),
                    usbongAnswerContainerCounter);
            usbongAnswerContainerCounter++;

            initParser();
        } else if (currScreen == UsbongConstants.MULTIPLE_RADIO_BUTTONS_SCREEN) {
            currUsbongNode = nextUsbongNodeIfYes; //nextUsbongNodeIfNo will also do, since this is "Any"
            RadioGroup myRadioGroup = (RadioGroup) findViewById(R.id.multiple_radio_buttons_radiogroup);

            //                   if (UsbongUtils.IS_IN_DEBUG_MODE==false) {
            if (myRadioGroup.getCheckedRadioButtonId() == -1) { //no radio button checked
                if (!UsbongUtils.IS_IN_DEBUG_MODE) {
                    if (!isAnOptionalNode) {
                        showRequiredFieldAlert(PLEASE_CHOOSE_AN_ANSWER_ALERT_TYPE);
                        wasNextButtonPressed = false;
                        hasUpdatedDecisionTrackerContainer = true;
                        return;
                    }
                }
                //                          else {
                currUsbongNode = nextUsbongNodeIfYes; //nextUsbongNodeIfNo will also do, since this is "Any"
                UsbongUtils.addElementToContainer(usbongAnswerContainer, "A;", usbongAnswerContainerCounter);
                usbongAnswerContainerCounter++;

                initParser();
                //                          }
            } else {
                //                         usbongAnswerContainer.addElement(myRadioGroup.getCheckedRadioButtonId()+";");
                UsbongUtils.addElementToContainer(usbongAnswerContainer,
                        myRadioGroup.getCheckedRadioButtonId() + ";", usbongAnswerContainerCounter);
                usbongAnswerContainerCounter++;

                initParser();
            }
            //                   }
            /*                   
                               else {
            //                      usbongAnswerContainer.addElement(myRadioGroup.getCheckedRadioButtonId()+";");
              UsbongUtils.addElementToContainer(usbongAnswerContainer, myRadioGroup.getCheckedRadioButtonId()+";", usbongAnswerContainerCounter);
             usbongAnswerContainerCounter++;
                      
              initParser();                      
                               }
            */
        } else if (currScreen == UsbongConstants.MULTIPLE_RADIO_BUTTONS_WITH_ANSWER_SCREEN) {
            currUsbongNode = nextUsbongNodeIfYes; //nextUsbongNodeIfNo will also do, since this is "Any"
            RadioGroup myRadioGroup = (RadioGroup) findViewById(R.id.multiple_radio_buttons_radiogroup);

            /*                   if (UsbongUtils.IS_IN_DEBUG_MODE==false) {
             */
            if (myRadioGroup.getCheckedRadioButtonId() == -1) { //no radio button checked                                                  
                if (!UsbongUtils.IS_IN_DEBUG_MODE) {
                    if (!isAnOptionalNode) {
                        showRequiredFieldAlert(PLEASE_CHOOSE_AN_ANSWER_ALERT_TYPE);
                        wasNextButtonPressed = false;
                        hasUpdatedDecisionTrackerContainer = true;
                        return;
                    }
                }
                //                          else {
                currUsbongNode = nextUsbongNodeIfYes; //choose Yes if "Any"
                UsbongUtils.addElementToContainer(usbongAnswerContainer,
                        "A," + myRadioGroup.getCheckedRadioButtonId() + ";", usbongAnswerContainerCounter);
                usbongAnswerContainerCounter++;

                initParser();
                //                          }
            } else {
                if (myMultipleRadioButtonsWithAnswerScreenAnswer
                        .equals("" + myRadioGroup.getCheckedRadioButtonId())) {
                    currUsbongNode = nextUsbongNodeIfYes;
                    UsbongUtils.addElementToContainer(usbongAnswerContainer,
                            "Y," + myRadioGroup.getCheckedRadioButtonId() + ";", usbongAnswerContainerCounter);
                } else {
                    currUsbongNode = nextUsbongNodeIfNo;
                    UsbongUtils.addElementToContainer(usbongAnswerContainer,
                            "N," + myRadioGroup.getCheckedRadioButtonId() + ";", usbongAnswerContainerCounter);
                }

                usbongAnswerContainerCounter++;
                initParser();
            }
        } else if (currScreen == UsbongConstants.LINK_SCREEN) {
            RadioGroup myRadioGroup = (RadioGroup) findViewById(R.id.multiple_radio_buttons_radiogroup);

            try {
                currUsbongNode = UsbongUtils.getLinkFromRadioButton(
                        radioButtonsContainer.elementAt(myRadioGroup.getCheckedRadioButtonId()));
            } catch (Exception e) {
                //if the user hasn't ticked any radio button yet
                //put the currUsbongNode to default
                currUsbongNode = UsbongUtils.getLinkFromRadioButton(nextUsbongNodeIfYes); //nextUsbongNodeIfNo will also do, since this is "Any"
                //of course, showPleaseAnswerAlert() will be called                        
            }

            //                   Log.d(">>>>>>>>>>currUsbongNode",currUsbongNode);
            if (myRadioGroup.getCheckedRadioButtonId() == -1) { //no radio button checked
                //                         if (!UsbongUtils.IS_IN_DEBUG_MODE) {
                if (!isAnOptionalNode) {
                    showRequiredFieldAlert(PLEASE_CHOOSE_AN_ANSWER_ALERT_TYPE);
                    wasNextButtonPressed = false;
                    hasUpdatedDecisionTrackerContainer = true;

                    return;
                }
                //                         }
                //                          else {
                currUsbongNode = nextUsbongNodeIfYes; //nextUsbongNodeIfNo will also do, since this is "Any"
                UsbongUtils.addElementToContainer(usbongAnswerContainer, "A;", usbongAnswerContainerCounter);
                usbongAnswerContainerCounter++;

                initParser();
                //                          }
            } else {
                //                         usbongAnswerContainer.addElement(myRadioGroup.getCheckedRadioButtonId()+";");
                UsbongUtils.addElementToContainer(usbongAnswerContainer,
                        myRadioGroup.getCheckedRadioButtonId() + ";", usbongAnswerContainerCounter);
                usbongAnswerContainerCounter++;

                initParser();
            }
            /*                   }
                               else {
              usbongAnswerContainer.addElement(myRadioGroup.getCheckedRadioButtonId()+";");
               initParser();                      
                               }
            */
        } else if ((currScreen == UsbongConstants.TEXTFIELD_SCREEN)
                || (currScreen == UsbongConstants.TEXTFIELD_WITH_UNIT_SCREEN)
                || (currScreen == UsbongConstants.TEXTFIELD_NUMERICAL_SCREEN)) {
            currUsbongNode = nextUsbongNodeIfYes; //= nextIMCIQuestionIfNo will also do
            EditText myTextFieldScreenEditText = (EditText) findViewById(R.id.textfield_edittext);

            //                    if (UsbongUtils.IS_IN_DEBUG_MODE==false) {
            //if it's blank
            if (myTextFieldScreenEditText.getText().toString().trim().equals("")) {
                if (!UsbongUtils.IS_IN_DEBUG_MODE) {
                    if (!isAnOptionalNode) {
                        showRequiredFieldAlert(PLEASE_ANSWER_FIELD_ALERT_TYPE);
                        wasNextButtonPressed = false;
                        hasUpdatedDecisionTrackerContainer = true;
                        return;
                    }
                }
                //                          else {
                currUsbongNode = nextUsbongNodeIfYes; //nextUsbongNodeIfNo will also do, since this is "Any"
                //                           usbongAnswerContainer.addElement("A;");                                             
                UsbongUtils.addElementToContainer(usbongAnswerContainer, "A,;", usbongAnswerContainerCounter);
                usbongAnswerContainerCounter++;

                initParser();
                //                          }
            } else {
                //added by Mike, 20170207
                TextView myTextFieldScreenTextView = (TextView) this.findViewById(R.id.textfield_textview);

                //Reference: http://stackoverflow.com/questions/23024831/android-shared-preferences-example
                //; last accessed: 20150609
                //answer by Elenasys
                //added by Mike, 20170207
                SharedPreferences.Editor editor = getSharedPreferences(UsbongConstants.MY_ACCOUNT_DETAILS,
                        MODE_PRIVATE).edit();
                if (myTextFieldScreenTextView.getText().toString().contains("First Name")) {
                    editor.putString("firstName", myTextFieldScreenEditText.getText().toString());
                } else if (myTextFieldScreenTextView.getText().toString().contains("Surname")) {
                    editor.putString("surname", myTextFieldScreenEditText.getText().toString());
                } else if (myTextFieldScreenTextView.getText().toString().contains("Contact Number")) {
                    editor.putString("contactNumber", myTextFieldScreenEditText.getText().toString());
                } else if (myTextFieldScreenTextView.getText().toString().contains("Shipping Address")) {
                    editor.putString("shippingAddress", myTextFieldScreenEditText.getText().toString());
                }
                editor.commit();

                //                        usbongAnswerContainer.addElement("A,"+myTextFieldScreenEditText.getText()+";");                     
                UsbongUtils.addElementToContainer(usbongAnswerContainer,
                        "A," + myTextFieldScreenEditText.getText() + ";", usbongAnswerContainerCounter);
                usbongAnswerContainerCounter++;

                initParser();
            }
        } else if (currScreen == UsbongConstants.TEXTFIELD_WITH_ANSWER_SCREEN) {
            currUsbongNode = nextUsbongNodeIfYes;
            EditText myTextFieldScreenEditText = (EditText) findViewById(R.id.textfield_edittext);
            //if it's blank
            if (myTextFieldScreenEditText.getText().toString().trim().equals("")) {
                if (!UsbongUtils.IS_IN_DEBUG_MODE) {
                    if (!isAnOptionalNode) {
                        showRequiredFieldAlert(PLEASE_ANSWER_FIELD_ALERT_TYPE);
                        wasNextButtonPressed = false;
                        hasUpdatedDecisionTrackerContainer = true;
                        return;
                    }
                }
                currUsbongNode = nextUsbongNodeIfYes; //choose Yes if "Any"
                UsbongUtils.addElementToContainer(usbongAnswerContainer,
                        "A," + myTextFieldScreenEditText.getText().toString().trim() + ";",
                        usbongAnswerContainerCounter);
                usbongAnswerContainerCounter++;

                initParser();
            } else {
                //added by Mike, Jan. 27, 2014
                Vector<String> myPossibleAnswers = new Vector<String>();
                StringTokenizer myPossibleAnswersStringTokenizer = new StringTokenizer(
                        myTextFieldWithAnswerScreenAnswer, "||");
                if (myPossibleAnswersStringTokenizer != null) {
                    while (myPossibleAnswersStringTokenizer.hasMoreTokens()) { //get last element (i.e. Mike in "textFieldWithAnswer~Who is the founder of Usbong (nickname)?Answer=Mike")
                        myPossibleAnswers.add(myPossibleAnswersStringTokenizer.nextToken());
                    }
                }
                int size = myPossibleAnswers.size();
                for (int i = 0; i < size; i++) {
                    if (myPossibleAnswers.elementAt(i)
                            .equals(myTextFieldScreenEditText.getText().toString().trim())) {
                        currUsbongNode = nextUsbongNodeIfYes;
                        UsbongUtils.addElementToContainer(usbongAnswerContainer,
                                "Y," + myTextFieldScreenEditText.getText().toString().trim() + ";",
                                usbongAnswerContainerCounter);
                        break;
                    }

                    if (i == size - 1) { //if this is the last element in the vector
                        currUsbongNode = nextUsbongNodeIfNo;
                        UsbongUtils.addElementToContainer(usbongAnswerContainer,
                                "N," + myTextFieldScreenEditText.getText().toString().trim() + ";",
                                usbongAnswerContainerCounter);
                    }
                }
                /*                        
                  if (myTextFieldWithAnswerScreenAnswer.equals(myTextFieldScreenEditText.getText().toString().trim())) {
                   currUsbongNode = nextUsbongNodeIfYes;    
                    UsbongUtils.addElementToContainer(usbongAnswerContainer, "Y,"+myTextFieldScreenEditText.getText().toString().trim()+";", usbongAnswerContainerCounter);
                  }
                  else {
                   currUsbongNode = nextUsbongNodeIfNo;                                               
                    UsbongUtils.addElementToContainer(usbongAnswerContainer, "N,"+myTextFieldScreenEditText.getText().toString().trim()+";", usbongAnswerContainerCounter);
                  }                    
                */
                usbongAnswerContainerCounter++;
                initParser();
            }
        } else if ((currScreen == UsbongConstants.TEXTAREA_SCREEN)) {
            currUsbongNode = nextUsbongNodeIfYes; //= nextIMCIQuestionIfNo will also do
            EditText myTextAreaScreenEditText = (EditText) findViewById(R.id.textarea_edittext);

            //                    if (UsbongUtils.IS_IN_DEBUG_MODE==false) {
            //if it's blank
            if (myTextAreaScreenEditText.getText().toString().trim().equals("")) {
                if (!UsbongUtils.IS_IN_DEBUG_MODE) {
                    if (!isAnOptionalNode) {
                        showRequiredFieldAlert(PLEASE_ANSWER_FIELD_ALERT_TYPE);
                        wasNextButtonPressed = false;
                        hasUpdatedDecisionTrackerContainer = true;
                        return;
                    }
                }
                //                          else {
                currUsbongNode = nextUsbongNodeIfYes; //nextUsbongNodeIfNo will also do, since this is "Any"
                UsbongUtils.addElementToContainer(usbongAnswerContainer, "A,;", usbongAnswerContainerCounter);
                usbongAnswerContainerCounter++;

                initParser();
                //                          }
            } else {
                //                        usbongAnswerContainer.addElement("A,"+myTextAreaScreenEditText.getText()+";");                     
                UsbongUtils.addElementToContainer(usbongAnswerContainer,
                        "A," + myTextAreaScreenEditText.getText() + ";", usbongAnswerContainerCounter);
                usbongAnswerContainerCounter++;

                initParser();
            }
        } else if (currScreen == UsbongConstants.TEXTAREA_WITH_ANSWER_SCREEN) {
            currUsbongNode = nextUsbongNodeIfYes;
            EditText myTextAreaScreenEditText = (EditText) findViewById(R.id.textarea_edittext);
            //if it's blank
            if (myTextAreaScreenEditText.getText().toString().trim().equals("")) {
                if (!UsbongUtils.IS_IN_DEBUG_MODE) {
                    if (!isAnOptionalNode) {
                        showRequiredFieldAlert(PLEASE_ANSWER_FIELD_ALERT_TYPE);
                        wasNextButtonPressed = false;
                        hasUpdatedDecisionTrackerContainer = true;
                        return;
                    }
                }
                currUsbongNode = nextUsbongNodeIfYes; //choose Yes if "Any"
                UsbongUtils.addElementToContainer(usbongAnswerContainer,
                        "A," + myTextAreaScreenEditText.getText().toString().trim() + ";",
                        usbongAnswerContainerCounter);
                usbongAnswerContainerCounter++;

                initParser();
            } else {
                /*                        
                  if (myTextAreaWithAnswerScreenAnswer.equals(myTextAreaScreenEditText.getText().toString().trim())) {
                   currUsbongNode = nextUsbongNodeIfYes;    
                    UsbongUtils.addElementToContainer(usbongAnswerContainer, "Y,"+myTextAreaScreenEditText.getText().toString().trim()+";", usbongAnswerContainerCounter);
                  }
                  else {
                   currUsbongNode = nextUsbongNodeIfNo;                                               
                    UsbongUtils.addElementToContainer(usbongAnswerContainer, "N,"+myTextAreaScreenEditText.getText().toString().trim()+";", usbongAnswerContainerCounter);
                  }                    
                */
                //added by Mike, Jan. 27, 2014
                Vector<String> myPossibleAnswers = new Vector<String>();
                StringTokenizer myPossibleAnswersStringTokenizer = new StringTokenizer(
                        myTextAreaWithAnswerScreenAnswer, "||");
                if (myPossibleAnswersStringTokenizer != null) {
                    while (myPossibleAnswersStringTokenizer.hasMoreTokens()) { //get last element (i.e. Mike in "textAreaWithAnswer~Who is the founder of Usbong (nickname)?Answer=Mike||mike")
                        myPossibleAnswers.add(myPossibleAnswersStringTokenizer.nextToken());
                    }
                }
                int size = myPossibleAnswers.size();
                for (int i = 0; i < size; i++) {
                    //                           Log.d(">>>>>>myPossibleAnswers: ",myPossibleAnswers.elementAt(i));
                    if (myPossibleAnswers.elementAt(i)
                            .equals(myTextAreaScreenEditText.getText().toString().trim())) {
                        currUsbongNode = nextUsbongNodeIfYes;
                        UsbongUtils.addElementToContainer(usbongAnswerContainer,
                                "Y," + myTextAreaScreenEditText.getText().toString().trim() + ";",
                                usbongAnswerContainerCounter);
                        break;
                    }

                    if (i == size - 1) { //if this is the last element in the vector
                        currUsbongNode = nextUsbongNodeIfNo;
                        UsbongUtils.addElementToContainer(usbongAnswerContainer,
                                "N," + myTextAreaScreenEditText.getText().toString().trim() + ";",
                                usbongAnswerContainerCounter);
                    }
                }
                usbongAnswerContainerCounter++;
                initParser();
            }
        } else if (currScreen == UsbongConstants.GPS_LOCATION_SCREEN) {
            currUsbongNode = nextUsbongNodeIfYes; //= nextIMCIQuestionIfNo will also do
            TextView myLongitudeTextView = (TextView) findViewById(R.id.longitude_textview);
            TextView myLatitudeTextView = (TextView) findViewById(R.id.latitude_textview);

            //                  usbongAnswerContainer.addElement(myLongitudeTextView.getText()+","+myLatitudeTextView.getText()+";");                     
            UsbongUtils.addElementToContainer(usbongAnswerContainer,
                    "A," + myLongitudeTextView.getText() + "," + myLatitudeTextView.getText() + ";",
                    usbongAnswerContainerCounter);
            usbongAnswerContainerCounter++;

            initParser();

        } else if (currScreen == UsbongConstants.SIMPLE_ENCRYPT_SCREEN) {
            EditText myPinEditText = (EditText) findViewById(R.id.pin_edittext);

            if (myPinEditText.getText().toString().length() != 4) {
                String message = "";
                if (currLanguageBeingUsed == UsbongUtils.LANGUAGE_FILIPINO) {
                    message = (String) getResources().getText(R.string.Usbong4DigitsPinAlertMessageFILIPINO);
                } else if (currLanguageBeingUsed == UsbongUtils.LANGUAGE_JAPANESE) {
                    message = (String) getResources().getText(R.string.Usbong4DigitsPinAlertMessageJAPANESE);
                } else { //if (udtea.currLanguageBeingUsed==UsbongUtils.LANGUAGE_ENGLISH) {
                    message = (String) getResources().getText(R.string.Usbong4DigitsPinAlertMessageENGLISH);
                }

                new AlertDialog.Builder(UsbongDecisionTreeEngineActivity.this).setTitle("Hey!")
                        .setMessage(message).setPositiveButton("OK", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                            }
                        }).show();
            } else {
                int yourKey = Integer.parseInt(myPinEditText.getText().toString());
                currUsbongNode = nextUsbongNodeIfYes; //= nextIMCIQuestionIfNo will also do

                UsbongUtils.addElementToContainer(usbongAnswerContainer, "A;", usbongAnswerContainerCounter);
                usbongAnswerContainerCounter++;

                //                  Log.d(">>>>>>>start encode","encode");
                for (int i = 0; i < usbongAnswerContainerCounter; i++) {
                    try {
                        usbongAnswerContainer.set(i, UsbongUtils.performSimpleFileEncrypt(yourKey,
                                usbongAnswerContainer.elementAt(i)));
                        //                        Log.d(">>>>>>"+i,""+usbongAnswerContainer.get(i));
                        //                        Log.d(">>>decoded"+i,""+UsbongUtils.performSimpleFileDecode(yourKey, usbongAnswerContainer.get(i)));
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }

                initParser();
            }
        } else if (currScreen == UsbongConstants.DATE_SCREEN) {
            currUsbongNode = nextUsbongNodeIfYes;
            Spinner dateMonthSpinner = (Spinner) findViewById(R.id.date_month_spinner);
            Spinner dateDaySpinner = (Spinner) findViewById(R.id.date_day_spinner);
            EditText myDateYearEditText = (EditText) findViewById(R.id.date_edittext);
            /*                   usbongAnswerContainer.addElement("A,"+monthAdapter.getItem(dateMonthSpinner.getSelectedItemPosition()).toString() +
                                    dayAdapter.getItem(dateDaySpinner.getSelectedItemPosition()).toString() + "," +
                                    myDateYearEditText.getText().toString()+";");                         
            */
            UsbongUtils.addElementToContainer(usbongAnswerContainer,
                    "A," + monthAdapter.getItem(dateMonthSpinner.getSelectedItemPosition()).toString()
                            + dayAdapter.getItem(dateDaySpinner.getSelectedItemPosition()).toString() + ","
                            + myDateYearEditText.getText().toString() + ";",
                    usbongAnswerContainerCounter);
            usbongAnswerContainerCounter++;

            //                   System.out.println(">>>>>>>>>>>>>Date screen: "+usbongAnswerContainer.lastElement());
            initParser();
        } else if (currScreen == UsbongConstants.TIMESTAMP_DISPLAY_SCREEN) {
            currUsbongNode = nextUsbongNodeIfYes;
            UsbongUtils.addElementToContainer(usbongAnswerContainer, timestampString + ";",
                    usbongAnswerContainerCounter);
            usbongAnswerContainerCounter++;

            initParser();
        } else if (currScreen == UsbongConstants.QR_CODE_READER_SCREEN) {
            currUsbongNode = nextUsbongNodeIfYes; //= nextIMCIQuestionIfNo will also do

            if (!myQRCodeContent.equals("")) {
                //                      usbongAnswerContainer.addElement("Y,"+myQRCodeContent+";");                     
                UsbongUtils.addElementToContainer(usbongAnswerContainer, "Y," + myQRCodeContent + ";",
                        usbongAnswerContainerCounter);
                usbongAnswerContainerCounter++;
            } else {
                //                      usbongAnswerContainer.addElement("N;");                                           
                UsbongUtils.addElementToContainer(usbongAnswerContainer, "N;", usbongAnswerContainerCounter);
                usbongAnswerContainerCounter++;
            }
            initParser();
        } else if ((currScreen == UsbongConstants.DCAT_SUMMARY_SCREEN)) {
            currUsbongNode = nextUsbongNodeIfYes; //= nextIMCIQuestionIfNo will also do
            /*
            LinearLayout myDCATSummaryLinearLayout = (LinearLayout)findViewById(R.id.dcat_summary_linearlayout);
            int total = myDCATSummaryLinearLayout.getChildCount();
                    
                              StringBuffer dcatSummary= new StringBuffer();
            for (int i=0; i<total; i++) {
               dcatSummary.append(((TextView) myDCATSummaryLinearLayout.getChildAt(i)).getText().toString());
            }
            */
            //                   UsbongUtils.addElementToContainer(usbongAnswerContainer, "dcat_end;", usbongAnswerContainerCounter);
            UsbongUtils.addElementToContainer(usbongAnswerContainer,
                    "dcat_end," + myDcatSummaryStringBuffer.toString() + ";", usbongAnswerContainerCounter);
            usbongAnswerContainerCounter++;

            initParser();
        }

        else { //TODO: do this for now                
            currUsbongNode = nextUsbongNodeIfYes; //nextUsbongNodeIfNo will also do, since this is "Any"
            //                  usbongAnswerContainer.addElement("A;");                                             
            UsbongUtils.addElementToContainer(usbongAnswerContainer, "A;", usbongAnswerContainerCounter);
            usbongAnswerContainerCounter++;

            initParser();
        }
    }
}

From source file:fiskinfoo.no.sintef.fiskinfoo.Implementation.UtilityOnClickListeners.java

@Override
public OnClickListener getSubscriptionCheckBoxOnClickListener(final PropertyDescription subscription,
        final Subscription activeSubscription, final User user) {
    return new OnClickListener() {
        @Override/*w w  w .  j  a v  a  2s .com*/
        public void onClick(final View v) {
            UtilityRowsInterface utilityRowsInterface = new UtilityRows();
            final FiskInfoUtility fiskInfoUtility = new FiskInfoUtility();

            final Dialog dialog;

            int iconId = fiskInfoUtility.subscriptionApiNameToIconId(subscription.ApiName);

            if (iconId != -1) {
                dialog = new UtilityDialogs().getDialogWithTitleIcon(v.getContext(),
                        R.layout.dialog_manage_subscription, subscription.Name, iconId);
            } else {
                dialog = new UtilityDialogs().getDialog(v.getContext(), R.layout.dialog_manage_subscription,
                        subscription.Name);
            }

            final Switch subscribedSwitch = (Switch) dialog.findViewById(R.id.manage_subscription_switch);
            final LinearLayout formatsContainer = (LinearLayout) dialog
                    .findViewById(R.id.manage_subscription_formats_container);
            final LinearLayout intervalsContainer = (LinearLayout) dialog
                    .findViewById(R.id.manage_subscription_intervals_container);
            final EditText subscriptionEmailEditText = (EditText) dialog
                    .findViewById(R.id.manage_subscription_email_edit_text);

            final Button subscribeButton = (Button) dialog.findViewById(R.id.manage_subscription_update_button);
            Button cancelButton = (Button) dialog.findViewById(R.id.manage_subscription_cancel_button);

            final boolean isSubscribed = activeSubscription != null;
            final Map<String, String> subscriptionFrequencies = new HashMap<>();

            dialog.setTitle(subscription.Name);

            if (isSubscribed) {
                subscriptionEmailEditText.setText(activeSubscription.SubscriptionEmail);

                subscribedSwitch.setVisibility(View.VISIBLE);
                subscribedSwitch.setChecked(true);
                subscribedSwitch
                        .setText(v.getResources().getString(R.string.manage_subscription_subscription_active));

                subscribedSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                    @Override
                    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                        System.out.println("This is checked:" + isChecked);
                        String switchText = isChecked
                                ? v.getResources().getString(R.string.manage_subscription_subscription_active)
                                : v.getResources()
                                        .getString(R.string.manage_subscription_subscription_cancellation);
                        subscribedSwitch.setText(switchText);
                    }
                });
            } else {
                subscriptionEmailEditText.setText(user.getUsername());
            }

            for (String format : subscription.Formats) {
                final RadioButtonRow row = utilityRowsInterface.getRadioButtonRow(v.getContext(), format);
                if (isSubscribed && activeSubscription.FileFormatType.equals(format)) {
                    row.setSelected(true);
                }

                formatsContainer.addView(row.getView());
            }

            for (String interval : subscription.SubscriptionInterval) {
                final RadioButtonRow row = utilityRowsInterface.getRadioButtonRow(v.getContext(),
                        SubscriptionInterval.getType(interval).toString());

                if (activeSubscription != null) {
                    row.setSelected(activeSubscription.SubscriptionIntervalName.equals(interval));
                }

                subscriptionFrequencies.put(SubscriptionInterval.getType(interval).toString(), interval);
                intervalsContainer.addView(row.getView());
            }

            if (intervalsContainer.getChildCount() == 1) {
                ((RadioButton) intervalsContainer.getChildAt(0)
                        .findViewById(R.id.radio_button_row_radio_button)).setChecked(true);
            }

            subscribeButton.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View subscribeButton) {
                    String subscriptionFormat = null;
                    String subscriptionInterval = null;
                    String subscriptionEmail;

                    BarentswatchApi barentswatchApi = new BarentswatchApi();
                    barentswatchApi.setAccesToken(user.getToken());
                    final IBarentswatchApi api = barentswatchApi.getApi();

                    for (int i = 0; i < formatsContainer.getChildCount(); i++) {
                        if (((RadioButton) formatsContainer.getChildAt(i)
                                .findViewById(R.id.radio_button_row_radio_button)).isChecked()) {
                            subscriptionFormat = ((TextView) formatsContainer.getChildAt(i)
                                    .findViewById(R.id.radio_button_row_text_view)).getText().toString();
                            break;
                        }
                    }

                    if (subscriptionFormat == null) {
                        Toast.makeText(v.getContext(),
                                v.getContext().getString(R.string.choose_subscription_format),
                                Toast.LENGTH_LONG).show();
                        return;
                    }

                    for (int i = 0; i < intervalsContainer.getChildCount(); i++) {
                        if (((RadioButton) intervalsContainer.getChildAt(i)
                                .findViewById(R.id.radio_button_row_radio_button)).isChecked()) {
                            subscriptionInterval = ((TextView) intervalsContainer.getChildAt(i)
                                    .findViewById(R.id.radio_button_row_text_view)).getText().toString();
                            break;
                        }
                    }

                    if (subscriptionInterval == null) {
                        Toast.makeText(v.getContext(),
                                v.getContext().getString(R.string.choose_subscription_interval),
                                Toast.LENGTH_LONG).show();
                        return;
                    }

                    subscriptionEmail = subscriptionEmailEditText.getText().toString();

                    if (!(new FiskInfoUtility().isEmailValid(subscriptionEmail))) {
                        Toast.makeText(v.getContext(), v.getContext().getString(R.string.error_invalid_email),
                                Toast.LENGTH_LONG).show();
                        return;
                    }

                    if (isSubscribed) {
                        if (subscribedSwitch.isChecked()) {
                            if (!(subscriptionFormat.equals(activeSubscription.FileFormatType)
                                    && activeSubscription.SubscriptionIntervalName
                                            .equals(subscriptionFrequencies.get(subscriptionInterval))
                                    && user.getUsername().equals(subscriptionEmail))) {
                                SubscriptionSubmitObject updatedSubscription = new SubscriptionSubmitObject(
                                        subscription.ApiName, subscriptionFormat, user.getUsername(),
                                        user.getUsername(), subscriptionFrequencies.get(subscriptionInterval));
                                Subscription newSubscriptionObject = api.updateSubscription(
                                        String.valueOf(activeSubscription.Id), updatedSubscription);

                                if (newSubscriptionObject != null) {
                                    ((CheckBox) v).setChecked(true);
                                }
                            }
                        } else {
                            Response response = api.deleteSubscription(String.valueOf(activeSubscription.Id));

                            if (response.getStatus() == 204) {
                                ((CheckBox) v).setChecked(false);
                                Toast.makeText(v.getContext(), R.string.subscription_update_successful,
                                        Toast.LENGTH_LONG).show();
                            } else {
                                Toast.makeText(v.getContext(), R.string.subscription_update_failed,
                                        Toast.LENGTH_LONG).show();
                            }
                        }
                    } else {
                        SubscriptionSubmitObject newSubscription = new SubscriptionSubmitObject(
                                subscription.ApiName, subscriptionFormat, user.getUsername(),
                                user.getUsername(), subscriptionFrequencies.get(subscriptionInterval));

                        Subscription response = api.setSubscription(newSubscription);

                        if (response != null) {
                            ((CheckBox) v).setChecked(true);
                            // TODO: add to "Mine abonnementer"
                            Toast.makeText(v.getContext(), R.string.subscription_update_successful,
                                    Toast.LENGTH_LONG).show();
                        } else {
                            Toast.makeText(v.getContext(), R.string.subscription_update_failed,
                                    Toast.LENGTH_LONG).show();
                        }
                    }

                    dialog.dismiss();
                }
            });

            cancelButton.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View cancelButton) {
                    ((CheckBox) v).setChecked(isSubscribed);

                    dialog.dismiss();
                }
            });

            dialog.show();

        }
    };
}

From source file:com.nadmm.airports.wx.MetarFragment.java

protected void showMetar(Intent intent) {
    if (getActivity() == null) {
        // Not ready to do this yet
        return;//  w  w  w  .j  a  v  a2  s .co  m
    }

    Metar metar = (Metar) intent.getSerializableExtra(NoaaService.RESULT);
    if (metar == null) {
        return;
    }

    View detail = findViewById(R.id.wx_detail_layout);
    LinearLayout layout = (LinearLayout) findViewById(R.id.wx_status_layout);
    layout.removeAllViews();
    TextView tv = (TextView) findViewById(R.id.status_msg);
    if (!metar.isValid) {
        tv.setVisibility(View.VISIBLE);
        layout.setVisibility(View.VISIBLE);
        tv.setText("Unable to get METAR for this location");
        addRow(layout, "This could be due to the following reasons:");
        addBulletedRow(layout, "Network connection is not available");
        addBulletedRow(layout, "ADDS does not publish METAR for this station");
        addBulletedRow(layout, "Station is currently out of service");
        addBulletedRow(layout, "Station has not updated the METAR for more than 3 hours");
        detail.setVisibility(View.GONE);
        stopRefreshAnimation();
        setFragmentContentShown(true);
        return;
    } else {
        tv.setText("");
        tv.setVisibility(View.GONE);
        layout.setVisibility(View.GONE);
        detail.setVisibility(View.VISIBLE);
    }

    tv = (TextView) findViewById(R.id.wx_station_info2);
    WxUtils.setFlightCategoryDrawable(tv, metar.flightCategory);

    tv = (TextView) findViewById(R.id.wx_age);
    tv.setText(TimeUtils.formatElapsedTime(metar.observationTime));

    // Raw Text
    tv = (TextView) findViewById(R.id.wx_raw_metar);
    tv.setText(metar.rawText);

    // Winds
    tv = (TextView) findViewById(R.id.wx_wind_label);
    layout = (LinearLayout) findViewById(R.id.wx_wind_layout);
    layout.removeAllViews();
    int visibility = View.GONE;
    if (metar.windSpeedKnots < Integer.MAX_VALUE) {
        showWindInfo(layout, metar);
        visibility = View.VISIBLE;
    }
    tv.setVisibility(visibility);
    layout.setVisibility(visibility);

    // Visibility
    tv = (TextView) findViewById(R.id.wx_vis_label);
    layout = (LinearLayout) findViewById(R.id.wx_vis_layout);
    layout.removeAllViews();
    visibility = View.GONE;
    if (metar.visibilitySM < Float.MAX_VALUE) {
        if (metar.flags.contains(Flags.AutoReport) && metar.visibilitySM == 10) {
            addRow(layout, "10+ statute miles horizontal");
        } else {
            NumberFormat decimal2 = NumberFormat.getNumberInstance();
            decimal2.setMaximumFractionDigits(2);
            decimal2.setMinimumFractionDigits(0);
            addRow(layout,
                    String.format("%s statute miles horizontal", FormatUtils.formatNumber(metar.visibilitySM)));
        }
        if (metar.vertVisibilityFeet < Integer.MAX_VALUE) {
            addRow(layout, String.format("%s vertical", FormatUtils.formatFeetAgl(metar.vertVisibilityFeet)));
        }
        visibility = View.VISIBLE;
    }
    tv.setVisibility(visibility);
    layout.setVisibility(visibility);

    // Weather
    layout = (LinearLayout) findViewById(R.id.wx_weather_layout);
    layout.removeAllViews();
    for (WxSymbol wx : metar.wxList) {
        addWeatherRow(layout, wx, metar.flightCategory);
    }

    // Sky Conditions
    tv = (TextView) findViewById(R.id.wx_sky_cond_label);
    layout = (LinearLayout) findViewById(R.id.wx_sky_cond_layout);
    layout.removeAllViews();
    visibility = View.GONE;
    if (!metar.skyConditions.isEmpty()) {
        for (SkyCondition sky : metar.skyConditions) {
            addSkyConditionRow(layout, sky, metar.flightCategory);
        }
        visibility = View.VISIBLE;
    }
    tv.setVisibility(visibility);
    layout.setVisibility(visibility);

    // Temperature
    tv = (TextView) findViewById(R.id.wx_temp_label);
    layout = (LinearLayout) findViewById(R.id.wx_temp_layout);
    layout.removeAllViews();
    visibility = View.GONE;
    if (metar.tempCelsius < Float.MAX_VALUE && metar.dewpointCelsius < Float.MAX_VALUE) {
        addRow(layout, "Temperature", FormatUtils.formatTemperature(metar.tempCelsius));
        if (metar.dewpointCelsius < Float.MAX_VALUE) {
            addRow(layout, "Dew point", FormatUtils.formatTemperature(metar.dewpointCelsius));
            addRow(layout, "Relative humidity", String.format("%.0f%%", WxUtils.getRelativeHumidity(metar)));

            long denAlt = WxUtils.getDensityAltitude(metar);
            if (denAlt > mElevation) {
                addRow(layout, "Density altitude", FormatUtils.formatFeet(denAlt));
            }
        } else {
            addRow(layout, "Dew point", "n/a");
        }

        if (metar.maxTemp6HrCentigrade < Float.MAX_VALUE) {
            addRow(layout, "6-hour maximum", FormatUtils.formatTemperature(metar.maxTemp6HrCentigrade));
        }
        if (metar.minTemp6HrCentigrade < Float.MAX_VALUE) {
            addRow(layout, "6-hour minimum", FormatUtils.formatTemperature(metar.minTemp6HrCentigrade));
        }
        if (metar.maxTemp24HrCentigrade < Float.MAX_VALUE) {
            addRow(layout, "24-hour maximum", FormatUtils.formatTemperature(metar.maxTemp24HrCentigrade));
        }
        if (metar.minTemp24HrCentigrade < Float.MAX_VALUE) {
            addRow(layout, "24-hour minimum", FormatUtils.formatTemperature(metar.minTemp24HrCentigrade));
        }
        visibility = View.VISIBLE;
    }
    tv.setVisibility(visibility);
    layout.setVisibility(visibility);

    // Pressure
    tv = (TextView) findViewById(R.id.wx_pressure_label);
    layout = (LinearLayout) findViewById(R.id.wx_pressure_layout);
    layout.removeAllViews();
    visibility = View.GONE;
    if (metar.altimeterHg < Float.MAX_VALUE) {
        addRow(layout, "Altimeter", FormatUtils.formatAltimeter(metar.altimeterHg));
        if (metar.seaLevelPressureMb < Float.MAX_VALUE) {
            addRow(layout, "Sea level pressure",
                    String.format("%s mb", FormatUtils.formatNumber(metar.seaLevelPressureMb)));
        }
        long presAlt = WxUtils.getPressureAltitude(metar);
        if (presAlt > mElevation) {
            addRow(layout, "Pressure altitude", FormatUtils.formatFeet(presAlt));
        }
        if (metar.pressureTend3HrMb < Float.MAX_VALUE) {
            addRow(layout, "3-hour tendency", String.format("%+.2f mb", metar.pressureTend3HrMb));
        }
        if (metar.presfr) {
            addRow(layout, "Pressure falling rapidly");
        }
        if (metar.presrr) {
            addRow(layout, "Pressure rising rapidly");
        }
        visibility = View.VISIBLE;
    }
    tv.setVisibility(visibility);
    layout.setVisibility(visibility);

    // Precipitation
    tv = (TextView) findViewById(R.id.wx_precip_label);
    layout = (LinearLayout) findViewById(R.id.wx_precip_layout);
    layout.removeAllViews();
    if (metar.precipInches < Float.MAX_VALUE) {
        addRow(layout, "1-hour precipitation", String.format("%.2f\"", metar.precipInches));
    }
    if (metar.precip3HrInches < Float.MAX_VALUE) {
        addRow(layout, "3-hour precipitation", String.format("%.2f\"", metar.precip3HrInches));
    }
    if (metar.precip6HrInches < Float.MAX_VALUE) {
        addRow(layout, "6-hour precipitation", String.format("%.2f\"", metar.precip6HrInches));
    }
    if (metar.precip24HrInches < Float.MAX_VALUE) {
        addRow(layout, "24-hour precipitation", String.format("%.2f\"", metar.precip24HrInches));
    }
    if (metar.snowInches < Float.MAX_VALUE) {
        addRow(layout, "Snow depth", String.format("%.0f\"", metar.snowInches));
    }
    if (metar.snincr) {
        addRow(layout, "Snow is increasing rapidly");
    }
    visibility = layout.getChildCount() > 0 ? View.VISIBLE : View.GONE;
    tv.setVisibility(visibility);
    layout.setVisibility(visibility);

    // Remarks
    tv = (TextView) findViewById(R.id.wx_remarks_label);
    layout = (LinearLayout) findViewById(R.id.wx_remarks_layout);
    layout.removeAllViews();
    for (Flags flag : metar.flags) {
        addBulletedRow(layout, flag.toString());
    }
    for (String remark : mRemarks) {
        addBulletedRow(layout, remark);
    }
    visibility = layout.getChildCount() > 0 ? View.VISIBLE : View.GONE;
    tv.setVisibility(visibility);
    layout.setVisibility(visibility);

    // Fetch time
    tv = (TextView) findViewById(R.id.wx_fetch_time);
    tv.setText("Fetched on " + TimeUtils.formatDateTime(getActivity(), metar.fetchTime));
    tv.setVisibility(View.VISIBLE);

    stopRefreshAnimation();
    setFragmentContentShown(true);
}

From source file:com.RSMSA.policeApp.Adapters.ViewPagerAccidentsDetailsAdapter.java

@Override
public Object instantiateItem(ViewGroup container, int position) {
    inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    android.widget.ScrollView itemView = (ScrollView) inflater.inflate(R.layout.accident_details, container,
            false);/* ww w.ja va  2 s . co m*/

    final AccidentVehicle accidentVehicle = new AccidentVehicle();
    Button addPasenger = (Button) itemView.findViewById(R.id.add_witness);
    Button next = (Button) itemView.findViewById(R.id.next);
    final LinearLayout linearLayout = (LinearLayout) itemView.findViewById(R.id.passengers_layout);

    if (position == tabnames.size() - 1) {
        next.setVisibility(View.VISIBLE);
    } else {
        next.setVisibility(View.GONE);
    }
    next.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            AccidentReportFormActivity.showWitneses();
        }
    });

    final EditText fatalEdit = (EditText) itemView.findViewById(R.id.fatal_edit);
    fatalEdit.setOnFocusChangeListener(new CustomeTimeWatcher(accidentVehicle, "setFatal"));

    final EditText simpleEdit = (EditText) itemView.findViewById(R.id.simple_edit);
    simpleEdit.setOnFocusChangeListener(new CustomeTimeWatcher(accidentVehicle, "setSimple"));

    EditText injuryEdit = (EditText) itemView.findViewById(R.id.injury_edit);
    injuryEdit.setOnFocusChangeListener(new CustomeTimeWatcher(accidentVehicle, "setSevere_injured"));

    EditText notInjuredEdit = (EditText) itemView.findViewById(R.id.not_injured_edit);
    notInjuredEdit.setOnFocusChangeListener(new CustomeTimeWatcher(accidentVehicle, "setOnly_damage"));

    EditText driverLicenceEdit = (EditText) itemView.findViewById(R.id.license_one);
    driverLicenceEdit.setOnFocusChangeListener(new CustomeTimeWatcher(accidentVehicle, "setLicence_no") {
        public void afterFocus(final String text, final EditText editText) {
            new AsyncTask<Void, Void, Boolean>() {
                @Override
                protected Boolean doInBackground(Void... params) {
                    DHIS2Modal dhis2Modal = new DHIS2Modal("Driver", null, MainOffence.username,
                            MainOffence.password);
                    JSONObject where = new JSONObject();
                    try {
                        where.put("value", text);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                    JSONObject driverObject = null;
                    try {
                        JSONArray driver = dhis2Modal.getEvent(where);
                        Log.d(TAG, "returned driver json = " + driver.toString());
                        driverObject = driver.getJSONObject(0);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                    try {
                        if (driverObject.getString("Driver License Number").equals(text)) {
                            accidentVehicle.setProgram_driver(driverObject.getString("id"));
                            return true;
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    } catch (NullPointerException e) {
                        Log.e(TAG, "returned json object is null");
                    }
                    return false;
                }

                @Override
                protected void onPostExecute(Boolean aVoid) {
                    super.onPostExecute(aVoid);
                    if (!aVoid) {
                        editText.setTextColor(context.getResources().getColor(R.color.red));
                    } else {
                        editText.setTextColor(context.getResources().getColor(R.color.green_500));
                    }
                }
            }.execute();

        }
    });

    final EditText alcoholEdit = (EditText) itemView.findViewById(R.id.alcohol_edit);
    alcoholEdit.setOnFocusChangeListener(new CustomeTimeWatcher(accidentVehicle, "setAlcohol_percentage"));

    CheckBox drug = (CheckBox) itemView.findViewById(R.id.drug_edit);
    drug.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            accidentVehicle.setDrug(isChecked);
        }
    });

    CheckBox phone = (CheckBox) itemView.findViewById(R.id.phone_edit);
    phone.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            accidentVehicle.setPhone_use(isChecked);
        }
    });

    EditText plateNumber = (EditText) itemView.findViewById(R.id.registration_number_one);
    plateNumber.setOnFocusChangeListener(new CustomeTimeWatcher(accidentVehicle, "setPlate_number") {
        public void afterFocus(final String text, final EditText editText) {
            new AsyncTask<Void, Void, Boolean>() {
                @Override
                protected Boolean doInBackground(Void... params) {
                    DHIS2Modal dhis2Modal = new DHIS2Modal("Vehicle", null, MainOffence.username,
                            MainOffence.password);
                    JSONObject where = new JSONObject();
                    try {
                        where.put("value", text);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                    JSONObject vehicleObject = null;
                    try {
                        JSONArray vehiclesArray = dhis2Modal.getEvent(where);
                        Log.d(TAG, "returned vehicle json = " + vehiclesArray.toString());
                        vehicleObject = vehiclesArray.getJSONObject(0);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    } catch (NullPointerException e) {
                        e.printStackTrace();
                    }

                    try {
                        if (vehicleObject.getString("Vehicle Plate Number").equals(text)) {
                            accidentVehicle.setProgram_vehicle(vehicleObject.getString("id"));
                            return true;
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    } catch (NullPointerException e) {
                        Log.e(TAG, "returned json object is null");
                    }
                    return false;
                }

                @Override
                protected void onPostExecute(Boolean aVoid) {
                    super.onPostExecute(aVoid);
                    if (!aVoid) {
                        editText.setTextColor(context.getResources().getColor(R.color.red));
                    } else {
                        editText.setTextColor(context.getResources().getColor(R.color.light_gray));
                    }
                }
            }.execute();

        }
    });

    EditText repairCost = (EditText) itemView.findViewById(R.id.repair_amount_one);
    repairCost.setOnFocusChangeListener(new CustomeTimeWatcher(accidentVehicle, "setEstimated_repair"));

    EditText vehicleEdit = (EditText) itemView.findViewById(R.id.vehicle_title_edit);
    vehicleEdit.setOnFocusChangeListener(new CustomeTimeWatcher(accidentVehicle, "setVehicle"));

    EditText vehicleTotalEdit = (EditText) itemView.findViewById(R.id.vehicle_total_edit);
    vehicleTotalEdit.setOnFocusChangeListener(new CustomeTimeWatcher(accidentVehicle, "setVehicle_total"));

    EditText infastructureEdit = (EditText) itemView.findViewById(R.id.infrastructure_edit);
    infastructureEdit.setOnFocusChangeListener(new CustomeTimeWatcher(accidentVehicle, "setInfastructure"));

    EditText costEdit = (EditText) itemView.findViewById(R.id.rescue_cost_edit);
    costEdit.setOnFocusChangeListener(new CustomeTimeWatcher(accidentVehicle, "setCost"));

    final List<PassengerVehicle> passengers = new ArrayList<PassengerVehicle>();

    addPasenger.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            final PassengerVehicle passengerVehicle = new PassengerVehicle();
            LinearLayout passenger = (LinearLayout) inflater.inflate(R.layout.passenger, null);

            linearLayout.addView(passenger);

            EditText nameEdit = (EditText) passenger.findViewById(R.id.name_edit);
            nameEdit.setOnFocusChangeListener(new CustomeTimeWatcher(passengerVehicle, "setName"));

            final EditText dateOfBirth = (EditText) passenger.findViewById(R.id.dob_one);
            dateOfBirth.setOnFocusChangeListener(new CustomeTimeWatcher(passengerVehicle, "setDate_of_birth"));

            EditText physicalAddressEdit = (EditText) passenger.findViewById(R.id.physical_address_one);
            physicalAddressEdit
                    .setOnFocusChangeListener(new CustomeTimeWatcher(passengerVehicle, "setPhysical_address"));

            EditText addressBoxEdit = (EditText) passenger.findViewById(R.id.address_box_one);
            addressBoxEdit.setOnFocusChangeListener(new CustomeTimeWatcher(passengerVehicle, "setAddress"));

            EditText nationalIDEdit = (EditText) passenger.findViewById(R.id.national_id_one);
            nationalIDEdit.setOnFocusChangeListener(new CustomeTimeWatcher(passengerVehicle, "setNational_id"));

            EditText phoneNoEdit = (EditText) passenger.findViewById(R.id.phone_no_one);
            phoneNoEdit.setOnFocusChangeListener(new CustomeTimeWatcher(passengerVehicle, "setPhone_no"));

            EditText alcoholPercentageEdit = (EditText) passenger.findViewById(R.id.alcohol_percentage);
            alcoholPercentageEdit
                    .setOnFocusChangeListener(new CustomeTimeWatcher(passengerVehicle, "setAlcohol_percent"));

            CheckBox seatbeltCheckbox = (CheckBox) passenger.findViewById(R.id.seat_belt_check);
            seatbeltCheckbox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                    passengerVehicle.setHelmet(isChecked);
                }
            });

            Button date_picker = (Button) passenger.findViewById(R.id.date_picker);
            date_picker.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    DatePickerDialog newDatePickerDialogueFragment;
                    newDatePickerDialogueFragment = new DatePickerDialog();
                    newDatePickerDialogueFragment.show(AccidentReportFormActivity.fragmentManager,
                            "DatePickerDialogue");
                    newDatePickerDialogueFragment
                            .setOnDateSetListener(new DatePickerDialog.OnDateSetListener() {
                                @Override
                                public void onDateSet(DatePickerDialog dialog, int year, int monthOfYear,
                                        int dayOfMonth) {
                                    dateOfBirth.setText(dayOfMonth + " / " + (monthOfYear + 1) + " / " + year);
                                }
                            });
                }
            });

            final RadioButton male = (RadioButton) passenger.findViewById(R.id.male);
            male.setTypeface(MainOffence.Roboto_Regular);

            final RadioButton female = (RadioButton) passenger.findViewById(R.id.female);
            female.setTypeface(MainOffence.Roboto_Regular);

            passengerVehicle.setGender("Male");
            male.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                    if (isChecked)
                        passengerVehicle.setGender("Male");
                }
            });

            female.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                    if (isChecked)
                        passengerVehicle.setGender("Female");
                }
            });

            passengers.add(linearLayout.getChildCount() - 1, passengerVehicle);

        }
    });

    accident[position] = accidentVehicle;
    passanger.add(position, passengers);

    ((ViewPager) container).addView(itemView);
    return itemView;
}

From source file:fiskinfoo.no.sintef.fiskinfoo.MyToolsFragment.java

private void updateToolList(Set<Map.Entry<String, ArrayList<ToolEntry>>> tools,
        final LinearLayout toolContainer) {
    if (fiskInfoUtility.isNetworkAvailable(getActivity())) {
        List<ToolEntry> localTools = new ArrayList<>();
        final List<ToolEntry> unconfirmedRemovedTools = new ArrayList<>();
        final List<ToolEntry> synchedTools = new ArrayList<>();

        for (final Map.Entry<String, ArrayList<ToolEntry>> dateEntry : tools) {
            for (final ToolEntry toolEntry : dateEntry.getValue()) {
                if (toolEntry.getToolStatus() == ToolEntryStatus.STATUS_REMOVED) {
                    continue;
                } else if (toolEntry.getToolStatus() == ToolEntryStatus.STATUS_RECEIVED) {
                    synchedTools.add(toolEntry);
                } else if (!(toolEntry.getToolStatus() == ToolEntryStatus.STATUS_REMOVED_UNCONFIRMED)) {
                    localTools.add(toolEntry);
                } else {
                    unconfirmedRemovedTools.add(toolEntry);
                }/*from w w w. j  ava2s. c o  m*/
            }
        }

        barentswatchApi.setAccesToken(user.getToken());

        Response response = barentswatchApi.getApi().geoDataDownload("fishingfacility", "JSON");

        if (response == null) {
            Log.d(TAG, "RESPONSE == NULL");
        }

        byte[] toolData;
        try {
            toolData = FiskInfoUtility.toByteArray(response.getBody().in());
            JSONObject featureCollection = new JSONObject(new String(toolData));
            JSONArray jsonTools = featureCollection.getJSONArray("features");
            JSONArray matchedTools = new JSONArray();
            UserSettings settings = user.getSettings();

            for (int i = 0; i < jsonTools.length(); i++) {
                JSONObject tool = jsonTools.getJSONObject(i);
                boolean hasCopy = false;

                for (int j = 0; j < localTools.size(); j++) {
                    if (localTools.get(j).getToolId()
                            .equals(tool.getJSONObject("properties").getString("toolid"))) {
                        SimpleDateFormat sdfMilliSeconds = new SimpleDateFormat(
                                getString(R.string.datetime_format_yyyy_mm_dd_t_hh_mm_ss_sss),
                                Locale.getDefault());
                        SimpleDateFormat sdfMilliSecondsRemote = new SimpleDateFormat(
                                getString(R.string.datetime_format_yyyy_mm_dd_t_hh_mm_ss_sss),
                                Locale.getDefault());
                        SimpleDateFormat sdfRemote = new SimpleDateFormat(
                                getString(R.string.datetime_format_yyyy_mm_dd_t_hh_mm_ss), Locale.getDefault());

                        sdfMilliSeconds.setTimeZone(TimeZone.getTimeZone("UTC"));
                        /* Timestamps from BW seem to be one hour earlier than UTC/GMT?  */
                        sdfMilliSecondsRemote.setTimeZone(TimeZone.getTimeZone("GMT-1"));
                        sdfRemote.setTimeZone(TimeZone.getTimeZone("GMT-1"));
                        Date localLastUpdatedDateTime;
                        Date localUpdatedBySourceDateTime;
                        Date serverUpdatedDateTime;
                        Date serverUpdatedBySourceDateTime = null;
                        try {
                            localLastUpdatedDateTime = sdfMilliSeconds
                                    .parse(localTools.get(j).getLastChangedDateTime());
                            localUpdatedBySourceDateTime = sdfMilliSeconds
                                    .parse(localTools.get(j).getLastChangedBySource());

                            serverUpdatedDateTime = tool.getJSONObject("properties")
                                    .getString("lastchangeddatetime").length() == getResources()
                                            .getInteger(R.integer.datetime_without_milliseconds_length)
                                                    ? sdfRemote.parse(tool.getJSONObject("properties")
                                                            .getString("lastchangeddatetime"))
                                                    : sdfMilliSecondsRemote
                                                            .parse(tool.getJSONObject("properties")
                                                                    .getString("lastchangeddatetime"));

                            if (tool.getJSONObject("properties").has("lastchangedbysource")) {
                                serverUpdatedBySourceDateTime = tool.getJSONObject("properties")
                                        .getString("lastchangedbysource").length() == getResources()
                                                .getInteger(R.integer.datetime_without_milliseconds_length)
                                                        ? sdfRemote.parse(tool.getJSONObject("properties")
                                                                .getString("lastchangedbysource"))
                                                        : sdfMilliSecondsRemote
                                                                .parse(tool.getJSONObject("properties")
                                                                        .getString("lastchangedbysource"));
                            }

                            if ((localLastUpdatedDateTime.equals(serverUpdatedDateTime)
                                    || localLastUpdatedDateTime.before(serverUpdatedDateTime))
                                    && serverUpdatedBySourceDateTime != null
                                    && (localUpdatedBySourceDateTime.equals(serverUpdatedBySourceDateTime)
                                            || localUpdatedBySourceDateTime
                                                    .before(serverUpdatedBySourceDateTime))) {
                                localTools.get(j).updateFromGeoJson(tool, getActivity());

                                localTools.get(j).setToolStatus(ToolEntryStatus.STATUS_RECEIVED);
                            } else if (serverUpdatedBySourceDateTime != null
                                    && localUpdatedBySourceDateTime.after(serverUpdatedBySourceDateTime)) {
                                // TODO: Do nothing, local changes should be reported.

                            } else {
                                // TODO: what gives?
                            }

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

                        localTools.remove(j);
                        j--;

                        hasCopy = true;
                        break;
                    }
                }

                for (int j = 0; j < unconfirmedRemovedTools.size(); j++) {
                    if (unconfirmedRemovedTools.get(j).getToolId()
                            .equals(tool.getJSONObject("properties").getString("toolid"))) {
                        hasCopy = true;
                        unconfirmedRemovedTools.remove(j);
                        j--;
                    }
                }

                for (int j = 0; j < synchedTools.size(); j++) {
                    if (synchedTools.get(j).getToolId()
                            .equals(tool.getJSONObject("properties").getString("toolid"))) {
                        hasCopy = true;
                        synchedTools.remove(j);
                        j--;
                    }
                }

                if (!hasCopy && settings != null) {
                    if ((!settings.getVesselName().isEmpty()
                            && (FiskInfoUtility.ReplaceRegionalCharacters(settings.getVesselName())
                                    .equalsIgnoreCase(tool.getJSONObject("properties").getString("vesselname"))
                                    || settings.getVesselName().equalsIgnoreCase(
                                            tool.getJSONObject("properties").getString("vesselname"))))
                            && ((!settings.getIrcs().isEmpty() && settings.getIrcs().toUpperCase()
                                    .equals(tool.getJSONObject("properties").getString("ircs")))
                                    || (!settings.getMmsi().isEmpty() && settings.getMmsi()
                                            .equals(tool.getJSONObject("properties").getString("mmsi")))
                                    || (!settings.getImo().isEmpty() && settings.getImo()
                                            .equals(tool.getJSONObject("properties").getString("imo"))))) {
                        matchedTools.put(tool);
                    }
                }
            }

            if (matchedTools.length() > 0) {
                final Dialog dialog = dialogInterface.getDialog(getActivity(),
                        R.layout.dialog_confirm_tools_from_api, R.string.tool_confirmation);
                Button cancelButton = (Button) dialog.findViewById(R.id.dialog_bottom_cancel_button);
                Button addToolsButton = (Button) dialog.findViewById(R.id.dialog_bottom_add_button);
                final LinearLayout linearLayoutToolContainer = (LinearLayout) dialog
                        .findViewById(R.id.dialog_confirm_tool_main_container_linear_layout);
                final List<ToolConfirmationRow> matchedToolsList = new ArrayList<>();

                for (int i = 0; i < matchedTools.length(); i++) {
                    ToolConfirmationRow confirmationRow = new ToolConfirmationRow(getActivity(),
                            matchedTools.getJSONObject(i));
                    linearLayoutToolContainer.addView(confirmationRow.getView());
                    matchedToolsList.add(confirmationRow);
                }

                addToolsButton.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        for (ToolConfirmationRow row : matchedToolsList) {
                            if (row.isChecked()) {
                                ToolEntry newTool = row.getToolEntry();
                                user.getToolLog().addTool(newTool, newTool.getSetupDateTime().substring(0, 10));
                                ToolLogRow newRow = new ToolLogRow(v.getContext(), newTool,
                                        utilityOnClickListeners.getToolEntryEditDialogOnClickListener(
                                                getActivity(), getFragmentManager(), mGpsLocationTracker,
                                                newTool, user));
                                row.getView().setTag(newTool.getToolId());
                                toolContainer.addView(newRow.getView());
                            }
                        }

                        user.writeToSharedPref(v.getContext());
                        dialog.dismiss();
                    }
                });

                cancelButton.setOnClickListener(utilityOnClickListeners.getDismissDialogListener(dialog));
                dialog.show();
            }

            if (unconfirmedRemovedTools.size() > 0) {
                final Dialog dialog = dialogInterface.getDialog(getActivity(),
                        R.layout.dialog_confirm_tools_from_api, R.string.tool_confirmation);
                TextView infoTextView = (TextView) dialog.findViewById(R.id.dialog_description_text_view);
                Button cancelButton = (Button) dialog.findViewById(R.id.dialog_bottom_cancel_button);
                Button archiveToolsButton = (Button) dialog.findViewById(R.id.dialog_bottom_add_button);
                final LinearLayout linearLayoutToolContainer = (LinearLayout) dialog
                        .findViewById(R.id.dialog_confirm_tool_main_container_linear_layout);

                infoTextView.setText(R.string.removed_tools_information_text);
                archiveToolsButton.setText(R.string.ok);
                cancelButton.setVisibility(View.GONE);

                for (ToolEntry removedEntry : unconfirmedRemovedTools) {
                    ToolLogRow removedToolRow = new ToolLogRow(getActivity(), removedEntry, null);
                    removedToolRow.setToolNotificationImageViewVisibility(false);
                    removedToolRow.setEditToolImageViewVisibility(false);
                    linearLayoutToolContainer.addView(removedToolRow.getView());
                }

                archiveToolsButton.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        for (ToolEntry removedEntry : unconfirmedRemovedTools) {
                            removedEntry.setToolStatus(ToolEntryStatus.STATUS_REMOVED);

                            for (int i = 0; i < toolContainer.getChildCount(); i++) {
                                if (removedEntry.getToolId()
                                        .equals(toolContainer.getChildAt(i).getTag().toString())) {
                                    toolContainer.removeViewAt(i);
                                    break;
                                }
                            }
                        }

                        user.writeToSharedPref(v.getContext());
                        dialog.dismiss();
                    }
                });

                dialog.show();
            }

            if (synchedTools.size() > 0) {
                final Dialog dialog = dialogInterface.getDialog(getActivity(),
                        R.layout.dialog_confirm_tools_from_api, R.string.tool_confirmation);
                TextView infoTextView = (TextView) dialog.findViewById(R.id.dialog_description_text_view);
                Button cancelButton = (Button) dialog.findViewById(R.id.dialog_bottom_cancel_button);
                Button archiveToolsButton = (Button) dialog.findViewById(R.id.dialog_bottom_add_button);
                final LinearLayout linearLayoutToolContainer = (LinearLayout) dialog
                        .findViewById(R.id.dialog_confirm_tool_main_container_linear_layout);

                infoTextView.setText(R.string.unexpected_tool_removal_info_text);
                archiveToolsButton.setText(R.string.archive);

                for (ToolEntry removedEntry : synchedTools) {
                    ToolLogRow removedToolRow = new ToolLogRow(getActivity(), removedEntry, null);
                    removedToolRow.setToolNotificationImageViewVisibility(false);
                    removedToolRow.setEditToolImageViewVisibility(false);
                    linearLayoutToolContainer.addView(removedToolRow.getView());
                }

                archiveToolsButton.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        for (ToolEntry removedEntry : synchedTools) {
                            removedEntry.setToolStatus(ToolEntryStatus.STATUS_REMOVED);

                            for (int i = 0; i < toolContainer.getChildCount(); i++) {
                                if (removedEntry.getToolId()
                                        .equals(toolContainer.getChildAt(i).getTag().toString())) {
                                    toolContainer.removeViewAt(i);
                                    break;
                                }
                            }
                        }

                        user.writeToSharedPref(v.getContext());
                        dialog.dismiss();
                    }
                });

                cancelButton.setOnClickListener(utilityOnClickListeners.getDismissDialogListener(dialog));
                dialog.show();
            }

            if (unconfirmedRemovedTools.size() > 0) {
                // TODO: If not found server side, tool is assumed to be removed. Inform user.

                final Dialog dialog = dialogInterface.getDialog(getActivity(),
                        R.layout.dialog_confirm_tools_from_api, R.string.reported_tools_removed_title);
                TextView informationTextView = (TextView) dialog
                        .findViewById(R.id.dialog_description_text_view);
                Button cancelButton = (Button) dialog.findViewById(R.id.dialog_bottom_cancel_button);
                Button archiveToolsButton = (Button) dialog.findViewById(R.id.dialog_bottom_add_button);
                final LinearLayout linearLayoutToolContainer = (LinearLayout) dialog
                        .findViewById(R.id.dialog_confirm_tool_main_container_linear_layout);

                informationTextView.setText(getString(R.string.removed_tools_information_text));
                cancelButton.setVisibility(View.GONE);
                archiveToolsButton.setText(getString(R.string.ok));

                for (ToolEntry toolEntry : unconfirmedRemovedTools) {
                    ToolConfirmationRow confirmationRow = new ToolConfirmationRow(getActivity(), toolEntry);
                    linearLayoutToolContainer.addView(confirmationRow.getView());
                }

                archiveToolsButton.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        for (ToolEntry toolEntry : unconfirmedRemovedTools) {
                            toolEntry.setToolStatus(ToolEntryStatus.STATUS_REMOVED);
                        }

                        user.writeToSharedPref(v.getContext());
                        dialog.dismiss();
                    }
                });

                dialog.show();
            }

            if (synchedTools.size() > 0) {
                //                    // TODO: Prompt user: Tool was confirmed, now is no longer at BW, remove or archive?

                final Dialog dialog = dialogInterface.getDialog(getActivity(),
                        R.layout.dialog_confirm_tools_from_api, R.string.tool_confirmation);
                TextView informationTextView = (TextView) dialog
                        .findViewById(R.id.dialog_description_text_view);
                Button cancelButton = (Button) dialog.findViewById(R.id.dialog_bottom_cancel_button);
                Button archiveToolsButton = (Button) dialog.findViewById(R.id.dialog_bottom_add_button);
                final LinearLayout linearLayoutToolContainer = (LinearLayout) dialog
                        .findViewById(R.id.dialog_confirm_tool_main_container_linear_layout);

                informationTextView.setText(getString(R.string.unexpected_tool_removal_info_text));
                archiveToolsButton.setText(getString(R.string.ok));

                for (ToolEntry toolEntry : synchedTools) {
                    ToolConfirmationRow confirmationRow = new ToolConfirmationRow(getActivity(), toolEntry);
                    linearLayoutToolContainer.addView(confirmationRow.getView());
                }

                archiveToolsButton.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        for (ToolEntry toolEntry : synchedTools) {
                            toolEntry.setToolStatus(ToolEntryStatus.STATUS_REMOVED);
                        }

                        user.writeToSharedPref(v.getContext());
                        dialog.dismiss();
                    }
                });

                cancelButton.setOnClickListener(utilityOnClickListeners.getDismissDialogListener(dialog));

                dialog.show();
            }

            user.writeToSharedPref(getActivity());
        } catch (IOException e) {
            e.printStackTrace();
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
}