0

我正在尝试将 EditText 字段中的数据写入文本文件。我已验证数据正在被捕获以在单击“添加”按钮后填充的 EditText 字段中输出。程序在模拟器中成功运行,但没有创建输出文件。我已将 uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" 添加到 Android Manifest xml 文件中。LogCat 和控制台不显示任何错误。在这里研究示例后,我尝试了几种不同的方法,但没有运气。谁能指出我的问题?在此先感谢您的帮助。

package john.BRprogram;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.EditText;
//import android.graphics.Color;
import java.io.OutputStreamWriter;
import java.util.Scanner;
import java.util.List;
import java.util.ArrayList;

public class BRprogramActivity extends Activity implements OnItemSelectedListener {
  private static final String TAG = null;
//
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
 //
    Button addButton;
    Button editButton;
    Button sendButton;
//  
    Spinner array_spinner;
//      
//      activate soft Keyboard
    this.getWindow().setSoftInputMode
      (WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE); 
//
    EditText myCustomer = (EditText)findViewById(R.id.editText1);
    myCustomer.setText("");   
//
    EditText myQuantity = (EditText)findViewById(R.id.editText2);
    myQuantity.setText("");
//      
    EditText myPrice = (EditText)findViewById(R.id.editText3);
    myPrice.setText("");
//    
//      .csv comma separated values file
//        
    try {
        Scanner scanner = new Scanner(getResources().openRawResource(R.raw.brdata));  
//         
        List<String> list = new ArrayList<String>(); 
        while (scanner.hasNext()) {
        String data = (scanner.next());                  //read data record
        String [] values = data.split(",");           //parse data to fields
//      String [] values = data.split(",(?=([^\"]\"[^\"]\")[^\"]$)");
        if(values.length != 3)     
            Log.v("Example", "Malformed row: " + data); 
            else  
            list.add(values[0] + " " + values[1] + " $" + values[2]);
}
//          
        array_spinner = (Spinner)findViewById(R.id.spinner1);         
        ArrayAdapter<String> adapter = new ArrayAdapter<String>
        (this,android.R.layout.simple_spinner_item, list);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); 
        array_spinner.setAdapter(adapter); 
        array_spinner.setOnItemSelectedListener((OnItemSelectedListener) this);
//           
        scanner.close();
//    
}   catch (Exception e) {
        Log.e(TAG, "Exception: "+Log.getStackTraceString(e));
}
//
    addButton = (Button) findViewById(R.id.addbutton);
    addButton.setOnClickListener(new OnClickListener(){
        public void onClick(View v){
//    
// get customer number,itemnumber,quantity,price
//
    String writeCustomer = ((EditText) findViewById(R.id.editText1)).getText().toString().trim();
//  itemNumber from list selection
    String writeQuantity = ((EditText) findViewById(R.id.editText2)).getText().toString().trim();
    String writePrice = ((EditText) findViewById(R.id.editText3)).getText().toString().trim();
//
    String newRecord = writeCustomer + "," + writeQuantity + "," + writePrice; 

    EditText myString = (EditText)findViewById(R.id.editText4);
    myString.setText(newRecord);        
//          
// write seq to output file             
//              
    try {
        OutputStreamWriter out = new OutputStreamWriter(openFileOutput("broutput.txt",0));
        out.write(newRecord);   
        out.close(); 
    }catch (Exception e){
      Log.v("test", "record written");
}                       

//
            EditText myQuantity = (EditText)findViewById(R.id.editText2);
            myQuantity.setText("");
//      
            EditText myPrice = (EditText)findViewById(R.id.editText3);
            myPrice.setText("");
            Log.v("test", "ADD button clicked");
}
});
//
    editButton = (Button) findViewById(R.id.editbutton);
    editButton.setOnClickListener(new OnClickListener(){
        public void onClick(View v){
            Log.v("test", "EDIT button clicked");
}
});    
//
    sendButton = (Button) findViewById(R.id.sendbutton);
    sendButton.setOnClickListener(new OnClickListener(){
        public void onClick(View v){
//
            EditText myCustomer = (EditText)findViewById(R.id.editText1);
            myCustomer.setText("");
//
            EditText myQuantity = (EditText)findViewById(R.id.editText2);
            myQuantity.setText("");
//      
            EditText myPrice = (EditText)findViewById(R.id.editText3);
            myPrice.setText("");
            Log.v("test", "SEND button clicked");
}
});

}
//  ***  http://www.youtube.com/watch?v=Pfasw0bbe_4  ***
//
    public void onItemSelected(AdapterView<?> parent, View view, int position,
            long id) {
//  
    String selection = parent.getItemAtPosition(position).toString();
    String [] priceField = selection.split("\\$");       //parse price field
    String [] item = selection.split("_");         //parse item number 
    String itemNumber = item[0];   
//
    EditText myQuantity = (EditText)findViewById(R.id.editText2);
    myQuantity.setText("");
//      
    EditText myPrice = (EditText)findViewById(R.id.editText3);
    myPrice.setText(priceField[1]);
}
//
   public void onNothingSelected(AdapterView<?> arg0) {
//nothing here      
}
}
4

2 回答 2

0

我实际上遇到过这样的问题;一切似乎都很好,但我的代码不起作用。我的问题是我正在编写的文件名中的字符。例如,我尝试编写文件名my_file - date 07/11/2012. 这会导致问题,因为它将每个都/视为开始新目录的提示!出于这个原因,我发现我的文件名中不能有任何/(或者:,由于某种原因)。这会是你的问题吗?

如果这是您的问题,那么您可以做我所做的:执行 a将文件名中的newRecord.replace('/', '-');所有内容替换为 a (如果您可以使用's 代替)。/--

附带说明一下,为什么要在 try/catch 语句的 catch 中记录“记录写入”?如果它发现了一个问题,那不就意味着它没有被写出来吗?

于 2012-07-11T17:43:42.987 回答
0

看起来您需要创建和/或指定要保存文件的目录。我在您的代码中的任何地方都没有看到。它可能看起来像这样:

if (Environment.getExternalStorageState() == null) {
            directory = new File(Environment.getDataDirectory()
                    + "/RobotiumTestLog/");
            photoDirectory = new File(Environment.getDataDirectory()
                    + "/Robotium-Screenshots/");
            /*
             * this checks to see if there are any previous test photo files
             * if there are any photos, they are deleted for the sake of
             * memory
             */
            if (photoDirectory.exists()) {
                File[] dirFiles = photoDirectory.listFiles();
                if (dirFiles.length != 0) {
                    for (int ii = 0; ii <= dirFiles.length; ii++) {
                        dirFiles[ii].delete();
                    }
                }
            }
            // if no directory exists, create new directory
            if (!directory.exists()) {
                directory.mkdir();
            }

            // if phone DOES have sd card
        } else if (Environment.getExternalStorageState() != null) {
            // search for directory on SD card
            directory = new File(Environment.getExternalStorageDirectory()
                    + "/RobotiumTestLog/");
            photoDirectory = new File(
                    Environment.getExternalStorageDirectory()
                            + "/Robotium-Screenshots/");
            if (photoDirectory.exists()) {
                File[] dirFiles = photoDirectory.listFiles();
                if (dirFiles.length > 0) {
                    for (int ii = 0; ii < dirFiles.length; ii++) {
                        dirFiles[ii].delete();
                    }
                    dirFiles = null;
                }
            }
            // if no directory exists, create new directory to store test
            // results
            if (!directory.exists()) {
                directory.mkdir();
            }
        }

当您从您的应用程序中保存数据时,您必须记住它是在 Android 上运行的,而不是您的计算机上,因此所有数据都将写入您的 Android,而不是您的计算机。您必须在写入数据后拉取数据才能查看它。确保您在设备上创建了一个本地目录,并确保您检查了 SD 卡。我列出的代码将向您展示如何做您需要的一切。

希望这可以帮助!

于 2012-07-11T19:51:43.850 回答