从(MainActivity.java)中的按钮调用另一个类中的方法

时间:2016-12-23 02:55:30

标签: android

从MainActivity单击按钮后,我的代码应该写一个文件。 为什么我在模拟器上运行时点击按钮时收到消息“不幸的是我的应用程序已经停止”,我得到了一个空白。(Android Studio 2.2.3) 感谢您的任何见解。

        public class MainActivity extends AppCompatActivity {

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            Button button;
            button = (Button) findViewById(R.id.button);

            button.setOnClickListener(new OnClickListener() {
                public void onClick(View arg0) {
                    Class2 Class2_ref = new Class2();
                    Class2_ref.method();

                }
            });
        }
    }


//Class2
import android.app.Activity;
import android.content.Context;
import android.util.Log;
import java.io.IOException;
import java.io.OutputStreamWriter;

public class Class2 extends Activity{
    private static final String TAG = Class2.class.getName();
    private static final String FILENAME = "myFile.txt";

    public void method(){
        String textToSaveString = "Hello World";
        writeToFile(FILENAME, textToSaveString);
    }

    public void writeToFile(String filename, String data) {
        try {
            OutputStreamWriter outputStreamWriter = new OutputStreamWriter(openFileOutput(filename, Context.MODE_PRIVATE));
            outputStreamWriter.write(data);
            outputStreamWriter.close();
        }
        catch (IOException e) {
            Log.e(TAG, "File write failed: " + e.toString());
        }
    }
}

2 个答案:

答案 0 :(得分:0)

您的openFileOutput方法是什么,您必须提供outputStreamWriter的完整路径,请写下您的错误跟踪。

答案 1 :(得分:0)

public class Class2{

    private static final String TAG = Class2.class.getName();
    private static final String FILENAME = "myFile.txt";
    public void method(){
        String textToSaveString = "Hello World";
        writeToFile(FILENAME, textToSaveString);
    }

    public void writeToFile(String filename, String data) {

        File f = new File(Environment.getExternalStorageDirectory() + "/" + filename);
        if (f.exists()) {
            f.delete();
        }
        try {
            f.createNewFile();
        } catch (IOException e) {
            e.printStackTrace();
        }
        BufferedWriter bw = null;
        try {
            bw = new BufferedWriter(new FileWriter(f));
        } catch (IOException e) {
            e.printStackTrace();
        }

        try {
            bw.write("CONTENT HERE");
        } catch (IOException e) {
            e.printStackTrace();
        }

        try {
            if (bw != null)
            bw.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

试试这个希望它有所帮助!