0
我在一個類中定義的兩個子類LoadData()和保存數據()在內部存儲加載和保存數據:從內部存儲在一個類ANDROID定義的數據
public class LoadSaveInternalActivity extends Activity {
public String LoadData(String filename)
{ String read = "";
try {
FileInputStream fis = getBaseContext().openFileInput(filename);
if (fis != null) {
BufferedReader br = new BufferedReader(new InputStreamReader(fis));
read = br.readLine();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return read;
}
public void SaveData(String data, String filename)
{
try {
FileOutputStream outputStream = getBaseContext().openFileOutput(filename, Context.MODE_PRIVATE);
String text = data;
outputStream.write(text.getBytes());
outputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
}}
,我試圖從另一個活動中調用這些類的方法,如:
public class Fragment1 extends Fragment {
EditText edittxt;
private final static String file_name = "myfile";
private LoadSaveInternalActivity InternalActivity;@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.frag1, container,false);
edittxt = (EditText) rootView.findViewById(R.id.editTxt);
InternalActivity = new LoadSaveInternalActivity();
String readData = InternalActivity.LoadData(file_name);
edittxt.setText(readData);
return rootView;
}
@Override
public void onStop() {
super.onStop();
InternalActivity = new LoadSaveInternalActivity();
InternalActivity.SaveData(edittxt.getText().toString(),file_name);
}
但它不起作用。在這種情況下有人能幫助我嗎?
其實我需要在另一個類中定義它們,而不是在片段本身中。因爲我需要從其他類訪問它們。當我在片段中定義它們時,一切都很好。 – srt
@srt:然後在某處定義它們的'static'方法,在這裏它們以'Context'作爲參數。在原始代碼中使用'Context'而不是'getBaseContext()'。在片段中使用'getActivity()'來獲得一個'Context'傳遞給方法。 – CommonsWare
在某個地方,你的意思是在一個新班級?像這樣: staticData(Context c,String filename) – srt