请注意:我已阅读其他相关问题。
我有一个DatabaseCall类,其中包含检索特定数据的函数。我已经在下面添加了代码,我只是得到了所有问题等。
我将从testActivity.class
拨打此邮件,因此我可以填充list<Questions>
,但是因为这是异步的,我无法从onPostExecute
返回任何内容; d在活动中称之为 - 但是我的代码变得太乱了。
以下CodeCall类代码
public class DatabaseCalls {
public List<Question> getTestQuestionsFromDatabase(){
class LoginAsync extends AsyncTask<String, Void, String>{
private Dialog loading;
@Override
protected List<Question> onPostExecute(String s){
loading.dismiss();
Log.d("PostExecute", "JSON!: " + s);
try{
JSONObject jObj = new JSONObject(s);
boolean error = jObj.getBoolean("error");
List<Question> listQuestions = new ArrayList<Question>();
if (!error){
for (int i=0; i<11; i++){
JSONObject question = jObj.getJSONObject(Integer.toString(i));
Question qObj = new Question(Integer.parseInt(question.getString("questionID")), question.getString("question"), Integer.parseInt(question.getString("answerID")), Integer.parseInt(question.getString("complexityID")));
listQuestions.add(qObj);
}
return listQuestions;
}else{
String errorMsg = jObj.getString("error_msg");
/**
* Can't toast here because it is a helper class - it isn't
* an activity - need to return an empty object instead?
*/
//Toast.makeText(getApplicationContext(),errorMsg, Toast.LENGTH_LONG).show();
}
}catch(JSONException e){
e.printStackTrace();
}
}
@Override
protected String doInBackground(String... params) {
String s = params[0];
BufferedReader bufferedReader = null;
try {
URL url = new URL(AppConfig.Questions_URL + s);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestProperty ("Authorization", "Basic Z2FycmV0dGg6ZnJBc3Rpbmc0");
bufferedReader = new BufferedReader(new InputStreamReader(con.getInputStream()));
//This string is returned to the onPostExecute
String result;
result = bufferedReader.readLine();
return result;
}catch(Exception e){
Log.d("Exception in try", "Exception" + e.toString());
return null;
}
}
}
LoginAsync la = new LoginAsync();
la.execute();
}}
我该如何对抗这个?并返回一个值。