Android in Eclipse - Invoke File Writer class in B

2019-08-05 06:53发布

问题:

When I click the button (btnPrintTardy) I need to generate a .txt file of whatever i have entered into a txtbox (editText1).

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();
                };
}

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?

I have tried

 public void UpdateStudenttxtfile(View View)
    {

    Intent intent = new Intent(View.getContext(), FileWriter.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    }

with no luck :(

回答1:

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

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]
  }
}

Here's another answer about AsyncTask: Where do I extend the AsyncTask?