我正在尝试使用全局类使对象数据可通过我的所有活动使用。在我的第一个活动中,我将初始化全局类patient
,并将变量设置为setPatientName
。在我的下一个活动中,我将其称为“ getPatientName”,但它将返回null
。当我尝试设置“ getPatientName”的结果时,它给了我错误java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
编辑:我的第一个活动是从文本字段中收集名称,这就是我正在尝试setPatientName
作为
第一项活动:
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);
第二项活动:
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;
}
manifest.xml:
<application android:name="com.example.imac.chs_pharmacy.Patient"
还值得注意的是,在我的
Patient
类中,我在getPatientName
和setPatientName
中注销了一个字符串,但似乎只在setPatientName
上进行了登录。我的setPatientName
是否由于某种原因没有被解雇? 最佳答案
无需扩展Application
。尝试如下
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);