Kayne Khoury Kayne Khoury - 7 months ago 11
Java Question

How can I add a value to an ArrayList from an inner method?

I am currently trying to add a value to an

ArrayList
object from a method inside of another class.

Here is the class I have created for the
ArrayList
Object:

public class ArrayClass {

public static ArrayList<String> array = new ArrayList<>();

public static void add_val(String s){
array.add(s);
}

public static int get_size(){
return array.size();
}

public static String get_val(int i){
return array.get(i);
}
}


And the other class where I attempt to edit the
ArrayList
object:

ArrayClass fill = new ArrayClass();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_explore);
Response.Listener<String> responseListener4 = new Response.Listener<String>(){
@Override
public void onResponse(String response) {

try {
JSONObject jsonResponse4 = new JSONObject(response);
boolean success = jsonResponse4.getBoolean("success");
if (success){
int l;
String filled;
int length4 = jsonResponse4.length();
for (l=0;l<length4;l++){
filled = jsonResponse4.getString(l+"");
fill.add_val(filled);
}
}else{
AlertDialog.Builder builder = new AlertDialog.Builder(ExploreActivity.this);
builder.setMessage("Could not retrieve restaurant tables filled")
.setNegativeButton("Retry", null)
.create()
.show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
};
FilledRequest filledRequest = new FilledRequest(responseListener4);
RequestQueue queue4 = Volley.newRequestQueue(ExploreActivity.this);
queue4.add(filledRequest);


If you look in the
onResponse
method, you can see the attempt to add a value from the
jsonResponse
into the
ArrayClass
object. However, when I launch my app, it does not add the value into the object. I'm used to python global variables and not having to deal with the semantics of java, so if you could shed some light on what changes need to be made, I would greatly appreciate it.

Answer

Firstly, since your variable is static, and the methods are static too, you don't have to instantiate the object. You could do something like this:

ArrayClass.add_val("Hello");

But if you want to instantiate then you can do this:

public class ArrayClass {

    private ArrayList<String> array;

    public ArrayClass() {
        array = new ArrayList<>();
    }

    public void add_val(String s){
        array.add(s);
    }

    public int get_size(){
        return array.size();
    }

    public String get_val(int i){
        return array.get(i);
    }
}

To make sure the values are filled in, you can check the array size like this:

 for (l=0;l<length4;l++){
     filled = jsonResponse4.getString(l+"");
     fill.add_val(filled);
 }
 Log.d("TEST", String.valueOf(fill.get_size());
Comments