for循环直到在Android中按下按钮?

时间:2015-12-04 16:16:23

标签: android csv

我是Android新手。如何在按下按钮之前运行此For循环?我正在将保存的数据数据写入CSV文件并将其存储到SD卡上。我想保持循环运行,直到我按writeFileBtn并将数据保存为CSV。

import com.opencsv.CSVWriter;

public class MainActivity extends Activity {

    Button getTimeBtn, writeFileBtn;
    ArrayList<String> entries;

    String[] entriesArr;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        entries = new ArrayList<String>();

        getTimeBtn = (Button) findViewById(R.id.get_time);

        writeFileBtn = (Button) findViewById(R.id.write_file);

        getTimeBtn.setOnClickListener(new View.OnClickListener() {

            public void onClick(View v) {

                for (int i = 0; i <= 10; i++) {
                    entries.add(String.valueOf(System.nanoTime()));

                    entriesArr = entries.toArray(new String[entries.size()]);
                }
            }
        });

        writeFileBtn.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {

                CSVWriter writer = null;
                try 
                {
                    writer = new CSVWriter(new FileWriter(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM) + "myfile.csv"), ',');
                    //String[] entries = "first#second#third".split("#"); // array of your values
                    writer.writeNext(entriesArr);  
                    writer.close();
                } 
                catch (IOException e)
                {
                    Toast.makeText(MainActivity.this, "Error",
                            Toast.LENGTH_LONG).show();
                }
            }
        });
    }
}

1 个答案:

答案 0 :(得分:1)

您应该使用AsyncTask在后台执行此操作。

private class DownloadFilesTask extends AsyncTask<URL, Integer, Long> {
 protected Long doInBackground(URL... urls) {
     int count = urls.length;
     long totalSize = 0;
     for (int i = 0; i < count; i++) {
         totalSize += Downloader.downloadFile(urls[i]);
         publishProgress((int) ((i / (float) count) * 100));
         // Escape early if cancel() is called
         if (isCancelled()) break;
     }
     return totalSize;
 }

 protected void onProgressUpdate(Integer... progress) {
     setProgressPercent(progress[0]);
 }

 protected void onPostExecute(Long result) {
     showDialog("Downloaded " + result + " bytes");
 }

}

AsynkTask为您提供了一个可以被按钮使用的isCancelled()。