我正在尝试使用全局类来使对象数据在我的所有 Activity 中可用。在我的第一个 Activity 中,我初始化全局类 patent
,并使用 setPatientName
设置变量。在下一个 Activity 中,我调用“getPatientName”,但它返回 null
。当我尝试设置“getPatientName”的结果时,它给出了错误
java.lang.NullPointerException:尝试在空对象引用上调用虚拟方法“void android.widget.TextView.setText(java.lang.CharSequence)”
编辑:我的第一个 Activity 是从文本字段收集姓名,这就是我试图setPatientName
作为
第一个 Activity :
tv2=(TextView)findViewById(R.id.textView2);
EditText name = (EditText) findViewById(R.id.textView2);
String nameString = name.getText().toString();
final Patient p = (Patient) getApplicationContext();
p.setPatientName(nameString);
第二个 Activity :
Patient p = (Patient)getApplication();
String patName = p.getPatientName();
tv2.setText(patName);
患者类别:
package com.example.imac.chs_pharmacy;
import android.app.Application;
import android.os.Parcel;
import android.os.Parcelable;
import android.util.Log;
public class Patient extends Application {
//private variables
public String patient_name;
//default constructor
public Patient(){
}
public Patient(String startPatientName) {
this.patient_name = startPatientName;
}
public void setPatientName( String patientName ){
Log.d(TAG, "setting patient name");
this.patient_name = patientName;
}
public String getPatientName( ){
Log.d(TAG, "getting patient name");
return this.patient_name;
}
list .xml:
<application android:name="com.example.imac.chs_pharmacy.Patient"
还值得注意的是,在我的 Patient
类中,我在 getPatientName
和 setPatientName
中注销了一个字符串,但它只是似乎正在登录 setPatientName
。我的 setPatientName
是否因某种原因没有被解雇?
最佳答案
无需扩展应用程序
。尝试如下
public class Patient {
private static Patient patientInstance;
private String patient_name;
//private contrunctor to prevent from creating patient instance directly through constructor.
private Patient() {
}
public static Patient getInstance() {
if (patientInstance == null) {
patientInstance = new Patient();
}
return patientInstance;
}
public void setPatientName( String patientName ){
this.patient_name = patientName;
}
public String getPatientName( ){
return this.patient_name;
}
}
然后使用下面的类
Patient p = Patient.getInstance();
String patName = p.getPatientName();
TextView tv2 = (TextView) findViewById(R.id.your_text_view_id);
tv2.setText(patName);
关于java - 全局类/变量不由 setter 保存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41877018/