0

我从Android 开发者页面获取了这段代码,但代码不起作用。我环顾四周,但似乎没有人给出明确的答案。

private void writetofile(String FILENAME, String content){

    FileOutputStream outputStream;

    try {
        //The problem is here ↓
      outputStream = openFileOutput(FILENAME, Context.MODE_PRIVATE);
      outputStream.write(content.getBytes());
      outputStream.close();
    } catch (Exception e) {
      e.printStackTrace();
    }
}

“openFileOutput”显然是未定义的。我如何编写代码以使其写入文件并且不会编译失败?

这是我的完整代码(如果有帮助的话)

public class HastighetFragment extends Fragment {
int color;
Button bAdd;

private void writetofile(String FILENAME, String content){

    FileOutputStream outputStream;

    try {
      outputStream = openFileOutput(FILENAME, Context.MODE_PRIVATE);
      outputStream.write(content.getBytes());
      outputStream.close();
    } catch (Exception e) {
      e.printStackTrace();
    }
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {

    View rootView = inflater.inflate(R.layout.fragment_hastighet, container, false);
    bAdd = (Button) rootView.findViewById(R.id.addbutton);
    color=0;

    bAdd.setOnClickListener(new OnClickListener() {@Override
        public void onClick(View v) {
        switch(color){
        case 0:
            bAdd.setBackgroundResource(R.drawable.buttonstylered);
            color=1;
            break;
        case 1:
            bAdd.setBackgroundResource(R.drawable.buttonstylegreen);
            color=0;

            break;
        }
    }});

    return rootView;
}
public void onBackPressed() {
    android.app.FragmentManager FragmentManager = getActivity().getFragmentManager();
    FragmentManager.popBackStack();
}

}

4

1 回答 1

2

“openFileOutput”显然是未定义的。我如何编写代码以使其写入文件并且不会编译失败?

openFileOutput()是一个方法Context及其子类。

这是我的完整代码(如果有帮助的话)

在 aFragment中,您可以调用getActivity()以检索Activity承载Fragment. Activity继承自Context,因此您可以调用openFileOutput().Activity

于 2014-01-12T17:33:30.013 回答