Android在Eclipse中 - 调用后台文件Writer类 [英] Android in Eclipse - Invoke File Writer class in Background
问题描述
当我按一下按钮(btnPrintTardy)我需要生成什么我已经进入了一个txtbox(editText1).txt文件
When I click the button (btnPrintTardy) I need to generate a .txt file of whatever i have entered into a txtbox (editText1).
这是我的文件写入Java类。
This is my File Writer java class.
import android.app.Activity;
import java.io.*;
import android.os.Bundle;
import android.view.*;
import android.widget.*;
public class FileWriter extends Activity {
EditText txtData;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
txtData = (EditText) findViewById(R.id.editText1);
}
public void onClick(View v) {
// write in data folder
try {
File myFile = new File("/data/LatePass/StudentLatePass.txt");
myFile.createNewFile();
FileOutputStream fOut = new FileOutputStream(myFile);
OutputStreamWriter myOutWriter =
new OutputStreamWriter(fOut);
myOutWriter.append(txtData.getText());
myOutWriter.close();
fOut.close();
Toast.makeText(getBaseContext(),
"Finished writing StudentLatePass.txt'",
Toast.LENGTH_SHORT).show();
} catch (Exception e) {
Toast.makeText(getBaseContext(), e.getMessage(),
Toast.LENGTH_SHORT).show();
}
finish();
};
}
我打电话从我的StudentActivity这种方法但是,这就是我有点卡住。我想留在我的当前屏幕活动,但在后台运行的FileWriter的。所以,我怎么会叫这个?
I am calling this method from my "StudentActivity" however, this is where i am kind of stuck. I want to stay on my current screen activity, but run the filewriter in the background. So how would I call this?
我曾尝试
public void UpdateStudenttxtfile(View View)
{
Intent intent = new Intent(View.getContext(), FileWriter.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
}
没有运气:(
推荐答案
我会建议使用的AsyncTask这个后台工作,而不是实施作为一个单独的活动:
http://developer.android.com/reference/android/os/AsyncTask.html
I would recommend using an AsyncTask for this background work instead of implementing as a separate activity: http://developer.android.com/reference/android/os/AsyncTask.html
然后,而不是发送一个Intent,您只要致电:
Then, instead of sending an Intent, you just call:
EditText txtData = (EditText) findViewById(R.id.editText1);
FileWriterTask task = new FileWriterTask();
task.execute(txtData.getText().toString());
public class FileWriterTask extends AsyncTask<String, Void, Void> {
@Override
protected Void doInBackground(String... params) {
// Do your filewriting here. The text should now be in params[0]
}
}
下面是关于AsyncTask的另一种答案:
<一href=\"http://stackoverflow.com/questions/9224476/where-do-i-extend-the-asynctask/9224574#9224574\">Where我做延长AsyncTask的?
Here's another answer about AsyncTask: Where do I extend the AsyncTask?
这篇关于Android在Eclipse中 - 调用后台文件Writer类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!