简体   繁体   中英

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.

Apart from other given answers/solutions to the issue you are facing, let me share a best and optimized way to implement JSON parsing in Android.

I would suggest you to check GSON or Jackson libraries which provides Java serialization/deserialization that can convert Java Objects into JSON and back.

There are some benefits it does provide, one of the main benefits is you do not need to implement parsing manually and less chances of mistakes in implementing parsing, like you may make a mistake in mentioning key "Success" or "success" or any such silly mistakes!

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());

Remove all cases of the static keyword in ArrayClass. Static methods are class level methods, ie. are called on the class itself, rather than an instance of the class.

You can also try this, for ArrayList:

First do some changes in your ArrayClass. Use get And Set method to access your array.

public class ArrayClass {
   private ArrayList<String> array = new ArrayList<>();
   public ArrayList<String> getArray() {
      return array;
    }
   public void setArray(ArrayList<String> array) {
      this.array = array;
   }

}

And your other class where you attempt to edit the ArrayList use getArray And SetArray method and some predefined method of ArrayList like this:

Store the data in ArrayList:

 for (l=0;l<length4;l++){
      filled = jsonResponse4.getString(l+"");
       fill.getArray().add(filled);
    }

Get Size of ArrayList:

  fill.getArray().size();

And also you can store an another ArrayList like

ArrayList<String> tempArrayList = new ArrayList<String>();
tempArrayList.add("string 1");
tempArrayList.add("string 2");
tempArrayList.add("string 3");
tempArrayList.add("string 4");

fill.setArray(tempArrayList)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM