Android : 同步方式使用 asynctask : Json 上传问题
Android : Synchronous way to use asyncttask : Json upload issue
更新
在下方查看我的回答
我正在尝试以 json 格式发送多个学生数据和他们的回复。
问题
当 table 中有多行时。该功能一次发出多个请求。然后我从回调函数中得到多个响应...我想要一个请求及其回调。然后提出新的要求
我要这个
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());
}
}
}
As per the docs here,可以通过"get()"方法同步使用AsyncTaskclass。
一个简单的例子:
MyAsyncTask task = new MyAsyncTaskTask();
String result = task.execute().get();
class MyAsyncTask extends AsyncTask<Void,Void,String>{...}
根据其中一条评论,Volley 还具有 运行 异步的能力。
一个合适的解决方案。
protected void sendJson()
{
if(isOnline())
{
Thread t = new Thread() {
public void run() {
Looper.prepare(); //For Preparing Message Pool for the child Thread
HttpClient client = new DefaultHttpClient();
HttpConnectionParams.setConnectionTimeout(client.getParams(), 100000); //Timeout Limit
HttpResponse response;
// JSONObject json = new JSONObject();
try {
String URL ="http://{Your URL }/Service/RegisterStudent";
HttpPost post = new HttpPost(URL);
JSONObject StudentData = new JSONObject();
String android_id = Secure.getString(AdminSection.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);
// Toast.makeText(getBaseContext(), finaldata.toString(), Toast.LENGTH_LONG).show();
StringEntity se = new StringEntity( finaldata.toString());
se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
post.setEntity(se);
response = client.execute(post);
String jsonString = EntityUtils.toString(response.getEntity());
JSONObject resp = null;
resp = new JSONObject(jsonString);
JSONObject UploadStudentDataResult = resp.getJSONObject("RegisterStudentResult");
String strMessage = UploadStudentDataResult.getString("IsUploaded");
// Toast.makeText(getBaseContext(), strMessage, Toast.LENGTH_LONG).show();
if (StudentIDForSave != null)
{
SQLiteDatabase db1;
ContentValues values = new ContentValues();
values.put(DBHelper.isUploaded, strMessage);
// Call update method of SQLiteDatabase Class and close after
// performing task
db1 = helper.getWritableDatabase();
db1.update(DBHelper.TABLEStudent, values, DBHelper.S_ID + "=?",
new String[] { StudentIDForSave});
db1.close();
//Toast.makeText(getBaseContext(), "saved", Toast.LENGTH_LONG).show();
}
}
}catch(Exception e) {
e.printStackTrace();
//createDialog("Error", "Cannot Estabilish Connection");
}
Looper.loop(); //Loop in the message queue
}
};
t.start();
}
}
更新
在下方查看我的回答
我正在尝试以 json 格式发送多个学生数据和他们的回复。
问题
当 table 中有多行时。该功能一次发出多个请求。然后我从回调函数中得到多个响应...我想要一个请求及其回调。然后提出新的要求
我要这个
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());
}
}
}
As per the docs here,可以通过"get()"方法同步使用AsyncTaskclass。
一个简单的例子:
MyAsyncTask task = new MyAsyncTaskTask();
String result = task.execute().get();
class MyAsyncTask extends AsyncTask<Void,Void,String>{...}
根据其中一条评论,Volley 还具有 运行 异步的能力。
一个合适的解决方案。
protected void sendJson()
{
if(isOnline())
{
Thread t = new Thread() {
public void run() {
Looper.prepare(); //For Preparing Message Pool for the child Thread
HttpClient client = new DefaultHttpClient();
HttpConnectionParams.setConnectionTimeout(client.getParams(), 100000); //Timeout Limit
HttpResponse response;
// JSONObject json = new JSONObject();
try {
String URL ="http://{Your URL }/Service/RegisterStudent";
HttpPost post = new HttpPost(URL);
JSONObject StudentData = new JSONObject();
String android_id = Secure.getString(AdminSection.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);
// Toast.makeText(getBaseContext(), finaldata.toString(), Toast.LENGTH_LONG).show();
StringEntity se = new StringEntity( finaldata.toString());
se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
post.setEntity(se);
response = client.execute(post);
String jsonString = EntityUtils.toString(response.getEntity());
JSONObject resp = null;
resp = new JSONObject(jsonString);
JSONObject UploadStudentDataResult = resp.getJSONObject("RegisterStudentResult");
String strMessage = UploadStudentDataResult.getString("IsUploaded");
// Toast.makeText(getBaseContext(), strMessage, Toast.LENGTH_LONG).show();
if (StudentIDForSave != null)
{
SQLiteDatabase db1;
ContentValues values = new ContentValues();
values.put(DBHelper.isUploaded, strMessage);
// Call update method of SQLiteDatabase Class and close after
// performing task
db1 = helper.getWritableDatabase();
db1.update(DBHelper.TABLEStudent, values, DBHelper.S_ID + "=?",
new String[] { StudentIDForSave});
db1.close();
//Toast.makeText(getBaseContext(), "saved", Toast.LENGTH_LONG).show();
}
}
}catch(Exception e) {
e.printStackTrace();
//createDialog("Error", "Cannot Estabilish Connection");
}
Looper.loop(); //Loop in the message queue
}
};
t.start();
}
}