将数据从多个输入保存到文件

时间:2013-06-20 08:41:04

标签: java android file android-edittext save

我正在开发一个Android应用程序,用户必须在多个“edittext”框中输入文本,然后我尝试将输入的数据保存到文本文件中。我有我的应用程序来保存前几个框中的数据。我尝试了很多方法,比如使用for循环和其他方法,但它仍然不起作用。我目前正在使用数组列表,将前几位数据添加到列表中,将其写入文本文件,清除列表,然后添加其余数据并尝试将其附加到文件中。 在调试中,应用程序可以添加新数据的第一位并停止,而不会崩溃或出现任何错误。

这是我的代码:

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.StrictMode;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends Activity implements OnClickListener{

    private Button submitForm,resetForm,btnEmail;
    private String saveName;
    private EditText name,depot,date,time,location,details,outcome,did;
    private String attachedPathFile;
    private File folder;
    File myFile;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //StrictMode.enableDefaults();
        name = (EditText)findViewById(R.id.nameText);
        depot = (EditText)findViewById(R.id.DepotText);
        date = (EditText)findViewById(R.id.DateText);
        time = (EditText)findViewById(R.id.LocationText);
        details = (EditText)findViewById(R.id.IncidentText);
        outcome = (EditText)findViewById(R.id.OutcomeText);
        did = (EditText)findViewById(R.id.DetailsText);

        submitForm = (Button)findViewById(R.id.SubmitButton);
        submitForm.setOnClickListener(new OnClickListener(){

            @SuppressLint("SimpleDateFormat")
            public void onClick(View v) {
                // write on SD card file data in the text box
                try {
                    folder = new File(Environment.getExternalStorageDirectory(),"Close Call Reports");
                    folder.mkdirs();
                    saveName = new SimpleDateFormat("yyyy-MM-dd HH mm ss").format(new Date());
                    myFile = new File(Environment.getExternalStorageDirectory().toString()+"/Close Call Reports/"+saveName+".txt");
                    myFile.createNewFile();
//                  FileOutputStream fOut = new FileOutputStream(myFile, true);
//                  OutputStreamWriter myOutWriter = new OutputStreamWriter(fOut);
//                                      
//                  //gets text data to write to file
//                  String data = "Your Name: "+name.getText().toString()+"\n"+"Your Depot: "+depot.getText().toString()+"\n"+"Date: "+
//                  date.getText().toString()+"\n"+"Time: "+time.getText().toString()+"\n";

//                  String data2 ="Location: "+location.getText().toString()+
//                          "\n"+ "Incident: "+details.getText().toString()+"\n"+"Potential Outcome: "+outcome.getText().toString()+"\n"+
//                  "What did you do ? "+did.getText().toString();


                    List<String> data = new ArrayList<String>();
                    data.add("Your Name: "+name.getText().toString());
                    data.add("Your Depot: "+depot.getText().toString());
                    data.add("Date: "+date.getText().toString());
                    data.add("Time: "+time.getText().toString());

                    appendToFile(data);

                    data.clear();

                    Log.v("DEBUGGING", "got here 1");

                    //data = new ArrayList<String>();
                    data.add("Location: "+location.getText().toString());
                    data.add("Incident: "+details.getText().toString());
                    data.add("Potential Outcome: "+outcome.getText().toString());
                    data.add("What did you do ? "+did.getText().toString());

                    Log.v("DEBUGGING", "got here 2");

                    appendToFile(data);

                    Log.v("DEBUGGING", "got here 3");

//                  myOutWriter.append(data);
//                  myOutWriter.close();
//                  fOut.close();
//                  Toast.makeText(getBaseContext(),
//                          "Done writing Comment File",
//                          Toast.LENGTH_SHORT).show();
                    name.setText("");
                    depot.setText("");
                    date.setText("");
                    time.setText("");
                    location.setText("");
                    details.setText("");
                    outcome.setText("");
                    did.setText("");
                } catch (Exception e) {
                    Toast.makeText(getBaseContext(), e.getMessage(),
                            Toast.LENGTH_SHORT).show();
                }
                // write on SD card file data in the text box

            }// onClick
            }); // btnWriteSDFile

        btnEmail = (Button)findViewById(R.id.Emailbtn);
        btnEmail.setOnClickListener(new OnClickListener(){

            @Override
            public void onClick(View arg0) {
                String[] emailTo = new String[]{"ameyandroidapp@gmail.com"};
                String subject = "Close Call Reporting";
                String [] filePaths= new String[1];
                //if(filePaths[0]==null){
                for(int a=0; a < filePaths.length;a++){
                    attachedPathFile = Environment.getExternalStorageDirectory().toString()+"/Close Call Reports/"+saveName+".csv";
                            //path+ls+saveName+"("+a+")"+".txt";
                    filePaths[a] = attachedPathFile;
                }
                    sendEmail(emailTo,subject,filePaths);
            //  }else{
                //  Toast.makeText(getBaseContext(),"No Files To Email",Toast.LENGTH_LONG).show();
                //}
            }   

        });


        resetForm = (Button)findViewById(R.id.ResetButton);
        resetForm.setOnClickListener(new OnClickListener(){

            @Override
            public void onClick(View arg0) {
                name.setText("");
                depot.setText("");
                date.setText("");
                time.setText("");
                location.setText("");
                details.setText("");
                outcome.setText("");
                did.setText("");
            }

        });     
}

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

      public void sendEmail(String[] emailTo, String subject,
                String[] filePaths) {

            Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND_MULTIPLE);
            emailIntent.setData(Uri.parse("mailto: "));
            emailIntent.putExtra(Intent.EXTRA_EMAIL, emailTo);
            emailIntent.putExtra(Intent.EXTRA_SUBJECT, subject);
            emailIntent.setType("message/rfc822");

            ArrayList<Uri> uris = new ArrayList<Uri>();
            for(String file: filePaths){
                File fileIn = new File(file);
                Uri u = Uri.fromFile(fileIn);
                uris.add(u);
            }
            //emailIntent.putParcelableArrayListExtra(Intent.EXTRA_STREAM,uris);
            emailIntent.putExtra(android.content.Intent.EXTRA_STREAM, uris);
            startActivity(Intent.createChooser(emailIntent, "Email"));  
        }

    @Override
    public void onClick(View v) {
    }

    public void appendToFile (List<String> SarrayList) {

          BufferedWriter bw = null;
          boolean myappend = true;
          try {
             bw = new BufferedWriter(new FileWriter(myFile, myappend));
             for(String line: SarrayList ) {
             bw.write(line);
             bw.newLine();
             }
             bw.flush();
          } catch (IOException ioe) {
            ioe.printStackTrace();
          } finally { 
            if (bw != null) try {
            bw.close();
            } catch (IOException ioe2) {
            // ignore it  or write notice
            }
          }

       } 

}

1 个答案:

答案 0 :(得分:1)

我很惊讶你没有看到它崩溃,因为我觉得你应该得到一个NullPointerException,因为你似乎没有设置{的价值{1}}。此外,您使用ID为R.id.LocationText的视图设置location的值时看起来不对:

time

但如果不知道自己到底做了什么,就很难确定。