我有一个工人阶级,但现在我想要清理它,因为我需要重用代码的某些部分。 我有一个问题将字符串从一个类传递回另一个类,现在它给了我一个NullPointerException
在TextFileManager.readTheText(TextFileManager.java:55) 在ActivityOne.clickNext(ActivityOne.java:69)
以下是我的两个课程:
import android.content.Context;
import java.io.BufferedReader;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
public class TextFileManager extends MainActivity {
String fileName = "surveyFile2014.txt";
//Write the file
public void writeTextFile(String data){
try {
FileOutputStream fos = openFileOutput(fileName, Context.MODE_PRIVATE);
fos.write(data.getBytes());
fos.close();
} catch (Exception e) {
e.printStackTrace();
}
}
//Read the file
public String readTheText(){
try {
BufferedReader inputReader = new BufferedReader(new InputStreamReader(openFileInput(fileName)));
String inputString;
StringBuffer stringBuffer = new StringBuffer();
while ((inputString = inputReader.readLine()) != null) {
stringBuffer.append(inputString + "\n");
}
return stringBuffer.toString();
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
}

使用它的Activity:
public class ActivityOne extends ActionBarActivity {
RadioGroup radiogroup;
RadioButton male, female;
TextView display;
TextFileManager fileManagement;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.one);
fileManagement = new TextFileManager();
//Connect all the radioButtons
male = (RadioButton) findViewById(R.id.radioMale);
female = (RadioButton) findViewById(R.id.radioFemale);
//Connect the textview to display
display = (TextView) findViewById(R.id.Text_YourGender);
//Work with the radioGroup
radiogroup = (RadioGroup) findViewById(R.id.radioGroupGender);
radiogroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
if (checkedId == R.id.radioMale) {
Toast.makeText(getBaseContext(), "Male", Toast.LENGTH_LONG).show();
} else if (checkedId == R.id.radioFemale) {
Toast.makeText(getBaseContext(), "Female", Toast.LENGTH_LONG).show();
}
}
});
}
/**Update the text*/
public void clickNext(View view){
int selectedId = radiogroup.getCheckedRadioButtonId();
//Find which radioButton is checked by id
if (selectedId == male.getId()){
//Update the file, add one
fileManagement.writeTextFile("Male");
display.setText(fileManagement.readTheText()); //It crashes here
}else if(selectedId == female.getId()){
//Update the file, add one
//findString( readTheText("surveyFile2014.txt"), "Male");
fileManagement.writeTextFile("Female");
display.setText(fileManagement.readTheText());
}
}
}

我有什么遗漏的吗? 谢谢