Please note: I have read the other questions relating.
I have a DatabaseCall class with functions to retrieve specific data. I have added the code below where I simply get all questions etc.
I will be calling this from a testActivity.class
, so I can populate a list<Questions>
, however because this is asynchronous I can't return anything from onPostExecute
previously I'd called this within the activity - however my code was getting far too messy.
Code below for the DatabaseCall class
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();
}}
How can I combat this? and return a value.