Android:使用asyncttask的同步方式:Json上传问题

时间:2015-08-18 09:45:54

标签: android json rest httpclient

更新
检查下面的答案

我正在尝试以json格式发送多个学生数据及其响应。

问题

表格中有多行时。 Function一次发出多个请求。然后我从Callback函数得到多个响应...我想要一个请求及其回调。那么新的要求

我想要这个

 final ConnectToServer connect = new ConnectToServer();
            connect.extConnectToServer(AdminSection.this,new ConnectToServer.Callback() 

在每个请求发出后调用的函数。完成整个循环后调用回调函数。

代码

 public void Uploadalldata()
        {    
            if(isOnline())
            {   
              JSONObject StudentData = new JSONObject();    
               try
                 {

             String android_id = Secure.getString(this.getContentResolver(),Secure.ANDROID_ID);
             DBHelper db = new DBHelper(getApplicationContext());
             List<StudentClass> StudentDataAll = db.getAllStudentData();
             for(int iCount=0; iCount< StudentDataAll.size(); iCount++)
                {
                 StudentClass objStudentClass= (StudentClass)StudentDataAll.get(iCount);
                 String sSingleStudentCompleteDetails= android_id +","+ objStudentClass.RegistrationId + "," + objStudentClass.Name + "," + objStudentClass.SchoolID + "," + objStudentClass.Class + "," + objStudentClass.RollNo + "," + objStudentClass.RegistrationDate;
                 String sSingleStudentCompleteResponse = "";     
                 String strStudentID = objStudentClass.RegistrationId;       
                 StudentIDForSave = strStudentID;

                 List<StudentResponse> StudentResponse = db.getStudentResponseOnStudentID(strStudentID);

                    for(int iOptionCount=0; iOptionCount<StudentResponse.size(); iOptionCount++)
                        {

                           StudentResponse objStudentResponse=StudentResponse.get(iOptionCount);
                           if(iOptionCount>0) 
                        sSingleStudentCompleteResponse += ",";

                        sSingleStudentCompleteResponse += objStudentResponse.QuestionID + "-" + objStudentResponse.OptionID;

                        }
                    StudentData.put("StudentDetails", sSingleStudentCompleteDetails);
                    StudentData.put("Responses", sSingleStudentCompleteResponse);

                    JSONObject finaldata = new JSONObject();
                    finaldata.put("RegisterStudentRequest", StudentData);

         final ConnectToServer connect = new ConnectToServer();
            connect.extConnectToServer(AdminSection.this,new ConnectToServer.Callback() 
            {
                public void callFinished(String result)
                {
                    JSONObject resp = null;

                    try 
                    {
                        resp = new JSONObject(result);
                        JSONObject UploadStudentDataResult = resp.getJSONObject("RegisterStudentResult");

                        String strMessage = UploadStudentDataResult.getString("IsUploaded");

                        if (StudentIDForSave != null)
                        {
                            SQLiteDatabase db;
                            ContentValues values = new ContentValues();
                            values.put(DBHelper.isUploaded, strMessage);


                        // Call update method of SQLiteDatabase Class and close after
                        // performing task
                        db = helper.getWritableDatabase();
                        db.update(DBHelper.TABLEStudent, values, DBHelper.S_ID + "=?",
                                new String[] { StudentIDForSave});
                        db.close();
                        //Toast.makeText(getBaseContext(), "saved", Toast.LENGTH_LONG).show();
                        }
//                      else
//                      {
//                          Toast.makeText(getBaseContext(), "Data not saved", Toast.LENGTH_LONG).show();
//                      }

                    }


                    catch (final JSONException e)
                    {

                    }

                }
                    }, "http://myurl/Service/RegisterStudent", finaldata, "POST");
                connect.execute(finaldata).get();


     }

 }
  catch (Exception e) {
     Log.d("InputStream", e.getLocalizedMessage());
}
            }
     }

1 个答案:

答案 0 :(得分:1)

As per the docs here,可以使用&#34; get()&#34;同步使用AsyncTask类。方法。

一个简单的例子:

    //all my countries
    var countries = ["england", "france", "germany", "hungary", "ireland",    `"italy"`, "norway", "spain", "wales"]

    //gets the screen height and width for the game
    var scnWid,scnHei;
    if (self.innerHeight) // works for all except Internet Explorer
    {
    scnWid = self.innerWidth;
    scnHei = self.innerHeight;
    }
    else if (document.documentElement &&    document.documentElement.clientHeight)
    // internet explorer 6 fix 
    {
    scnWid = document.documentElement.clientWidth;
    scnHei = document.documentElement.clientHeight;
    }
    else if (document.body) // Other versions of ie
    {
    scnWid = document.body.clientWidth;
    scnHei = document.body.clientHeight;
    } 


    //shuffles the country array
    function shuffleArray(arr) {
        var currentIndex = arr.length, temporaryValue, randomIndex ;

    //array hasnt stopped
    while (0 !== currentIndex)


    //find a random element
    randomIndex =Math.floor(Math.random() * currentIndex);

    //swap it with current element

    temporaryValue = arr[currentIndex];
    arr[currentIndex] = arr[randomIndex];
    arr[randomIndex] = temporaryValue;

    //returns the shuffle array
    return arr;
    }







    //variables for the functionality of the game


    var randomCountry;
    var score;
    var count;
    var cityClicked;
    var winningscore;

    //will be passed when the function is called

    function gameInit(){

    //calculate the number of correct
    winningscore = Math.round(3*2)


    //the score variable
    score = 0;

    //is the city clicked yes or no
    cityClicked = false;

    var gameCountries = [];
    var gameCountryCities =[];

    //shuffles the existing countries array

    gameCountries = shuffleArray(countries)

    //loops throught the countries and attached names

    for (i = 0; i<gameCountries.length; i++)
    { 
    document.getElementById('gameCountry').innerHTML += "div class='countryName'    id= '" + gameCountries[i] + "' onclick='CountryClick'(this.id)'><img src='countries/" + gameCountries[i] + ".gif'></div>" ;}
    }

    //reshufflies the cities
    gameCountryCities = shuffleArray(gameCountries)

//loops through the countries and displays the attached cities

for (j = 0; j<gameCountryCities.length; j++ )
{ document.getElementById('gameCity').innerHTML += "<div class='countrycity' id='country-" + gameCountryCities[j] + "' onclick='cityClick(this.id)'><img src= 'cities/" + gameCountryCities[j] + ".gif'></div>" ;
}
}


//when a city is clicked

function cityClick(cityClickedId)
{
if (cityClicked == true)
{
//does the city and country match
if "country-" + selectedCity == cityClickedId)

{
    //add one to the the score

score = score +1;

//show the pop up and score

document.getElementById("gamePopup").style.display = "block";
document.getElementById("gamePopup").style.height = scnHei*2;
document.getElementById("gamePopup").style.display = "block";
document.getElementById("gamePopup").style.top = scnHei+150;

//GAME





//if the score is less than the winning score the player loses

if (score <winningscore){

    gameMessage = "You Lose"
}

//otherwise they win

else {gameMessage = "You Win"}

    //Show the game over pop up within the score

document.getElementById("popupBox").innerHTML = 
"<div>Game Over</div<div>" + gameMessage +
"</div><div>Your Score is : " + score 
+ "</div>";

//show the game over pop up with the score

document.getElementById("gamePopup").style.display = "block";
document.getElementById("gamePopup").style.height = scnHei*2;
document.getElementById("popupBox").style.display = "block";
document.getElementById("popupBox").style.top = scnHei+150;

//After 5 seconds redirect the user to the level select menu

setTimeout(function(){
    window.location = "level.html";
}, 5000);

}

根据其中一条评论,Volley还具有异步运行的能力。