Android Studio如何拥有永久变量

时间:2018-05-07 19:15:38

标签: java android android-studio variables global-variables

我想创建一个具有变量的类,可以修改此变量并从其他活动中获取该变量,并始终保存此变量。

我尝试使用变量“TipoAnuncio”执行此类:

public class Filter_Object  {
    private String TipoAnuncio ="Perdidos";

    public String getTipoAnuncio(){
        return TipoAnuncio;
    }
    public void setTipoAnuncio(String TipoAnuncio){
        this.TipoAnuncio = TipoAnuncio;
    }
}

我试图从其他活动中设置此变量,例如:

public class FilterActivity extends AppCompatActivity {

    private Filter_Object filter;
protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_filter);


        Log.i("anuncioahora", filter.getTipoAnuncio());
}
}

出现错误,上面写着:java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.julianrc1.petracecitm/com.example.julianrc1.petracecitm.fragments.Intents.FilterActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String com.example.julianrc1.petracecitm.Objects.Filter_Object.getTipoAnuncio()' on a null object reference

感谢您的帮助:)

1 个答案:

答案 0 :(得分:0)

使用static变量。示例:public static String TipoAnuncio = "Perdidos";

访问/修改为:Filter_Object.TipoAnuncio