テキスト ファイルをオブジェクトに変換し、それらの値を sqlite データベースに挿入する 3 つの個別のファイル解析関数があります。オブジェクトクラスを除いて、それらはすべて基本的に同じです。
プロセスは次のようになります。
- http を使用してファイルをダウンロードする
- 進捗計算のためにファイル内の行を数えます
- ターゲット テーブルの以前のレコードをすべて削除する
- BufferedReader でファイルを開く
- 一度に 2000 行を読み取り、オブジェクトに変換する
- トランザクションで sqlite に 2000 レコードを挿入する
- 完了するまでループ
このコードをジェネリックにして、任意のクラスをオブジェクトの作成に使用できるようにし、データの永続化に使用する DAL 関数を決定する方法がわかりません。Java は私の最初の言語ではないので、どんなガイダンスも素晴らしいものになるでしょう。
私が使用しているコードは次のとおりです。
public void downloadPendingPoleInspections() {
int count;
String filePath;
Inspections inspections = Inspections.getInstance();
filePath = Environment.getExternalStorageDirectory() + File.separator + "inspections.txt";
try {
downloadFile("http://localhost/api/inspectionservices.aspx?o=retrieve", "pendinginspections.txt", POST_PENDING_INSPECTIONS_PROGRESS_UPDATE);
int totalInspections = getLineCount(filePath);
inspections.deleteAllPendingInspections();
File file = new File(filePath);
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
int i = 0;
int j = 0;
List<PendingInspection> batch = new ArrayList<PendingInspection>();
while ((line = br.readLine()) != null) {
String[] values = line.split(" ");
PendingInspection pending = new PendingInspection(
Integer.parseInt(values[0]), values[1],
Double.parseDouble(values[2]),
Double.parseDouble(values[3]));
batch.add(pending);
i++;
j++;
if (i >= 2000) {
inspections.pendingInspectionsBatchInsert(batch);
batch.clear();
i = 0;
}
}
if (i > 0) {
inspections.pendingInspectionsBatchInsert(batch);
batch.clear();
}
br.close();
file.delete();
} catch (Exception e) {
Log.e("SyncActivity", e.toString());
}
}
編集:これはインターフェースとクラスの宣言です
public interface Inspectable {
public int getId();
public void setId(int id);
public String getLabel();
public void setLabel(String label);
public double getX();
public void setX(double x);
public double getY();
public void setY(double y);
}
public class RWInspection {
private String id;
private double x;
private double y;
private String inspector;
private String comments;
private String timestamp;
public RWInspection(String id, double x, double y, String inspector, String comments, String timestamp) {
this.id = id;
this.x = x;
this.y = y;
this.inspector = inspector;
this.comments = comments;
this.timestamp = timestamp;
}
中略....ゲッターとセッターの実装
public class PInspection implements Inspectable{
private int id;
private String number;
private double x;
private double y;
public PInspection(int id, String poleNumber, double x, double y) {
this.id = id;
this.number = number ;
this.x = x;
this.y = y;
}