android问题:保存文件后文件内容为空

package com.example.hellotest;


import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.OutputStream;


import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;


public class SaveFileActivity extends Activity{
private Button saveFileBtn;
private EditText message;
private OutputStream output;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_savefile);

message =(EditText) findViewById(R.id.file_content);
final String msg=message.getText().toString();
//saveFile(msg);//保存文件

saveFileBtn = (Button)findViewById(R.id.file_button);
saveFileBtn.setOnClickListener(new View.OnClickListener(){

@Override
public void onClick(View v) {
try {
output = SaveFileActivity.this.openFileOutput("saveFile.txt", MODE_PRIVATE);
output.write(msg.getBytes());
output.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally{
Toast.makeText(getApplicationContext(), "保存成功", Toast.LENGTH_LONG).show();
message.setText("");
}
}
});
}

}


--以上代码保存文件后文件为空

--原因:监听事件中msg获取不到控件的信息

--解决方法:监听事件中获取msg信息,代码如下:

package com.example.hellotest;


import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.OutputStream;


import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;


public class SaveFileActivity extends Activity{
private Button saveFileBtn;
private EditText message;
private OutputStream output;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_savefile);

message =(EditText) findViewById(R.id.file_content);

saveFileBtn = (Button)findViewById(R.id.file_button);
saveFileBtn.setOnClickListener(new View.OnClickListener(){

@Override
public void onClick(View v) {
try {
final String msg=message.getText().toString();
output = SaveFileActivity.this.openFileOutput("saveFile.txt", MODE_PRIVATE);
output.write(msg.getBytes());
output.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally{
Toast.makeText(getApplicationContext(), "保存成功", Toast.LENGTH_LONG).show();
message.setText("");
}
}
});
}
}


你可能感兴趣的:(android)