0

I am creating a Quiz app on android studio and the questions will be called from an URL containing a JSONObject, and since these API calls happen asynchronously, i have to make sure that my app is waiting for the server to respond with a callback, below is the parsing method i created following some internet tutorials, it would be nice if you could help me understand which changes should i apply

private void jsonParse(){
    final Question[] quest =new Question[10];
    String url="https://opentdb.com/api.php?amount=10";
    JsonObjectRequest request =new JsonObjectRequest(Request.Method.GET, url, null,
            new Response.Listener<JSONObject>() {
                @Override
                public void onResponse(JSONObject response) {
                    try {
                        JSONArray ja=response.getJSONArray("results");
                        for(int i=0;i<3;i++){
                            JSONObject temp_quest=ja.getJSONObject(i);
                            String question =temp_quest.getString("question");
                            String correctanswer=temp_quest.getString("correct_answer");

                           String incorrectanswer_1=(String)temp_quest.getJSONArray("incorrect_answers").getString(0);
                            String incorrectanswer_2=(String)temp_quest.getJSONArray("incorrect_answers").getString(1);
                            String incorrectanswer_3=(String)temp_quest.getJSONArray("incorrect_answers").getString(2);
                           String[] temp=new String[3];
                           temp[0]=incorrectanswer_1;
                           temp[1]=incorrectanswer_2;
                           temp[2]=incorrectanswer_3;
                           quest[i]=new Question(question,correctanswer,temp);
                            mTextViewResult.append(quest[i].getQuestion()+" \n"+ quest[i].getCorrectAnswer()+"\n "+
                                            quest[i].getAnswer(1)+"\n "+quest[i].getAnswer(2)+"\n "+
                                    quest[i].getAnswer(3)+"\n" +quest[i].getAnswer(4)+"\n\n");

                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }


                }
            }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            error.printStackTrace();

        }
    });
    mQueue.add(request);
}

}

Demha
  • 29
  • 6

1 Answers1

-1

I consider that you are not using the correct form to call a service.

  • You can use a async task

    package principal.concrete.concrete;

    import android.os.AsyncTask; import android.util.Log;

    import java.io.IOException; import java.net.URL; import java.net.HttpURLConnection; import java.io.BufferedReader; import java.io.InputStreamReader;

    public class Post extends AsyncTask<String, Void, String> {

      private InputStreamReader inputStreamReader;
      private BufferedReader bufferedReader;
    
      @Override
      protected String doInBackground(String... params){
    
          try {
              URL obj = new URL(params[0]);
              HttpURLConnection con = (HttpURLConnection) obj.openConnection();
              con.setRequestMethod("GET");
              con.setRequestProperty("User-Agent", " ");
              con.connect();
              inputStreamReader=new InputStreamReader(con.getInputStream());
              bufferedReader = new BufferedReader(inputStreamReader);
              return bufferedReader.readLine();
          }catch(Exception e){
              Log.d("Url  doInBackground", e.toString());
              return null;
          } finally {
              try {
                  closeConnection();
              } catch(Exception e){
    
              }
          }
    
      }
    
      private void closeConnection() {
          try {
              if(bufferedReader!=null){
                  bufferedReader.close();
              }
    
              if(inputStreamReader!=null){
                  inputStreamReader.close();
              }
          }catch(IOException ex){
              Log.d("Url disconnect", ex.toString());
          }
      }
    
      @Override
      protected void onPostExecute(String result){
    
          super.onPostExecute(result);
      }
    

    }

  • You can use a retrofit to call a service

link the implementation

https://programacionymas.com/blog/consumir-una-api-usando-retrofit

I have a code to call service

asyn task

Alejandro Gonzalez
  • 1,221
  • 4
  • 15
  • 30
  • so this can't be done using the Volley library ? because as i understood i need to wait for server's response and then return a value(the questions and answers) from the onResponse, because i will be working with the value next in my application – Demha Jun 30 '20 at 14:58
  • It is not neccesary to use a external library to call service, you can use asyn task and wait the respond – Alejandro Gonzalez Jun 30 '20 at 15:09
  • This may be working but i need it done with the volley library, i saw some works that match with my work but a part from it is still unclear to me https://stackoverflow.com/questions/28120029/how-can-i-return-value-from-function-onresponse-of-volley – Demha Jun 30 '20 at 15:35
  • what part haven't you understood it? – Alejandro Gonzalez Jun 30 '20 at 16:23
  • i didn't understand where has he implemented the function onResume for example how could i reform my code to match his form ? I made a new Interface called VolleyCallback like him and still don't know if my method get String should move to another class or it should stay in the activity class – Demha Jun 30 '20 at 17:48
  • can you put the complete code to check it? because your code is giving me a little idea. – Alejandro Gonzalez Jun 30 '20 at 18:40
  • There's no reason the OP should switch from Volley. Volley requests are asynchronous in much the same way as would be achieved with an `AsyncTask`. This answer is unhelpful. – codebod Jun 30 '20 at 18:47
  • https://drive.google.com/file/d/1z99d2BzWi9ngxBU-afEN6sJEJs6W8lsS/view?usp=sharing https://drive.google.com/file/d/1KbM5v84zeRlnj0mM838-PQQhduQKo9kc/view?usp=sharing https://drive.google.com/file/d/103roYVuubBhrF31-aeWLl8WrrLmfE5dj/view?usp=sharing – Demha Jun 30 '20 at 21:14