Menu
Who Do Is
  • Home
  • What
  • How
  • Is
  • Can
  • Are
  • Does
  • Do
  • Why
  • Who
  • Where
  • Which
  • Which
  • Should
  • Will
  • When
  • What’s
  • Did
Who Do Is

[ANSWERED] java – stuck in getting arraylist from another class in android

Posted on November 14, 2022

Solution 1 :

Implement the callback pattern.

Create a new Interface file:

Interface MyVolleyResponse {
    void onResponse(JSONArray response);
    void onError(VolleyError error);
}

Your activity should implement this, as follows:

public class MainActivity extends AppCompatActivity implements MyVolleyResponse {...}

Add the new methods to your activity:

void onResponse(JSONArray response) {
    // process your response here, building your question array...
}

void onError(VolleyError error) {
    // handle errors here...
}

Change your Volley responses within SetQ:

public void onResponse(JSONArray response) {
    callback.onResponse(response);
}

public void onErrorResponse(VolleyError error) {
    callback.onError(error);
}

Create a constructor within SetQ to set the callback:

private MyVolleyResponse callback;

SetQ(MyVolleyResponse callback) {
    this.callback = callback;
}

Call this constructor in your activity with:

SetQ volley = new SetQ(this);

Change the signnature of getData to just:

void getData() {...}

And run the Volley call with volley.getData().

Remove all AsyncTask objects in your code, because Volley is already asynchronous.

Problem :

I’m making a project in which i get data through api and stored it in arraylist but when i return it, it is empty.
Can Anyone Help Me Out?

Here is the Main Activity

package com.example.trivia;

import androidx.appcompat.app.AppCompatActivity;
import androidx.cardview.widget.CardView;

import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.TextView;

import com.example.trivia.Data.Async;
import com.example.trivia.Data.setQ;
import com.example.trivia.controller.AppController;
import com.example.trivia.model.question;

import org.json.JSONArray;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {
   private CardView c;
   private Button t_btn,f_btn;
   private ImageButton next,prev;
   private List<question>q;
   private TextView set;
   private int count=0;

   @Override
   protected void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
       setContentView(R.layout.activity_main);
       c=findViewById(R.id.cardView);
       t_btn=findViewById(R.id.true_btn);
       f_btn=findViewById(R.id.false_btn);
       next=findViewById(R.id.next);
       prev=findViewById(R.id.prev);
       set=findViewById(R.id.setq);


       //ArrayList<question> dummy = new ArrayList<question>();
       //AppController.OnCreate();
       q=new setQ().getData(new Async() {
           @Override
           public void finish(ArrayList<question> c) {
               set.setText(c.get(count).getQ());
             //  Log.d("test", "onCreate: "+c);
           }
       });

       Log.i("in main", "Main: "+q.size());
   }

}

the code of setQ class

package com.example.trivia.Data;

import android.util.Log;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonArrayRequest;
import com.example.trivia.controller.AppController;
import com.example.trivia.model.question;
import org.json.JSONArray;
import org.json.JSONException;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.List;

public class setQ {
    ArrayList<question> q =new ArrayList<question>();
    JSONArray r;
    private String url="https://raw.githubusercontent.com/curiousily/simple-quiz/master/script/statements-data.json";
    public List<question> getData(final Async call) {

        final JsonArrayRequest jarr = new JsonArrayRequest(Request.Method.GET, url, (JSONArray)null, new Response.Listener<JSONArray>() {
            @Override
            public void onResponse(JSONArray response) {
                r=response;
                for (int i = 0; i < response.length(); i++) {
                    try {
                        JSONArray  a = response.getJSONArray(i);
                        question k = new question(a.getString(0), a.getBoolean(1));
                        //Log.i("list", "onResponse: "+k.getAns());
                        q.add(k);
                       // Log.i("response", "onResponse: " +a.get(0));
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
                if(call!=null) {
                    call.finish( q);
                }
                //return q;
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {

            }
        });
        Log.i("error ",""+AppController.getInstance());
        AppController.getInstance().addToRequestQueue(jarr);
            return q;
       // return q;
    }
}

output

07/11 23:55:18: Launching 'app' on Pixel 3 API 21.
$ adb shell am start -n "com.example.trivia/com.example.trivia.MainActivity" -a android.intent.action.MAIN -c android.intent.category.LAUNCHER
Connected to process 15594 on device 'emulator-5554'.
Capturing and displaying logcat messages from application. This behavior can be disabled in the "Logcat output" section of the "Debugger" settings page.
W/art: Before Android 4.1, method android.graphics.PorterDuffColorFilter androidx.vectordrawable.graphics.drawable.VectorDrawableCompat.updateTintFilter(android.graphics.PorterDuffColorFilter, android.content.res.ColorStateList, android.graphics.PorterDuff$Mode) would have incorrectly overridden the package-private method in android.graphics.drawable.Drawable
I/art: Rejecting re-init on previously-failed class java.lang.Class<androidx.core.view.ViewCompat$2>
    Rejecting re-init on previously-failed class java.lang.Class<androidx.core.view.ViewCompat$2>
I/error: [email protected]

***I/in main: Main: 0***

D/OpenGLRenderer: Render dirty regions requested: true
D/: HostConnection::get() New Host Connection established 0x7f28894105c0, tid 15594
D/Atlas: Validating map...
I/art: Background sticky concurrent mark sweep GC freed 5802(428KB) AllocSpace objects, 0(0B) LOS objects, 0% free, 2MB/2MB, paused 8.789ms total 42.738ms
D/: HostConnection::get() New Host Connection established 0x7f28950b0e40, tid 15624
I/OpenGLRenderer: Initialized EGL, version 1.4
W/OpenGLRenderer: Failed to choose config with EGL_SWAP_BEHAVIOR_PRESERVED, retrying without...
D/EGL_emulation: eglCreateContext: 0x7f2894773200: maj 3 min 1 rcv 4
D/EGL_emulation: eglMakeCurrent: 0x7f2894773200: ver 3 1 (tinfo 0x7f289470fe40)
E/eglCodecCommon: glUtilsParamSize: unknow param 0x000082da
E/eglCodecCommon: glUtilsParamSize: unknow param 0x00008cdf
    glUtilsParamSize: unknow param 0x00008824
D/OpenGLRenderer: Enabling debug mode 0
D/EGL_emulation: eglMakeCurrent: 0x7f2894773200: ver 3 1 (tinfo 0x7f289470fe40)
I/Choreographer: Skipped 62 frames!  The application may be doing too much work on its main thread.

Comments

Comment posted by codebod

Your

READ  [ANSWERED] layout - how to create android linearlayout Tag?
Powered by Inline Related Posts

Recent Posts

  • How can I play with my cat without toys?
  • What is a bag pipe band called?
  • Are Honda Civics actually fast?
  • Are Yankee candles toxic?
  • How do I pair my Michael Kors smartwatch with my Android?

Recent Comments

No comments to show.

Archives

  • January 2023
  • December 2022
  • November 2022
  • October 2022
  • September 2022

Categories

  • ¿Cómo
  • ¿Cuál
  • ¿Cuántas
  • ¿Cuánto
  • ¿Que
  • ¿Quién
  • 90” and 108” so you may have to round up to the nearest size.
  • and delete any Spotify folders from it. Once this is done
  • Android
  • Are
  • At
  • Bei
  • blink
  • C'est
  • Can
  • carbs
  • Comment
  • Did
  • Do
  • Does
  • During
  • For
  • Has
  • How
  • In
  • Is
  • Ist
  • Kann
  • Können
  • nouveau
  • On
  • or 108 inches.2020-08-03
  • Où
  • owning
  • Pourquoi
  • Puis-je
  • Quand
  • Quante
  • Quel
  • Quelle
  • Quelles
  • Quels
  • Qui
  • Should
  • Sind
  • Sollte
  • spiritual
  • tap the downward-facing arrow on the top left. A downward-facing arrow will appear underneath each song in the album; they'll turn green as the download completes.2020-07-28
  • Uncategorized
  • Wann
  • Warum
  • Was
  • Welche
  • Welcher
  • Welches
  • Welke
  • Wer
  • Were
  • What
  • What's
  • When
  • Where
  • Which
  • Who
  • Whose
  • Why
  • Wie
  • Will
  • Wo
  • Woher
  • you will receive two curtains each with the same measurements of width 66"" (168cm) x drop 54""(137cm).
  • you'll see a green downward-facing arrow next to each song.2021-02-26
©2023 Who Do Is | Powered by SuperbThemes & WordPress