private int deleteMessages(SQLiteDatabase db, String selection, String[] selectionArgs) { int count = 0; String sqlDesc = ""; db.beginTransaction(); try { // Delete all related records from MyDatabase.MsgOfUser for these messages String selectionG = " EXISTS (" + "SELECT * FROM " + Msg.TABLE_NAME + " WHERE (" + Msg.TABLE_NAME + "." + BaseColumns._ID + "=" + MsgOfUser.TABLE_NAME + "." + MyDatabase.MsgOfUser.MSG_ID + ") AND (" + selection + "))"; String descSuffix = "; args=" + Arrays.toString(selectionArgs); sqlDesc = selectionG + descSuffix; count = db.delete(MsgOfUser.TABLE_NAME, selectionG, selectionArgs); // Now delete messages themselves sqlDesc = selection + descSuffix; count = db.delete(Msg.TABLE_NAME, selection, selectionArgs); db.setTransactionSuccessful(); } catch (Exception e) { MyLog.d(TAG, "; SQL='" + sqlDesc + "'", e); } finally { db.endTransaction(); } return count; }
/** * Based on <a href="http://www.screaming-penguin.com/node/7749">Backing up your Android SQLite * database to the SD card</a> * * @param src * @param dst * @return true if success * @throws IOException */ boolean copyFile(File src, File dst) throws IOException { long sizeIn = -1; long sizeCopied = 0; boolean ok = false; if (src != null && src.exists()) { sizeIn = src.length(); if (!dst.createNewFile()) { MyLog.e(this, "New file was not created: '" + dst.getCanonicalPath() + "'"); } else if (src.getCanonicalPath().compareTo(dst.getCanonicalPath()) == 0) { MyLog.d(this, "Cannot copy to itself: '" + src.getCanonicalPath() + "'"); } else { FileInputStream fileInputStream = null; java.nio.channels.FileChannel inChannel = null; FileOutputStream fileOutputStream = null; java.nio.channels.FileChannel outChannel = null; try { fileInputStream = new FileInputStream(src); inChannel = fileInputStream.getChannel(); fileOutputStream = new FileOutputStream(dst); outChannel = fileOutputStream.getChannel(); sizeCopied = inChannel.transferTo(0, inChannel.size(), outChannel); ok = (sizeIn == sizeCopied); } finally { DbUtils.closeSilently(outChannel); DbUtils.closeSilently(fileOutputStream); DbUtils.closeSilently(inChannel); DbUtils.closeSilently(fileInputStream); } } } MyLog.d(this, "Copied " + sizeCopied + " bytes of " + sizeIn); return ok; }
public static boolean isServiceAvailable() { boolean isAvailable = MyContextHolder.get().isReady(); if (!isAvailable) { boolean tryToInitialize = false; synchronized (serviceAvailableLock) { tryToInitialize = mServiceAvailable; } if (tryToInitialize && !MyContextHolder.get().initialized()) { MyContextHolder.initialize(null, TAG); isAvailable = MyContextHolder.get().isReady(); } } if (isAvailable) { long availableInMillis = 0; synchronized (serviceAvailableLock) { availableInMillis = timeWhenTheServiceWillBeAvailable - System.currentTimeMillis(); if (!mServiceAvailable && availableInMillis <= 0) { setServiceAvailable(); } isAvailable = mServiceAvailable; } if (!isAvailable) { MyLog.v( TAG, "Service will be available in " + java.util.concurrent.TimeUnit.MILLISECONDS.toSeconds(availableInMillis) + " seconds"); } } else { MyLog.v(TAG, "Service is unavailable: Context is not Ready"); } return isAvailable; }
protected void copyMessageText(MessageEditorData editorData) { MyLog.v(this, "text='" + editorData.body + "'"); if (!TextUtils.isEmpty(editorData.body)) { // http://developer.android.com/guide/topics/text/copy-paste.html ClipboardManager clipboard = (ClipboardManager) MyContextHolder.get().context().getSystemService(Context.CLIPBOARD_SERVICE); ClipData clip = ClipData.newPlainText(I18n.trimTextAt(editorData.body, 40), editorData.body); clipboard.setPrimaryClip(clip); MyLog.v(this, "clip='" + clip.toString() + "'"); } }
@Override void executeOnUiThread(MessageContextMenu menu, MessageEditorData editorData) { Uri uri = MatchedUri.getUserListUri( editorData.ma.getUserId(), UserListType.USERS_OF_MESSAGE, menu.messageList.isTimelineCombined(), menu.getMsgId()); if (MyLog.isLoggable(this, MyLog.DEBUG)) { MyLog.d(this, "onItemClick, startActivity=" + uri); } menu.messageList.getActivity().startActivity(MyAction.VIEW_USERS.getIntent(uri)); }
@Override public String toString() { StringBuilder message = new StringBuilder(); if (executionCount > 0) { message.append("executed:" + executionCount + ","); if (retriesLeft > 0) { message.append("retriesLeft:" + retriesLeft + ","); } if (!hasError()) { message.append("error:None,"); } } if (hasError()) { message.append("error:" + (hasHardError() ? "Hard" : "Soft") + ","); } if (downloadedCount > 0) { message.append("downloaded:" + downloadedCount + ","); } if (messagesAdded > 0) { message.append("messagesAdded:" + messagesAdded + ","); } if (mentionsAdded > 0) { message.append("mentionsAdded:" + mentionsAdded + ","); } if (directedAdded > 0) { message.append("directedAdded:" + directedAdded + ","); } return MyLog.formatKeyValue("CommandResult", message); }
private void moveAll(TaskResult result) { boolean useExternalStorageOld = MyStorage.isStorageExternal(); if (mUseExternalStorageNew && !MyStorage.isWritableExternalStorageAvailable(result.messageBuilder)) { mUseExternalStorageNew = false; } MyLog.d( this, "About to move data from " + useExternalStorageOld + " to " + mUseExternalStorageNew); if (mUseExternalStorageNew == useExternalStorageOld) { result.messageBuilder.append(" Nothing to do."); result.success = true; return; } try { result.success = moveDatabase( mUseExternalStorageNew, result.messageBuilder, DatabaseHolder.DATABASE_NAME); if (result.success) { result.moved = true; moveDatabase( mUseExternalStorageNew, result.messageBuilder, TimelineSearchSuggestionsProvider.DATABASE_NAME); moveDownloads(mUseExternalStorageNew, result.messageBuilder); } } finally { if (result.success) { saveNewSettings(mUseExternalStorageNew, result.messageBuilder); } } }
@Override public String toString() { StringBuilder sb = new StringBuilder(64); sb.append("instance:" + instanceId + ","); sb.append("id:" + getId() + ","); return MyLog.formatKeyValue(this, sb.toString()); }
@Override protected void setUp() throws Exception { super.setUp(); MyLog.i(this, "setUp started"); TestSuite.initializeWithData(this); ma = MyContextHolder.get() .persistentAccounts() .fromAccountName(TestSuite.CONVERSATION_ACCOUNT_NAME); assertTrue(ma.isValid()); selectedMessageId = MyQuery.oidToId( OidEnum.MSG_OID, ma.getOriginId(), TestSuite.CONVERSATION_ENTRY_MESSAGE_OID); assertTrue("Selected message exists", selectedMessageId != 0); MyLog.i(this, "setUp ended"); }
public Activity waitForNextActivity(String methodExt, long timeOut) throws InterruptedException { Activity nextActivity = mInstrumentation.waitForMonitorWithTimeout(activityMonitor, timeOut); MyLog.v(methodExt, "After waitForMonitor: " + nextActivity); assertNotNull("Next activity is opened and captured", nextActivity); TestSuite.waitForListLoaded(mInstrumentation, nextActivity, 2); activityMonitor = null; return nextActivity; }
public static DownloadType load(String strCode) { try { return load(Long.parseLong(strCode)); } catch (NumberFormatException e) { MyLog.v(TAG, "Error converting '" + strCode + "'", e); } return UNKNOWN; }
public boolean execute(MessageContextMenu menu, MyAccount ma) { MyLog.v(this, "execute started"); if (mIsAsync) { executeAsync1(menu, ma); } else { executeOnUiThread(menu, MessageEditorData.newEmpty(ma).setMsgId(menu.getMsgId())); } return false; }
@Override protected void tearDown() throws Exception { logStartStop("tearDown started"); showAttachedImages = showAttachedImagesOld; showAvatars = showAvatarsOld; setPreferences(); MyLog.setLogToFile(false); super.tearDown(); }
public void findRepliesRecursively(ConversationOneMessage oMsg) { MyLog.v(this, "findReplies for id=" + oMsg.msgId); List<Long> replies = MyProvider.getReplyIds(oMsg.msgId); oMsg.nReplies = replies.size(); for (long replyId : replies) { ConversationOneMessage oMsgReply = new ConversationOneMessage(replyId, oMsg.replyLevel + 1); findPreviousMessagesRecursively(oMsgReply); } }
private boolean addMessageToList(ConversationOneMessage oMsg) { boolean added = false; if (oMsgs.contains(oMsg)) { MyLog.v(this, "Message id=" + oMsg.msgId + " is in the list already"); } else { oMsgs.add(oMsg); added = true; } return added; }
/** Returns true if message was added false in a case the message existed already */ private boolean addMessageIdToFind(long msgId) { if (msgId == 0) { return false; } else if (idsOfTheMessagesToFind.contains(msgId)) { MyLog.v(this, "findMessages cycled on the id=" + msgId); return false; } idsOfTheMessagesToFind.add(msgId); return true; }
private void saveNewSettings(boolean useExternalStorageNew, StringBuilder messageToAppend) { try { SharedPreferencesUtil.putBoolean( MyPreferences.KEY_USE_EXTERNAL_STORAGE, useExternalStorageNew); MyPreferences.onPreferencesChanged(); } catch (Exception e) { MyLog.v(this, "Save new settings", e); messageToAppend.append("Couldn't save new settings. " + e.getMessage()); } }
private void logStartStop(String text) { MyLog.i( this, text + ";" + " iteration " + iteration + (showAvatars ? " avatars;" : "") + (showAttachedImages ? " attached images;" : "")); }
// This is in the UI thread, so we can mess with the UI @Override protected void onPostExecute(TaskResult result) { DialogFactory.dismissSafely(dlg); if (result == null) { MyLog.e(this, "Result is Null"); return; } MyLog.d( this, this.getClass().getSimpleName() + " ended, " + (result.success ? (result.moved ? "moved" : "didn't move") : "failed")); if (!result.success) { result.messageBuilder.insert(0, mContext.getString(R.string.error) + ": "); } Toast.makeText(mContext, result.getMessage(), Toast.LENGTH_LONG).show(); parentFragment.showUseExternalStorage(); }
@Override protected void setUp() throws Exception { super.setUp(); MyLog.i(this, "setUp started"); TestSuite.initializeWithData(this); ma = MyContextHolder.get() .persistentAccounts() .fromAccountName(TestSuite.GNUSOCIAL_TEST_ACCOUNT_NAME); assertTrue(TestSuite.GNUSOCIAL_TEST_ACCOUNT_NAME + " exists", ma.isValid()); }
/** * InstrumentationTestCase.getInstrumentation().invokeContextMenuAction doesn't work properly * * @return success * <p>Note: This method cannot be invoked on the main thread. See * https://github.com/google/google-authenticator-android/blob/master/tests/src/com/google/android/apps/authenticator/TestUtilities.java */ private boolean invokeContextMenuAction( final String methodExt, final MyListActivity activity, int position, final int menuItemId) throws InterruptedException { final String method = "invokeContextMenuAction"; MyLog.v( methodExt, method + " started on menuItemId=" + menuItemId + " at position=" + position); boolean success = false; int position1 = position; for (long attempt = 1; attempt < 4; attempt++) { longClickAtPosition(methodExt, position1); if (mActivity.getPositionOfContextMenu() == position) { success = true; break; } MyLog.i( methodExt, method + "; Context menu created for position " + mActivity.getPositionOfContextMenu() + " instead of " + position + "; was set to " + position1 + "; attempt " + attempt); position1 = position + (position1 - mActivity.getPositionOfContextMenu()); } if (success) { mInstrumentation.runOnMainSync( new Runnable() { @Override public void run() { MyLog.v(methodExt, method + "; before performContextMenuIdentifierAction"); activity.getWindow().performContextMenuIdentifierAction(menuItemId, 0); } }); TestSuite.waitForIdleSync(mInstrumentation); } MyLog.v(methodExt, method + " ended " + success); return success; }
@Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); if (action.equals(MyAction.SERVICE_STATE.getAction())) { MyContextHolder.initialize(context, this); synchronized (mServiceState) { stateQueuedTime = System.nanoTime(); waitingForServiceState = false; mServiceState = MyServiceState.load(intent.getStringExtra(IntentExtra.SERVICE_STATE.key)); } MyLog.d(this, "Notification received: Service state=" + mServiceState); } else if ("android.intent.action.BOOT_COMPLETED".equals(action)) { MyLog.d(this, "Trying to start service on boot"); sendCommand(CommandData.getEmpty()); } else if ("android.intent.action.ACTION_SHUTDOWN".equals(action)) { // We need this to persist unsaved data in the service MyLog.d(this, "Stopping service on Shutdown"); setServiceUnavailable(); stopService(); } }
public void selectListPosition(final String methodExt, final int positionIn) throws InterruptedException { final String method = "selectListPosition"; MyLog.v(methodExt, method + " started; position=" + positionIn); mInstrumentation.runOnMainSync( new Runnable() { @Override public void run() { int position = positionIn; ListAdapter la = getListView().getAdapter(); if (la.getCount() <= position) { position = la.getCount() - 1; } MyLog.v( methodExt, method + " on setSelection " + position + " of " + (la.getCount() - 1)); getListView().setSelectionFromTop(position, 0); } }); TestSuite.waitForIdleSync(mInstrumentation); MyLog.v(methodExt, method + " ended"); }
@Override public void onReceive(CommandData commandData, MyServiceEvent event) { if (event != MyServiceEvent.AFTER_EXECUTING_COMMAND) { return; } final String method = "onReceive"; switch (commandData.getCommand()) { case AUTOMATIC_UPDATE: case FETCH_TIMELINE: if (mParams.mTimelineType != commandData.getTimelineType()) { break; } case GET_STATUS: case SEARCH_MESSAGE: if (commandData.getResult().getDownloadedCount() > 0) { if (MyLog.isVerboseEnabled()) { logV(method, "Content changed, " + commandData.toString()); } onContentChanged(); } break; case CREATE_FAVORITE: case DESTROY_FAVORITE: case DESTROY_REBLOG: case DESTROY_STATUS: case FETCH_ATTACHMENT: case FETCH_AVATAR: case REBLOG: case UPDATE_STATUS: if (!commandData.getResult().hasError()) { if (MyLog.isVerboseEnabled()) { logV(method, "Content changed, " + commandData.toString()); } onContentChanged(); } break; default: break; } }
private static Drawable loadDefaultAvatar(boolean lightTheme) { Drawable avatar = null; MyLog.v(AvatarDrawable.class, "Loading default avatar"); Context context = MyContextHolder.get().context(); if (context != null) { avatar = context .getResources() .getDrawable( lightTheme ? R.drawable.ic_action_user_light : R.drawable.ic_action_user); } return avatar; }
@Override void executeOnUiThread(MessageContextMenu menu, MessageEditorData editorData) { Uri uri = MatchedUri.getTimelineItemUri( editorData.ma.getUserId(), menu.messageList.getTimelineType(), menu.messageList.isTimelineCombined(), menu.messageList.getSelectedUserId(), menu.getMsgId()); String action = menu.messageList.getActivity().getIntent().getAction(); if (Intent.ACTION_PICK.equals(action) || Intent.ACTION_GET_CONTENT.equals(action)) { if (MyLog.isLoggable(this, MyLog.DEBUG)) { MyLog.d(this, "onItemClick, setData=" + uri); } menu.messageList.getActivity().setResult(Activity.RESULT_OK, new Intent().setData(uri)); } else { if (MyLog.isLoggable(this, MyLog.DEBUG)) { MyLog.d(this, "onItemClick, startActivity=" + uri); } menu.messageList.getActivity().startActivity(MyAction.VIEW_CONVERSATION.getIntent(uri)); } }
/** @return success */ public boolean invokeContextMenuAction4ListItemId( String methodExt, long listItemId, ContextMenuItem menuItem) throws InterruptedException { final String method = "invokeContextMenuAction4ListItemId"; boolean success = false; long id2 = listItemId; String msg = ""; for (long attempt = 1; attempt < 4; attempt++) { TestSuite.waitForIdleSync(mInstrumentation); int position = getPositionOfListItemId(listItemId); msg = "listItemId=" + listItemId + "; menu Item=" + menuItem + "; position=" + position + "; attempt=" + attempt; MyLog.v(this, msg); if (getListItemIdAtPosition(position) == listItemId) { selectListPosition(methodExt, position); if (invokeContextMenuAction(methodExt, mActivity, position, menuItem.getId())) { id2 = getListItemIdAtPosition(position); if (id2 == listItemId) { success = true; break; } else { MyLog.i( methodExt, method + "; Position changed, now pointing to listItemId=" + id2 + "; " + msg); } } } ; } MyLog.v(methodExt, method + " ended " + success + "; " + msg); TestSuite.waitForIdleSync(mInstrumentation); return success; }
private void markStart() { getParams().startTime = System.nanoTime(); getParams().cancelled = false; getParams().timelineToReload = TimelineType.UNKNOWN; if (MyLog.isVerboseEnabled()) { logV( "markStart", (TextUtils.isEmpty(getParams().mSearchQuery) ? "" : "queryString=\"" + getParams().mSearchQuery + "\"; ") + getParams().mTimelineType + "; isCombined=" + (getParams().mTimelineCombined ? "yes" : "no")); } }
public void clickView(final String methodExt, final View view) throws InterruptedException { assertTrue(view != null); Runnable clicker = new Runnable() { @Override public void run() { MyLog.v(methodExt, "Before click view"); view.performClick(); } }; mInstrumentation.runOnMainSync(clicker); MyLog.v(methodExt, "After click view"); TestSuite.waitForIdleSync(mInstrumentation); }
@Override protected void setUp() throws Exception { super.setUp(); TestSuite.initializeWithData(this); iteration = (iteration >= 4 ? 1 : iteration + 1); switch (iteration) { case 2: showAttachedImages = showAttachedImagesOld; showAvatars = !showAvatarsOld; break; case 3: showAttachedImages = !showAttachedImagesOld; showAvatars = showAvatarsOld; break; case 4: showAttachedImages = !showAttachedImagesOld; showAvatars = !showAvatarsOld; break; default: showAttachedImagesOld = MyPreferences.showAttachedImages(); showAvatarsOld = MyPreferences.showAvatars(); showAttachedImages = showAttachedImagesOld; showAvatars = showAvatarsOld; break; } setPreferences(); MyLog.setLogToFile(true); logStartStop("setUp started"); MyAccount ma = MyContextHolder.get() .persistentAccounts() .fromAccountName(TestSuite.CONVERSATION_ACCOUNT_NAME); assertTrue(ma.isValid()); MyContextHolder.get().persistentAccounts().setCurrentAccount(ma); Intent intent = new Intent( Intent.ACTION_VIEW, MatchedUri.getTimelineUri(ma.getUserId(), TimelineType.HOME, false, 0)); setActivityIntent(intent); activity = getActivity(); assertTrue("MyService is available", MyServiceManager.isServiceAvailable()); logStartStop("setUp ended"); }