我正在尝试使其能够检查字符串是否在json中。我这样做的方法是将json的值放入数组中,然后查看它是否包含该值。问题是它一一检查。这导致它说用户不在工作,而是在工作。然后在下一个循环中,它表示它们正在工作。

 private void CheckIfAlreadyWorking(String result) throws JSONException {
    //removed code to condense
    //result is a json of the days that the user is already working
    if (datematcher.find()) {
        String date = datematcher.group(1); //Date of the shift the user is already working
        JSONArray jsonArray = new JSONArray(result);
        String[] yourshifts = new String[jsonArray.length()];
        boolean end = false;
        for (int i = 0; i < jsonArray.length(); i++) {
                JSONObject obj = jsonArray.getJSONObject(i);
                yourshifts[i] = obj.getString("date");
            if (yourshifts[i].contains(date)) {
                //Already working that day
                Toast.makeText(getApplicationContext(), "Error: You are already working this day", Toast.LENGTH_SHORT).show();
            } else if(end == false){
                AddShift();
                end = true;
            }
        }

    }
    else {
        //Error
    }
}

最佳答案

尝试这样:
取一个boolean isfound = false;

for (int i = 0; i < jsonArray.length(); i++) {
                JSONObject obj = jsonArray.getJSONObject(i);
                yourshifts[i] = obj.getString("date");
            if (yourshifts[i].contains(date)) {
                isfound = true;
                break;

            }
        }


现在不在循环中:

if(isFound ==true)
{
    Toast.makeText(getApplicationContext(), "Error: You are already working this day", Toast.LENGTH_SHORT).show();
}
else
{
   AddShift();
}

10-01 22:42
查看更多