0

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.

bananabreadbob
  • 369
  • 2
  • 10
  • 26
  • 1
    Are you trying to make your AsyncTask blocking? What's the point of using an AsyncTask in the first place if it blocks..? – Matti Virkkunen Mar 05 '16 at 16:18
  • Im sorry, I don't understand that. I am new to android and I read that Async task was the best way to make calls to the server. @MattiVirkkunen – bananabreadbob Mar 05 '16 at 16:19
  • Yes but there's no point in using it if you're trying to circumvent what it's actually meant to do. You need to arrange it so that whatever you want to happen after your server call is done is done in `onPostExecute` or called from it. – Matti Virkkunen Mar 05 '16 at 16:20
  • So I want the response from the server call to be returned to where `getTestQuestionsFromDatabase` is called in another activity @MattiVirkkunen – bananabreadbob Mar 05 '16 at 16:24
  • That is exactly what I mean by circumventing what AsyncTask does. In order to wait for the return value to be available you'd have to make the call block, which is exactly what you're trying to avoid by using AsyncTask in the first place! You can't have that method return the value. – Matti Virkkunen Mar 05 '16 at 16:26
  • Oh! So to combat it I would just have to have a call that isn't asynchronous? @MattiVirkkunen – bananabreadbob Mar 05 '16 at 16:27
  • As long as you don't call it from your UI thread because blocking in the UI thread is not a good idea. – Matti Virkkunen Mar 05 '16 at 16:28
  • 1
    What you really need is a callback from the `AsyncTask` to deliver the results to whatever is interested in them. Take a look [here](http://stackoverflow.com/a/9963705/1435985) for an example. – George Mulligan Mar 05 '16 at 16:38

0 Answers0