您好我有一个运行我的getQus类的类(通过asynctask) 现在的问题是我试图以这样的方式设置它,如果 我的返回结果为null,用更新的变量再次重新运行getQus,即增加我的主题&直到我得到一个有效的结果。
这是我的系统流程。 第一类(设置主题& lvl) - >将主题& lvl传递给getQus - > getQus通过onPostExecute(委托)返回结果。
第一类代码
public void GenerateQus(){
//run code to get new qus
x.setLvl(lvl);
x.setTopic(topic);
System.out.println("GENERATEQUS:"+ lvl +" , "+topic);
new getQus(CAT.this).execute(x);
}
getQus Class
protected Question doInBackground(Level... params) {
int r = params[0].getLvl();
int z = params[0].getTopic();
System.out.println("getQlvl:" + r);
System.out.println("getQtopic:" + z);
String range = String.valueOf(r);
String topic = String.valueOf(z);
// TODO Auto-generated method stub
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("range",range));
nameValuePairs.add(new BasicNameValuePair("topic",topic));
int q_id = 0;
String result=null;
String q_qus =" ";
String result2 = " ";
Question q = new Question();
InputStream is = null;
try {
Globals g = Globals.getInstance();
String ip = g.getip();
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://"+ip+"/fyp/qus.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
}catch(Exception e){
Log.e("log_tag", "Error in http connection "+e.toString());
}
//convert response to string
try{
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result2=sb.toString();
System.out.println("TEDASD: "+result2);
if(result2.equals("[]")){
//to rerun again
}
我该怎么办才能让getQus再次重新召唤自己?提前谢谢!
答案 0 :(得分:0)
在onPostExecute()方法中,您将获得结果。所以,如果你的结果为null,那么就开始使用AysncTask itselt。
答案 1 :(得分:0)
如果我理解你的问题,你只想在doInBackground中重新运行逻辑。那么,你为什么不这样做呢?
protected Question doInBackground(Level... params) {
Question q;
while((q = doTheStuff(params))==null){
updateParams(params);
}
return q;
}
private Question doTheStuff(Level.. params){
//your logic here
}
private void updateParams(Level.. params){
//update params here
}
如果只能在主线程中更新x,则可以在onPostExecute中重新执行该任务:
public class SomeActivity extends Activity {
private X x = new X();
@Override protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
new AsyncTask<X, String, Long>() {
@Override protected Long doInBackground(final X... params) {
// do something here
return null;
}
@Override protected void onPostExecute(final Long result) {
if (result == null) {
// update args and restart task
x.setFoo("a");
x.setBar("b");
execute(x);
}
}
}.execute(x);
}
private class X {
String foo;
String bar;
public void setFoo(final String foo) {
this.foo = foo;
}
public void setBar(final String bar) {
this.bar = bar;
}
}
}