OSDN Git Service

xml形式のデータインポート時にお知らせ表示することにした。
[gokigen/MeMoMa.git] / app / src / main / java / jp / sourceforge / gokigen / memoma / io / MeMoMaFileImportCsvProcess.java
1 package jp.sourceforge.gokigen.memoma.io;
2
3 import java.io.BufferedReader;
4 import java.io.FileReader;
5
6 import android.app.ProgressDialog;
7 import android.content.Context;
8 import android.content.SharedPreferences;
9 import android.os.AsyncTask;
10 import android.preference.PreferenceManager;
11 import android.util.Log;
12
13 import jp.sourceforge.gokigen.memoma.R;
14 import jp.sourceforge.gokigen.memoma.holders.MeMoMaObjectHolder;
15 import jp.sourceforge.gokigen.memoma.holders.PositionObject;
16
17 /**
18  *  データをファイルに保存するとき用 アクセスラッパ (非同期処理を実行)
19  */
20 public class MeMoMaFileImportCsvProcess extends AsyncTask<MeMoMaObjectHolder, Integer, String> implements MeMoMaFileSavingProcess.ISavingStatusHolder, MeMoMaFileSavingProcess.IResultReceiver
21 {
22     private final String TAG = toString();
23         private final Context context;
24         private IResultReceiver receiver = null;
25
26         private String targetFileName = null;
27     private String fileSavedResult = "";
28         private ProgressDialog importingDialog = null;
29
30         private String backgroundUri = null;
31         private String userCheckboxString = null;
32         
33         /**
34          *   コンストラクタ
35          */
36     public MeMoMaFileImportCsvProcess(Context context, IResultReceiver resultReceiver, String fileName)
37     {
38         this.context = context;
39         receiver = resultReceiver;
40         targetFileName = fileName;
41
42         //  プログレスダイアログ(「データインポート中...」)を表示する。
43         importingDialog = new ProgressDialog(context);
44         importingDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
45         importingDialog.setMessage(context.getString(R.string.dataImporting));
46         importingDialog.setIndeterminate(true);
47         importingDialog.setCancelable(false);
48         importingDialog.show();
49
50         //  設定読み出し用...あらかじめ、UIスレッドで読みだしておく。         
51         SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
52         backgroundUri = preferences.getString("backgroundUri","");
53         userCheckboxString = preferences.getString("userCheckboxString","");
54     }
55         
56     /**
57      *  非同期処理実施前の前処理
58      */
59     @Override
60     protected void onPreExecute()
61     {
62     }
63
64     /**
65      *    1レコード分のデータを読み込む。
66      */
67     private String readRecord(BufferedReader buf )
68     {
69         String oneRecord = null;
70         try
71         {
72                 String oneLine = buf.readLine();
73             while (oneLine != null)
74             {
75                 oneRecord = (oneRecord == null) ? oneLine : oneRecord + oneLine;
76                 if (oneRecord.indexOf(",;!<_$") > 0)
77                 {
78                         // レコード末尾が見つかったので break する。
79                         break;
80                 }
81                 // 次の行を読みだす。
82                 oneLine = buf.readLine();
83             }
84         }
85         catch (Exception ex)
86         {
87             //
88                 Log.v(TAG, "CSV:readRecord() ex : " + ex.toString());
89                 oneRecord = null;
90         }
91         return (oneRecord);
92     }
93
94     /**
95      *   1レコード分のデータを区切る
96      */
97     private void parseRecord(String dataLine,  MeMoMaObjectHolder objectHolder)
98     {
99         int detailIndex = 0;
100         int userCheckIndexTrue = 0;
101         int userCheckIndexFalse = 0;
102         int nextIndex = 0;
103         String label = "";
104         String detail = "";
105         boolean userChecked = false;
106         try
107         {
108             detailIndex = dataLine.indexOf("\",\"");
109             if (detailIndex < 0)
110             {
111                 Log.v(TAG, "parseRecord() : label wrong : " + dataLine);
112                 return;
113             }
114             label = dataLine.substring(1, detailIndex);
115             userCheckIndexTrue = dataLine.indexOf("\",True,", detailIndex);
116             userCheckIndexFalse = dataLine.indexOf("\",False,", detailIndex);
117             if (userCheckIndexFalse > detailIndex)
118             {
119                 //
120                 detail = dataLine.substring(detailIndex + 3, userCheckIndexFalse);
121                 userChecked = false;
122                 nextIndex = userCheckIndexFalse + 8; // 8は、 ",False, を足した数
123             }
124             else if (userCheckIndexTrue > detailIndex)
125             {
126                 //
127                 detail = dataLine.substring(detailIndex + 3, userCheckIndexTrue);
128                 userChecked = true;
129                 nextIndex = userCheckIndexTrue + 7; // 7は、 ",True,  を足した数
130             }
131             else // if ((userCheckIndexTrue <= detailIndex)&&(userCheckIndexFalse <= detailIndex))
132             {
133                 Log.v(TAG, "parseRecord() : detail wrong : " + dataLine);
134                 return;                 
135             }
136             
137             //  残りのデータを切り出す。
138             String[] datas = (dataLine.substring(nextIndex)).split(",");
139             if (datas.length < 6)
140             {
141                 Log.v(TAG, "parseRecord() : data size wrong : " + datas.length);
142                 return;
143             }
144             int drawStyle = Integer.parseInt(datas[0]);
145             String paintStyle = datas[1];
146             float centerX = Float.parseFloat(datas[2]);
147             float centerY = Float.parseFloat(datas[3]);
148             float width = Float.parseFloat(datas[4]);
149             float height = Float.parseFloat(datas[5]);
150
151             float left = centerX - (width / 2.0f);
152             float top = centerY - (height / 2.0f);
153
154             // オブジェクトのデータを作成する
155             PositionObject pos = objectHolder.createPosition(left, top, drawStyle);
156             if (pos == null)
157             {
158                 Log.v(TAG, "parseRecord() : object create failure.");
159                 return;                 
160             }
161             pos.setRectRight(left + width);
162             pos.setRectBottom(top + height);
163             pos.setLabel(label);
164             pos.setDetail(detail);
165             pos.setPaintStyle(paintStyle);
166             pos.setUserChecked(userChecked);
167             Log.v(TAG, "OBJECT CREATED: " + label + "(" + left + "," + top + ") [" +drawStyle + "]");
168         }
169         catch (Exception ex)
170         {
171                 Log.v(TAG, "parseRecord() " + ex.toString());
172         }
173         
174     }
175
176     
177     /**
178      *    (CSV形式の)データを読み込んで格納する。
179      */
180     private String importFromCsvFile(String fileName, MeMoMaObjectHolder objectHolder)
181     {
182         String resultMessage = "";
183         try
184         {
185             Log.v(TAG, "CSV(import)>> " + fileName);
186                 BufferedReader buf = new BufferedReader(new FileReader(fileName));
187             String dataLine = readRecord(buf);
188             while (dataLine != null)
189             {
190                         if (!dataLine.startsWith(";"))
191                         {
192                                 // データ行だった。ログに出力する!
193                     parseRecord(dataLine, objectHolder);
194                         }
195                 // 次のデータ行を読み出す
196                         dataLine = readRecord(buf);
197             }
198         }
199         catch (Exception e)
200         {
201                 resultMessage = " ERR(import) " + e.getMessage();
202             Log.v(TAG, resultMessage);
203             e.printStackTrace();
204         } 
205         return (resultMessage);
206     }
207
208     /**
209      *  非同期処理
210      *  (バックグラウンドで実行する(このメソッドは、UIスレッドと別のところで実行する))
211      * 
212      */
213     @Override
214     protected String doInBackground(MeMoMaObjectHolder... datas)
215     {
216         // ファイル名の設定 ... (拡張子なし)
217         String fileName = context.getFilesDir() + "/exported/" + targetFileName;
218
219         // データを読み込む
220         String result = importFromCsvFile(fileName, datas[0]);
221
222         // データを保存する
223         MeMoMaFileSavingEngine savingEngine = new MeMoMaFileSavingEngine(context, backgroundUri, userCheckboxString);
224         String message = savingEngine.saveObjects(datas[0]);
225
226         System.gc();
227
228         return (result + " " + message);
229     }
230
231     /**
232      *  非同期処理の進捗状況の更新
233      */
234         @Override
235         protected void onProgressUpdate(Integer... values)
236         {
237         // 今回は何もしない
238         }
239
240     /**
241      *  非同期処理の後処理
242      *  (結果を応答する)
243      */
244     @Override
245     protected void onPostExecute(String result)
246     {
247         try
248         {
249             if (receiver != null)
250             {
251                 receiver.onImportedResult(result + "  " + fileSavedResult);
252             }
253             fileSavedResult = "";
254         }
255         catch (Exception ex)
256         {
257                 Log.v(TAG, "MeMoMaFileImportCsvProcess::onPostExecute() : " + ex.getMessage());
258         }
259         // プログレスダイアログを消す
260         importingDialog.dismiss();
261
262         return;
263     }
264     
265     public void onSavedResult(boolean isError, String detail)
266     {
267         fileSavedResult = detail;
268     }
269
270     public void setSavingStatus(boolean isSaving)
271     {
272         
273     }
274
275     public boolean getSavingStatus()
276     {
277         return (false);
278     }
279
280     /**
281      *    結果報告用のインタフェース(積極的に使う予定はないけど...)
282      */
283     public interface IResultReceiver
284     {
285         /**  保存結果の報告 **/
286         void onImportedResult(String fileName);
287     }
288 }