Android / Java:循环中的异步作业

时间:2016-10-03 04:45:06

标签: java android multithreading asynchronous

我有一个方法可以在我的Android应用程序中异步更新帐户列表。

方法看起来像这样

<?php
ob_start();
    //RJ Application Form
    //Connect Database
    include('admin/connect.php');
    //Set Variable
    $name = $sex = $zone = $email = $mobile = $education = $why_to_be_rj = $file_name = "";
    //Set Error array
    $errors = array();

    if (isset($_POST['submit']) && $_SERVER["REQUEST_METHOD"] == "POST") {

        //Function to process data
        function test_input($data) {
            $data = trim($data);
            $data = stripslashes($data);
            $data = htmlspecialchars($data);
            return $data;
        }

        //Check Name
        if (empty($_POST["name"])) {
            $errors['nameErr'] = 'Enter your name';
        } else {
            $name = test_input($_POST['name']);
            // check if name only contains letters and whitespace
            if (!preg_match("/^[a-zA-Z ]*$/", $name)) {
                $errors['nameErr'] = 'Only letters and white space allowed';
            }
        }


        //Check Sex
        if ($_POST['sex'] == '1') {
            $errors['sexErr'] = 'Select your sex';
        } else {
            $sex = $_POST['sex'];
        }


        //Check Audition Zone
        if (empty($_POST["zone"])) {
            $errors['$zoneErr'] = 'Enter your zone';
        } else {
            $zone = $_POST['zone'];
        }


        //Check Email
        if (empty($_POST["email"])) {
            $errors['emailErr'] = 'Enter your email';
        } else {
            $email = test_input($_POST['email']);
            // check if e-mail address is well-formed
            if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
                $errors['emailErr'] = 'Invalid email format';
            }
        }


        //Check Mobile
        if (empty($_POST["mobile"])) {
            $errors['mobileErr'] = 'Enter your mobile';
        } else {
            $mobile = test_input($_POST['mobile']);
            if (!preg_match("/^[\+0-9\-\(\)\s]*$/", $mobile)) {
                $errors['mobileErr'] = 'Only numbers are allowed';
            }
        }


        //Check Education
        if ($_POST["education"] == '1') {
            $errors['educationErr'] = 'Select your education';
        } else {
            $education = $_POST['education'];
        }


        //Check Description
        if (empty($_POST["about"])) {
            //$why_to_be_rjErr = 'Enter why you want to be a RJ';
            $errors['why_to_be_rjErr'] = 'Enter why you want to be a RJ';
        } else {
            $why_to_be_rj = test_input($_POST['about']);
        }


        //File Upload
            if(!empty($_FILES['fileToUpload']['name']) && !empty($_FILES['fileToUpload']['tmp_name'])){
                $uploadErr = array();
                $target_dir = "uploads/";
                //rename file before upload
                $file_name = $name.$mobile.$_FILES["fileToUpload"]["name"];
                $target_file = $target_dir . $name. $mobile. basename($_FILES["fileToUpload"]["name"]);
                $uploadOk = 1;
                $audioFileType = pathinfo($target_file,PATHINFO_EXTENSION);
                // Allow certain file formats
                if($audioFileType != "AMR" && 
                   $audioFileType != "amr" && 
                   $audioFileType != "MP3" && 
                   $audioFileType != "mp3" && 
                   $audioFileType != "WAV" && 
                   $audioFileType != "wav" && 
                   $audioFileType != "AAC" && 
                   $audioFileType != "aac" ) {
                    //echo "Sorry, only AMR, MP3, WAV & AAC files are allowed.";
                    $uploadErr['fileErr'] = "Sorry, only AMR, MP3, WAV & AAC files are allowed.";
                    $uploadOk = 0;
                }else{
                    // Check file size
                    if ($_FILES["fileToUpload"]["size"] > 100000000) {
                        echo "Sorry, your file is too large.";
                        $uploadErr['fileErr'] = "Sorry, your file is too large.";
                        $uploadOk = 0;
                    }else if(!$errors){
                            if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
                            echo "The file ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded.";
                            $file_upload_success = "The file ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded.";
                        } else {
                            echo "Sorry, there was an error uploading your file.";
                            $uploadErr['fileErr'] = "Sorry, there was an error uploading your file.";
                        }
                    }
                }
            }

//            // Check if image file is a actual image or fake image
//            $check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
//            if($check !== false) {
//                echo "File is an image - " . $check["mime"] . ".";
//                $uploadErr['fileErr'] = "File is an image - " . $check["mime"] . ".";
//                $uploadOk = 1;
//            } else {
//                echo "File is not an image.";
//                $uploadErr['fileErr'] = "File is not an image.";
//                $uploadOk = 0;
//            }

//            // Check if file already exists
//            if (file_exists($target_file)) {
//                echo "Sorry, file already exists.";
//                $uploadErr['fileErr'] = "Sorry, file already exists.";
//                $uploadOk = 0;
//            }


//            // Check if $uploadOk is set to 0 by an error
//            if ($uploadOk == 0) {
//                echo "Sorry, your file was not uploaded.";
//                $uploadErr['fileErr'] = "Sorry, your file was not uploaded.";
//            // if everything is ok, try to upload file
//            } else {
//                if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
//                    echo "The file ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded.";
//                    $file_upload_success = "The file ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded.";
//                } else {
//                    echo "Sorry, there was an error uploading your file.";
//                    $uploadErr['fileErr'] = "Sorry, there was an error uploading your file.";
//                }
//            }




        if(!$errors){//Check if there is any errors. if no errors, then the data will be inserted into the database
            //SQL to input data into rj-hunt table
            $sql = "INSERT INTO `rj_hunt`(`name`, `sex`, `audition_zone`, `email`, `mobile`, `education`, `why_to_be_rj`, `voice`) 
                            VALUES ('$name','$sex','$zone','$email','$mobile','$education','$why_to_be_rj','$file_name')";

            //mysqli query. $conn is included at the begining of the script.
            mysqli_query($conn, $sql);
            //After iserting data successfully, redirect to a sub page to show success message.
            header("location: rj-hunt.php?submit=success");
        }//if no error, process done.
    }//if clicked in submit button and method is post.
?>

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <meta name="keywords" content="WebRTC getUserMedia MediaRecorder API">
        <link rel="icon" href="img/ico.png">
        <title>RJ HUNT</title>
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">  
        <style>
            body { margin:0; padding:0; background: url(img/back.jpg); background-size:cover; position:relative; min-height:100vh; width:100%;}
            .hunt-form{
                margin-top: 20px;
            }
            .form-top{
                background: #740808;
                width: 31%;
                margin: auto;
                border-radius: 5px;
            }
            .form-top h2{
                color: #ffc905;
                padding: 10px 0;
                font-family: Verdana;
            }
            form{
                background: #740808;
                padding: 20px 0 10px 10px;
                border-radius: 10px;
                border: 10px solid #97614B;
                width: 80%;
                margin: auto;
            }
            label{
                color: #ffc905;
            }
            .error{
                color: red;
            }
            .after-submit-message{
                width: 50%;
                margin: auto;
            }
            .after-submit-message h3{
                background: yellowgreen;
                color: #fff;
                padding: 5px;
            }
            .btn-warning{
                background: #EC971F;
            }
             button{
        margin: 10px 5px;
      }
      li{
        margin: 10px;
      }
      body{
        width: 90%;
        max-width: 960px;
        margin: 0px auto;
      }
      #btns{
        display: none;
      }
      h1{
        margin: 100px;
      }
        </style>
    </head>
    <body>
        <div class="container">
            <div class="row">
                <div class="col-md-10 col-md-offset-1">
                    <div class="hunt-form">
                        <div class="form-top">
                            <h2 class="text-center"></h2>  
                        </div>
                        <div class="after-submit-message">
                            <?php if(isset($_GET['submit']) && $_GET['submit']=='success'){echo '<h3 class="text-center">Your information submitted successfully</h3>';}?>
                        </div>
                        <form class="form-horizontal" method="post" action="" enctype="multipart/form-data">
                            <div class="form-group">
                                <label class="col-sm-4 control-label" for="name">Name:</label>
                                <div class="col-sm-6">
                                    <input class="form-control" value="<?php echo $name; ?>" type="text" name="name" id="name" placeholder="Name">
                                    <span class="error"><?php if(isset($errors['nameErr'])){echo $errors['nameErr'];} ?></span>
                                </div>
                            </div>
                            <div class="form-group">
                                <label class="col-sm-4 control-label" for="sex">Sex:</label>
                                <div class="col-sm-3">
                                    <select class="form-control" name="sex" id="sex">
                                        <option value="1">-- Select --</option>
                                        <option value="Male" <?php if($sex == 'Male'){echo 'selected';}?>>Male</option>
                                        <option value="Female" <?php if($sex == 'Female'){echo 'selected';}?>>Female</option>
                                    </select>
                                    <span class="error"><?php if(isset($errors['sexErr'])){echo $errors['sexErr'];} ?></span>
                                </div>
                            </div>
                            <div class="form-group">
                                <label class="col-sm-4 control-label" for="zone">Audition Zone:</label>
                                <div class="col-sm-3">
                                    <select class="form-control" name="zone" id="zone">
                                        <option value="Dhaka">Dhaka</option>
                                    </select>
                                    <span class="error"><?php if(isset($errors['zoneErr'])){echo $errors['zoneErr'];} ?></span>
                                </div>
                            </div>
                            <div class="form-group">
                                <label class="col-sm-4 control-label" for="email">Email:</label>
                                <div class="col-sm-6">
                                    <input class="form-control" value="<?php echo $email; ?>" type="email" name="email" id="email" placeholder="Email">
                                    <span class="error"><?php if(isset($errors['emailErr'])) {echo $errors['emailErr'];} ?></span>
                                </div>
                            </div>
                            <div class="form-group">
                                <label class="col-sm-4 control-label" for="mobile">Mobile:</label>
                                <div class="col-sm-6">
                                    <input class="form-control" value="<?php echo $mobile; ?>" type="tel" name="mobile" id="mobile" placeholder="Mobile">
                                    <span class="error"><?php if(isset($errors['mobileErr'])) {echo $errors['mobileErr'];} ?></span>
                                </div>
                            </div>
                            <div class="form-group">
                                <label class="col-sm-4 control-label" for="education">Education Level:</label>
                                <div class="col-sm-3">
                                    <select class="form-control" name="education" id="education">
                                        <option value="1">-- Select --</option>
                                        <option value="Hsc" <?php if($education == 'Hsc'){echo 'selected';}?>>HSC</option>
                                        <option value="Undergraduate" <?php if($education == 'Undergraduate'){echo 'selected';}?>>Undergraduate</option>
                                        <option value="Ggraduate" <?php if($education == 'Ggraduate'){echo 'selected';}?>>Graduate</option>
                                    </select>
                                    <span class="error"><?php if(isset($errors['educationErr'])) {echo $errors['educationErr'];} ?></span>
                                </div>
                            </div>
                            <div class="form-group">
                                <label class="col-sm-4 control-label" for="about">Why you want to be a RJ:<br/>(300 words)</label>
                                <div class="col-sm-6">
                                    <textarea class="form-control" name="about" id="about" rows="4" placeholder="Why you want to be a RJ? (300 words)"><?php echo $why_to_be_rj; ?></textarea>
                                    <span class="error"><?php if(isset($errors['why_to_be_rjErr'])) {echo $errors['why_to_be_rjErr'];} ?></span>
                                </div>
                            </div>
                            <div class="form-group">
                                <label class="col-sm-4 control-label" for="fileToUpload">Add Voice</label>
                                <div class="col-sm-4">
                                    <input class="form-control" value="<?php echo $file_name;?>" type="file" name="fileToUpload" id="fileToUpload">
                                    <span class="error"><?php if(isset($uploadErr['fileErr'])) {echo $uploadErr['fileErr'];} ?></span>
                                </div>
                            </div>
                            <div form-group>
                                <label class="col-sm-4 control-label" id='mediaAudio'>Record Voice</label>
                                <div class="col-sm-4">
                                    <div id='gUMArea'>
                                        <input class="btn btn-default"  id='gUMbtn' value="Use Microphone">
                                    </div>
                                    <div id='btns'>
                                        <button  class="btn btn-default" id='start'>Start</button>
                                        <button  class="btn btn-default" id='stop'>Stop</button>
                                    </div>
                                    <div>
                                        <ul  class="list-unstyled" id='ul'></ul>
                                    </div>
                                </div>
                            </div>
                            <div class="form-group">
                                <div class="col-sm-8 col-sm-offset-4">
                                    <input class="btn btn-warning btn-lg" type="submit" name="submit" id="submit" value="Submit">
                                </div>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        </div>
        <!--<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>-->
        <script src="https://code.jquery.com/jquery-2.2.0.min.js"></script>
        <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
        <script src="js/media-recorder.js"></script>
    </body>
</html>
<?php ob_end_flush();?>

这是更新帐户的方法。

public void updateAccounts(List<String> accountIds, final SampleCallback callback) {
    for (String accountId : accountIds) {
         getAccountsAsync(accountId, new MySampleCallback() {
             @Override public void result(AccountResponse response) {
                 callback(response);
             }
         }
    }
}

这是我的回调界面

void getAccountsAsync(String accountId, final MySampleCallback callback) {
     //Execution of request
     callback.result(new AccountsResponse("Just a sample response from the service"));
}

问题是,在我执行循环时,我只得到列表最后一项的结果,例如 我有一个String列表 - &gt; “一个”,“两个”,“三个”

我得到的唯一结果是最后一项的三个结果。

其他两个被忽略,但是它们仍然被执行但是返回给我的唯一结果是最后一项。

我想要做的是,在循环的下一次迭代之前,我可以在执行下一次循环之前停止它吗?更像是运行使这个Async同步运行。

感谢。

1 个答案:

答案 0 :(得分:0)

我认为你试图以错误的方式解决这个问题。您需要对N个项目进行异步调用。而不是进行N次调用,编写一个调用服务器上的一组id。