简体   繁体   English

不同类java之间的全局变量

[英]global variables between different classes java

i am on the creation of an app in android. 我在android中创建了一个应用程序。 its a calculator app. 它是一个计算器应用。 the main activity is where the user could input the equation, and the second activity is where the user can add/edit/delete variables. 主要活动是用户可以输入等式的位置,第二个活动是用户可以添加/编辑/删除变量的位置。 so i made a new class in another file named Global.java. 所以我在另一个名为Global.java的文件中创建了一个新类。 then i extended it to application, imported everything i need, made s private string, made some public functions, edited the manifest, and initialized it right on my main activity. 然后我将它扩展到应用程序,导入我需要的所有内容,制作私有字符串,制作一些公共函数,编辑清单,并在我的主要活动上初始化它。 everything works fine while im only using a string to be passed by the functions but when i started adding what i need, an ArrayList, and made some functions so i could access the list then run it, the app closes. 一切正常,而我只使用一个字符串来传递函数,但当我开始添加我需要的东西,一个ArrayList,并做了一些功能,所以我可以访问列表然后运行它,应用程序关闭。 i think its because the arraylist is not allowed to be passed to different classes? 我认为是因为arraylist不允许被传递到不同的类? am i right or am i just missing something? 我是对的还是我错过了什么?

please dont downvote my post if i didn't post something needed. 如果我没有发布需要的东西,请不要低估我的帖子。 i am using aide so there is no log output. 我正在使用助手,所以没有日志输出。 code: Global.java 代码: Global.java

...
import android.app.*;
import java.util.*;

public class Global extends Application
{
    private String s;
    public static ArrayList<String> sList;

    public String getS() {
        return s;
    }
    public void setS(String ss) {
        s=ss;
    }
    public void add() {
        sList.add(s);
    }
}

MainActivity.java MainActivity.java

...
    String s;
... 
        global=(Global)getApplicationContext();
...
        global.setS("jian"); //this one works
        global.sList.add("jian"); // this one dont
...

Are you sure you initialized sList, like this: 你确定你初始化了sList,如下所示:

sList = new ArrayList<String>();

If you didn't, you might want to change its declaration to include this initialization. 如果没有,您可能希望更改其声明以包含此初始化。

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

Just do 做就是了

global.add("jian"); 

since you have an add function to take care of the addition of item to arraylist. 因为你有一个添加功能来处理项目添加到arraylist。

Also, try with this: 另外,试试这个:

  public void add(String ss) {
    sList.add(ss);
}

You are not instantiating your arraylist. 你没有实例化你的arraylist。

    public static ArrayList<String> sList = new Arraylist<String>();

Also you should read beginner tutorials on Java and android, using a public extension of application like this is a bad idea and you can get log outputs from different apps if Aide doesn't provide that, search play store 另外你应该阅读关于Java和android的初学者教程,使用像这样的应用程序的公共扩展是一个坏主意,你可以从不同的应用程序获取日志输出,如果Aide不提供,搜索游戏商店

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

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