Update DataUtils.java

main
pwiz98tyo 2 months ago
parent 5039cd6b33
commit 75549c0b7b

@ -16,395 +16,317 @@
package net.micode.notes.tool; package net.micode.notes.tool;
import android.content.Context; import android.content.ContentProviderOperation;
import android.content.ContentProviderResult;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.OperationApplicationException;
import android.database.Cursor; import android.database.Cursor;
import android.os.Build; import android.os.RemoteException;
import android.os.Environment;
import android.text.TextUtils;
import android.text.format.DateFormat;
import android.util.Log; import android.util.Log;
import net.micode.notes.R;
import net.micode.notes.data.Notes; import net.micode.notes.data.Notes;
import net.micode.notes.data.Notes.DataColumns; import net.micode.notes.data.Notes.CallNote;
import net.micode.notes.data.Notes.DataConstants;
import net.micode.notes.data.Notes.NoteColumns; import net.micode.notes.data.Notes.NoteColumns;
import net.micode.notes.ui.NotesListAdapter.AppWidgetAttribute;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.HashSet;
public class BackupUtils { public class DataUtils {
private static final String TAG = "BackupUtils"; public static final String TAG = "DataUtils";
// Singleton stuff
private static BackupUtils sInstance; /**
*
*/
public static boolean batchDeleteNotes(ContentResolver resolver, HashSet<Long> ids) {
if (ids == null) {
Log.d(TAG, "the ids is null");
return true;
}
if (ids.size() == 0) {
Log.d(TAG, "no id is in the hashset");
return true;
}
public static synchronized BackupUtils getInstance(Context context) { ArrayList<ContentProviderOperation> operationList = new ArrayList<ContentProviderOperation>();
if (sInstance == null) { for (long id : ids) {
sInstance = new BackupUtils(context); if(id == Notes.ID_ROOT_FOLDER) {
Log.e(TAG, "Don't delete system folder root");
continue;
}
ContentProviderOperation.Builder builder = ContentProviderOperation
.newDelete(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, id));
operationList.add(builder.build());
} }
return sInstance; try {
ContentProviderResult[] results = resolver.applyBatch(Notes.AUTHORITY, operationList);
if (results == null || results.length == 0 || results[0] == null) {
Log.d(TAG, "delete notes failed, ids:" + ids.toString());
return false;
}
return true;
} catch (RemoteException e) {
Log.e(TAG, String.format("%s: %s", e.toString(), e.getMessage()));
} catch (OperationApplicationException e) {
Log.e(TAG, String.format("%s: %s", e.toString(), e.getMessage()));
}
return false;
} }
/** /**
* Following states are signs to represents backup or restore *
* status
*/ */
// Currently, the sdcard is not mounted public static void moveNoteToFoler(ContentResolver resolver, long id, long srcFolderId, long desFolderId) {
public static final int STATE_SD_CARD_UNMOUONTED = 0; ContentValues values = new ContentValues();
// The backup file not exist values.put(NoteColumns.PARENT_ID, desFolderId);
public static final int STATE_BACKUP_FILE_NOT_EXIST = 1; values.put(NoteColumns.ORIGIN_PARENT_ID, srcFolderId);
// The data is not well formated, may be changed by other programs values.put(NoteColumns.LOCAL_MODIFIED, 1);
public static final int STATE_DATA_DESTROIED = 2; resolver.update(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, id), values, null, null);
// Some run-time exception which causes restore or backup fails
public static final int STATE_SYSTEM_ERROR = 3;
// Backup or restore success
public static final int STATE_SUCCESS = 4;
// Permission denied
public static final int STATE_PERMISSION_DENIED = 5;
private TextExport mTextExport;
private BackupUtils(Context context) {
mTextExport = new TextExport(context);
}
private static boolean externalStorageAvailable() {
return Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState());
} }
public int exportToText() { /**
return mTextExport.exportToText(); *
} */
public static boolean batchMoveToFolder(ContentResolver resolver, HashSet<Long> ids,
long folderId) {
if (ids == null) {
Log.d(TAG, "the ids is null");
return true;
}
public String getExportedTextFileName() { ArrayList<ContentProviderOperation> operationList = new ArrayList<ContentProviderOperation>();
return mTextExport.mFileName; for (long id : ids) {
} ContentProviderOperation.Builder builder = ContentProviderOperation
.newUpdate(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, id));
builder.withValue(NoteColumns.PARENT_ID, folderId);
builder.withValue(NoteColumns.LOCAL_MODIFIED, 1);
operationList.add(builder.build());
}
public String getExportedTextFileDir() { try {
return mTextExport.mFileDirectory; ContentProviderResult[] results = resolver.applyBatch(Notes.AUTHORITY, operationList);
if (results == null || results.length == 0 || results[0] == null) {
Log.d(TAG, "delete notes failed, ids:" + ids.toString());
return false;
}
return true;
} catch (RemoteException e) {
Log.e(TAG, String.format("%s: %s", e.toString(), e.getMessage()));
} catch (OperationApplicationException e) {
Log.e(TAG, String.format("%s: %s", e.toString(), e.getMessage()));
}
return false;
} }
private static class TextExport { /**
private static final String[] NOTE_PROJECTION = { *
NoteColumns.ID, */
NoteColumns.MODIFIED_DATE, public static int getUserFolderCount(ContentResolver resolver) {
NoteColumns.SNIPPET, Cursor cursor = resolver.query(Notes.CONTENT_NOTE_URI,
NoteColumns.TYPE, new String[] { "COUNT(*)" },
NoteColumns.PARENT_ID NoteColumns.TYPE + "=? AND " + NoteColumns.PARENT_ID + "<>?",
}; new String[] { String.valueOf(Notes.TYPE_FOLDER), String.valueOf(Notes.ID_TRASH_FOLER)},
null);
private static final int NOTE_COLUMN_ID = 0;
private static final int NOTE_COLUMN_MODIFIED_DATE = 1;
private static final int NOTE_COLUMN_SNIPPET = 2;
private static final int NOTE_COLUMN_TYPE = 3;
private static final int NOTE_COLUMN_PARENT_ID = 4;
private static final String[] DATA_PROJECTION = {
DataColumns.CONTENT,
DataColumns.MIME_TYPE,
DataColumns.DATA1,
DataColumns.DATA2,
DataColumns.DATA3,
DataColumns.DATA4,
};
private static final int DATA_COLUMN_CONTENT = 0;
private static final int DATA_COLUMN_MIME_TYPE = 1;
private static final int DATA_COLUMN_CALL_DATE = 2;
private static final int DATA_COLUMN_PHONE_NUMBER = 4;
private final String [] TEXT_FORMAT;
private static final int FORMAT_FOLDER_NAME = 0;
private static final int FORMAT_NOTE_DATE = 1;
private static final int FORMAT_NOTE_CONTENT = 2;
private Context mContext;
private String mFileName;
private String mFileDirectory;
private BufferedWriter mWriter;
private int mNotesCount;
private int mFoldersCount;
public TextExport(Context context) { int count = 0;
TEXT_FORMAT = context.getResources().getStringArray(R.array.format_for_exported_note); if(cursor != null) {
mContext = context; if(cursor.moveToFirst()) {
mFileName = ""; try {
mFileDirectory = ""; count = cursor.getInt(0);
mNotesCount = 0; } catch (IndexOutOfBoundsException e) {
mFoldersCount = 0; Log.e(TAG, "get folder count failed:" + e.toString());
} finally {
cursor.close();
}
}
} }
return count;
}
private String getFormat(int id) { /**
return TEXT_FORMAT[id]; *
} */
public static boolean visibleInNoteDatabase(ContentResolver resolver, long noteId, int type) {
Cursor cursor = resolver.query(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, noteId),
null,
NoteColumns.TYPE + "=? AND " + NoteColumns.PARENT_ID + "<>" + Notes.ID_TRASH_FOLER,
new String [] {String.valueOf(type)},
null);
/** boolean exist = false;
* Export notes to text file if (cursor != null) {
*/ if (cursor.getCount() > 0) {
public int exportToText() { exist = true;
if (!externalStorageAvailable()) {
Log.d(TAG, "Media was not mounted");
return STATE_SD_CARD_UNMOUONTED;
} }
cursor.close();
}
return exist;
}
File file = generateFileMountedOnSDcard(mContext, R.string.file_path, /**
R.string.file_name_txt_format); *
if (file == null) { */
Log.e(TAG, "create file to exported failed"); public static boolean existInNoteDatabase(ContentResolver resolver, long noteId) {
return STATE_SYSTEM_ERROR; Cursor cursor = resolver.query(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, noteId),
} null, null, null, null);
mFileName = file.getName(); boolean exist = false;
mFileDirectory = mContext.getString(R.string.file_path); if (cursor != null) {
if (cursor.getCount() > 0) {
// 使用try-with-resources确保资源释放 exist = true;
try (BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(new FileOutputStream(file), StandardCharsets.UTF_8))) {
mWriter = writer;
// 导出文件夹和笔记
exportFoldersAndNotes();
// 写入导出统计信息
writeExportSummary();
Log.d(TAG, "Export successful. Exported " + mFoldersCount + " folders and " + mNotesCount + " notes.");
return STATE_SUCCESS;
} catch (IOException e) {
Log.e(TAG, "Error during export: " + e.getMessage(), e);
return STATE_SYSTEM_ERROR;
} }
cursor.close();
} }
return exist;
/** }
*
*/ /**
private void writeExportSummary() throws IOException { *
mWriter.write("\n"); */
mWriter.write("==============================\n"); public static boolean existInDataDatabase(ContentResolver resolver, long dataId) {
mWriter.write(mContext.getString(R.string.export_summary) + "\n"); Cursor cursor = resolver.query(ContentUris.withAppendedId(Notes.CONTENT_DATA_URI, dataId),
mWriter.write(mContext.getString(R.string.export_date) + ": " null, null, null, null);
+ DateFormat.format(mContext.getString(R.string.format_datetime_ymdhm), System.currentTimeMillis()) + "\n");
mWriter.write(mContext.getString(R.string.folder_count) + ": " + mFoldersCount + "\n"); boolean exist = false;
mWriter.write(mContext.getString(R.string.note_count) + ": " + mNotesCount + "\n"); if (cursor != null) {
mWriter.write("==============================\n"); if (cursor.getCount() > 0) {
} exist = true;
/**
*
*/
private void exportFoldersAndNotes() throws IOException {
// 首先导出文件夹和其中的笔记
exportFolders();
// 导出根文件夹中的笔记
exportRootNotes();
}
/**
*
*/
private void exportFolders() throws IOException {
// 查询所有文件夹
String selection = "(" + NoteColumns.TYPE + "=" + Notes.TYPE_FOLDER + " AND "
+ NoteColumns.PARENT_ID + "<>" + Notes.ID_TRASH_FOLER + ") OR "
+ NoteColumns.ID + "=" + Notes.ID_CALL_RECORD_FOLDER;
try (Cursor folderCursor = mContext.getContentResolver().query(
Notes.CONTENT_NOTE_URI,
NOTE_PROJECTION,
selection, null, null)) {
if (folderCursor != null && folderCursor.moveToFirst()) {
do {
mFoldersCount++;
exportFolder(folderCursor);
} while (folderCursor.moveToNext());
}
} }
cursor.close();
} }
return exist;
/** }
*
*/ /**
private void exportFolder(Cursor folderCursor) throws IOException { *
String folderId = folderCursor.getString(NOTE_COLUMN_ID); */
String folderName; public static boolean checkVisibleFolderName(ContentResolver resolver, String name) {
Cursor cursor = resolver.query(Notes.CONTENT_NOTE_URI, null,
if(folderCursor.getLong(NOTE_COLUMN_ID) == Notes.ID_CALL_RECORD_FOLDER) { NoteColumns.TYPE + "=" + Notes.TYPE_FOLDER +
folderName = mContext.getString(R.string.call_record_folder_name); " AND " + NoteColumns.PARENT_ID + "<>" + Notes.ID_TRASH_FOLER +
} else { " AND " + NoteColumns.SNIPPET + "=?",
folderName = folderCursor.getString(NOTE_COLUMN_SNIPPET); new String[] { name }, null);
} boolean exist = false;
if(cursor != null) {
if (!TextUtils.isEmpty(folderName)) { if(cursor.getCount() > 0) {
mWriter.write(String.format(getFormat(FORMAT_FOLDER_NAME), folderName)); exist = true;
mWriter.newLine();
} }
cursor.close();
// 导出文件夹中的笔记
exportNotesInFolder(folderId);
// 添加文件夹分隔线
mWriter.write("\n");
} }
return exist;
/** }
*
*/ /**
private void exportNotesInFolder(String folderId) throws IOException { *
try (Cursor notesCursor = mContext.getContentResolver().query(Notes.CONTENT_NOTE_URI, */
NOTE_PROJECTION, NoteColumns.PARENT_ID + "=?", new String[] { folderId }, null)) { public static HashSet<AppWidgetAttribute> getFolderNoteWidget(ContentResolver resolver, long folderId) {
Cursor c = resolver.query(Notes.CONTENT_NOTE_URI,
if (notesCursor != null && notesCursor.moveToFirst()) { new String[] { NoteColumns.WIDGET_ID, NoteColumns.WIDGET_TYPE },
do { NoteColumns.PARENT_ID + "=?",
mNotesCount++; new String[] { String.valueOf(folderId) },
exportNote(notesCursor); null);
} while (notesCursor.moveToNext());
} HashSet<AppWidgetAttribute> set = null;
if (c != null) {
if (c.moveToFirst()) {
set = new HashSet<AppWidgetAttribute>();
do {
try {
AppWidgetAttribute widget = new AppWidgetAttribute();
widget.widgetId = c.getInt(0);
widget.widgetType = c.getInt(1);
set.add(widget);
} catch (IndexOutOfBoundsException e) {
Log.e(TAG, e.toString());
}
} while (c.moveToNext());
} }
c.close();
} }
return set;
/** }
*
*/ /**
private void exportRootNotes() throws IOException { * ID
try (Cursor noteCursor = mContext.getContentResolver().query( */
Notes.CONTENT_NOTE_URI, public static String getCallNumberByNoteId(ContentResolver resolver, long noteId) {
NOTE_PROJECTION, Cursor cursor = resolver.query(Notes.CONTENT_DATA_URI,
NoteColumns.TYPE + "=" + Notes.TYPE_NOTE + " AND " + NoteColumns.PARENT_ID + "=0", new String [] { CallNote.PHONE_NUMBER },
null, null)) { CallNote.NOTE_ID + "=? AND " + CallNote.MIME_TYPE + "=?",
new String [] { String.valueOf(noteId), CallNote.CONTENT_ITEM_TYPE },
if (noteCursor != null && noteCursor.moveToFirst()) { null);
do {
mNotesCount++; if (cursor != null && cursor.moveToFirst()) {
exportNote(noteCursor); try {
} while (noteCursor.moveToNext()); return cursor.getString(0);
} } catch (IndexOutOfBoundsException e) {
Log.e(TAG, "Get call number fails " + e.toString());
} finally {
cursor.close();
} }
} }
return "";
/** }
*
*/ /**
private void exportNote(Cursor noteCursor) throws IOException { * ID
// 打印笔记的最后修改日期 */
mWriter.write(String.format(getFormat(FORMAT_NOTE_DATE), public static long getNoteIdByPhoneNumberAndCallDate(ContentResolver resolver, String phoneNumber, long callDate) {
DateFormat.format(mContext.getString(R.string.format_datetime_mdhm), Cursor cursor = resolver.query(Notes.CONTENT_DATA_URI,
noteCursor.getLong(NOTE_COLUMN_MODIFIED_DATE)))); new String [] { CallNote.NOTE_ID },
mWriter.newLine(); CallNote.CALL_DATE + "=? AND " + CallNote.MIME_TYPE + "=? AND PHONE_NUMBERS_EQUAL("
+ CallNote.PHONE_NUMBER + ",?)",
// 查询并导出笔记的数据 new String [] { String.valueOf(callDate), CallNote.CONTENT_ITEM_TYPE, phoneNumber },
String noteId = noteCursor.getString(NOTE_COLUMN_ID); null);
exportNoteData(noteId);
if (cursor != null) {
// 添加笔记分隔线 if (cursor.moveToFirst()) {
mWriter.write("\n"); try {
} return cursor.getLong(0);
} catch (IndexOutOfBoundsException e) {
/** Log.e(TAG, "Get call note id fails " + e.toString());
*
*/
private void exportNoteData(String noteId) throws IOException {
try (Cursor dataCursor = mContext.getContentResolver().query(Notes.CONTENT_DATA_URI,
DATA_PROJECTION, DataColumns.NOTE_ID + "=?", new String[] { noteId }, null)) {
if (dataCursor != null && dataCursor.moveToFirst()) {
do {
String mimeType = dataCursor.getString(DATA_COLUMN_MIME_TYPE);
if (DataConstants.CALL_NOTE.equals(mimeType)) {
exportCallNote(dataCursor);
} else if (DataConstants.NOTE.equals(mimeType)) {
exportTextNote(dataCursor);
}
} while (dataCursor.moveToNext());
} }
} }
cursor.close();
} }
return 0;
/** }
*
*/
private void exportCallNote(Cursor dataCursor) throws IOException {
// 打印电话号码
String phoneNumber = dataCursor.getString(DATA_COLUMN_PHONE_NUMBER);
long callDate = dataCursor.getLong(DATA_COLUMN_CALL_DATE);
String location = dataCursor.getString(DATA_COLUMN_CONTENT);
if (!TextUtils.isEmpty(phoneNumber)) { /**
mWriter.write(String.format(getFormat(FORMAT_NOTE_CONTENT), phoneNumber)); * ID
mWriter.newLine(); */
} public static String getSnippetById(ContentResolver resolver, long noteId) {
Cursor cursor = resolver.query(Notes.CONTENT_NOTE_URI,
// 打印通话日期 new String [] { NoteColumns.SNIPPET },
mWriter.write(String.format(getFormat(FORMAT_NOTE_CONTENT), NoteColumns.ID + "=?",
DateFormat.format(mContext.getString(R.string.format_datetime_mdhm), callDate))); new String [] { String.valueOf(noteId)},
mWriter.newLine(); null);
// 打印通话附件位置
if (!TextUtils.isEmpty(location)) {
mWriter.write(String.format(getFormat(FORMAT_NOTE_CONTENT), location));
mWriter.newLine();
}
}
/**
*
*/
private void exportTextNote(Cursor dataCursor) throws IOException {
String content = dataCursor.getString(DATA_COLUMN_CONTENT);
if (!TextUtils.isEmpty(content)) {
mWriter.write(String.format(getFormat(FORMAT_NOTE_CONTENT), content));
mWriter.newLine();
}
}
/** if (cursor != null) {
* Generate the text file to store imported data String snippet = "";
*/ if (cursor.moveToFirst()) {
private static File generateFileMountedOnSDcard(Context context, int filePathResId, int fileNameFormatResId) { snippet = cursor.getString(0);
StringBuilder sb = new StringBuilder();
// 适配Android 10+的存储访问
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
sb.append(context.getExternalFilesDir(null));
} else {
sb.append(Environment.getExternalStorageDirectory());
} }
cursor.close();
sb.append(context.getString(filePathResId)); return snippet;
File filedir = new File(sb.toString()); }
throw new IllegalArgumentException("Note is not found with id: " + noteId);
// 确保目录存在 }
if (!filedir.exists() && !filedir.mkdirs()) {
Log.e(TAG, "Failed to create directory: " + filedir.getAbsolutePath());
return null;
}
// 构建文件名
sb.append(context.getString(
fileNameFormatResId,
DateFormat.format(context.getString(R.string.format_date_ymd),
System.currentTimeMillis())));
File file = new File(sb.toString());
try { /**
if (!file.exists() && !file.createNewFile()) { *
Log.e(TAG, "Failed to create file: " + file.getAbsolutePath()); */
return null; public static String getFormattedSnippet(String snippet) {
} if (snippet != null) {
return file; snippet = snippet.trim();
} catch (SecurityException | IOException e) { int index = snippet.indexOf('\n');
Log.e(TAG, "Error creating file: " + e.getMessage(), e); if (index != -1) {
return null; snippet = snippet.substring(0, index);
} }
} }
return snippet;
} }
} }

Loading…
Cancel
Save