简体   繁体   English

如何从内部方法向ArrayList添加值?

[英]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. 我目前正在尝试从另一个类内部的方法向ArrayList对象添加值。

Here is the class I have created for the ArrayList Object: 这是我为ArrayList对象创建的类:

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: 我尝试编辑ArrayList对象的另一个类:

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. 如果查看onResponse方法,则可以看到尝试将jsonResponse的值添加到ArrayClass对象中的ArrayClass 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. 我习惯于使用python全局变量,而不必处理java的语义,因此,如果您可以对需要进行哪些更改有所了解,我将不胜感激。

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. 除了针对您所面临问题的其他给定答案/解决方案之外,让我分享一种最佳且优化的方法来在Android中实现JSON解析。

I would suggest you to check GSON or Jackson libraries which provides Java serialization/deserialization that can convert Java Objects into JSON and back. 我建议您检查GSONJackson库,它们提供了Java序列化/反序列化功能,可以将Java对象转换为JSON并反过来

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. 删除ArrayClass中所有static关键字的情况。 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: 您也可以尝试使用ArrayList:

First do some changes in your ArrayClass. 首先在ArrayClass中进行一些更改。 Use get And Set method to access your array. 使用get And Set方法访问数组。

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: 您尝试编辑ArrayList的其他类使用getArray和SetArray方法以及ArrayList的一些预定义方法,如下所示:

Store the data in ArrayList: 将数据存储在ArrayList中:

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

Get Size of ArrayList: 获取ArrayList的大小:

  fill.getArray().size();

And also you can store an another ArrayList like 而且您还可以存储另一个ArrayList

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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