List of usage examples for android.content.res Resources getString
@NonNull public String getString(@StringRes int id) throws NotFoundException
From source file:cgeo.geocaching.CacheDetailActivity.java
static void updateCacheLists(final View view, final Geocache cache, final Resources res) { final SpannableStringBuilder builder = new SpannableStringBuilder(); for (final Integer listId : cache.getLists()) { if (builder.length() > 0) { builder.append(", "); }//from ww w . jav a2 s. c om appendClickableList(builder, view, listId); } builder.insert(0, res.getString(R.string.list_list_headline) + " "); final TextView offlineLists = ButterKnife.findById(view, R.id.offline_lists); offlineLists.setText(builder); offlineLists.setMovementMethod(LinkMovementMethod.getInstance()); }
From source file:android.support.v7.widget.SearchView.java
/** * Create and return an Intent that can launch the voice search activity, perform a specific * voice transcription, and forward the results to the searchable activity. * * @param baseIntent The voice app search intent to start from * @return A completely-configured intent ready to send to the voice search activity *///from w w w. jav a 2 s . com @TargetApi(Build.VERSION_CODES.FROYO) private Intent createVoiceAppSearchIntent(Intent baseIntent, SearchableInfo searchable) { ComponentName searchActivity = searchable.getSearchActivity(); // create the necessary intent to set up a search-and-forward operation // in the voice search system. We have to keep the bundle separate, // because it becomes immutable once it enters the PendingIntent Intent queryIntent = new Intent(Intent.ACTION_SEARCH); queryIntent.setComponent(searchActivity); PendingIntent pending = PendingIntent.getActivity(getContext(), 0, queryIntent, PendingIntent.FLAG_ONE_SHOT); // Now set up the bundle that will be inserted into the pending intent // when it's time to do the search. We always build it here (even if empty) // because the voice search activity will always need to insert "QUERY" into // it anyway. Bundle queryExtras = new Bundle(); if (mAppSearchData != null) { queryExtras.putParcelable(SearchManager.APP_DATA, mAppSearchData); } // Now build the intent to launch the voice search. Add all necessary // extras to launch the voice recognizer, and then all the necessary extras // to forward the results to the searchable activity Intent voiceIntent = new Intent(baseIntent); // Add all of the configuration options supplied by the searchable's metadata String languageModel = RecognizerIntent.LANGUAGE_MODEL_FREE_FORM; String prompt = null; String language = null; int maxResults = 1; if (Build.VERSION.SDK_INT >= 8) { Resources resources = getResources(); if (searchable.getVoiceLanguageModeId() != 0) { languageModel = resources.getString(searchable.getVoiceLanguageModeId()); } if (searchable.getVoicePromptTextId() != 0) { prompt = resources.getString(searchable.getVoicePromptTextId()); } if (searchable.getVoiceLanguageId() != 0) { language = resources.getString(searchable.getVoiceLanguageId()); } if (searchable.getVoiceMaxResults() != 0) { maxResults = searchable.getVoiceMaxResults(); } } voiceIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, languageModel); voiceIntent.putExtra(RecognizerIntent.EXTRA_PROMPT, prompt); voiceIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, language); voiceIntent.putExtra(RecognizerIntent.EXTRA_MAX_RESULTS, maxResults); voiceIntent.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE, searchActivity == null ? null : searchActivity.flattenToShortString()); // Add the values that configure forwarding the results voiceIntent.putExtra(RecognizerIntent.EXTRA_RESULTS_PENDINGINTENT, pending); voiceIntent.putExtra(RecognizerIntent.EXTRA_RESULTS_PENDINGINTENT_BUNDLE, queryExtras); return voiceIntent; }
From source file:com.auratech.launcher.Folder.java
/** * Used to inflate the Workspace from XML. * * @param context The application's context. * @param attrs The attribtues set containing the Workspace's customization values. *//*from w w w .j ava2 s . c o m*/ public Folder(Context context, AttributeSet attrs) { super(context, attrs); LauncherAppState app = LauncherAppState.getInstance(); DeviceProfile grid = app.getDynamicGrid().getDeviceProfile(); setAlwaysDrawnWithCacheEnabled(false); mInflater = LayoutInflater.from(context); mIconCache = app.getIconCache(); Resources res = getResources(); mMaxCountX = (int) grid.numColumns; // Allow scrolling folders when DISABLE_ALL_APPS is true. if (LauncherAppState.isDisableAllApps()) { mMaxCountY = mMaxNumItems = Integer.MAX_VALUE; } else { mMaxCountY = (int) grid.numRows; mMaxNumItems = mMaxCountX * mMaxCountY; } mInputMethodManager = (InputMethodManager) getContext().getSystemService(Context.INPUT_METHOD_SERVICE); mExpandDuration = res.getInteger(R.integer.config_folderAnimDuration); if (sDefaultFolderName == null) { sDefaultFolderName = res.getString(R.string.folder_name); } if (sHintText == null) { sHintText = res.getString(R.string.folder_hint_text); } mLauncher = (Launcher) context; // We need this view to be focusable in touch mode so that when text editing of the folder // name is complete, we have something to focus on, thus hiding the cursor and giving // reliable behvior when clicking the text field (since it will always gain focus on click). setFocusableInTouchMode(true); }
From source file:com.mikecorrigan.trainscorekeeper.FragmentSummary.java
@SuppressLint("NewApi") @Override//from w ww. j a v a 2 s. com public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { Log.vc(VERBOSE, TAG, "onCreateView: inflater=" + inflater + ", container=" + container + ", savedInstanceState=" + Utils.bundleToString(savedInstanceState)); View rootView = inflater.inflate(R.layout.fragment_summary, container, false); final MainActivity activity = (MainActivity) getActivity(); final Context context = activity; final Resources resources = context.getResources(); // Get the model and attach a listener. game = activity.getGame(); if (game != null) { game.addListener(mGameListener); } players = activity.getPlayers(); // Get resources. String[] playerNames = resources.getStringArray(R.array.playerNames); TypedArray drawablesArray = resources.obtainTypedArray(R.array.playerDrawables); TypedArray playerTextColorsArray = resources.obtainTypedArray(R.array.playerTextColors); int[] playerTextColorsIds = new int[playerTextColorsArray.length()]; for (int i = 0; i < playerTextColorsArray.length(); i++) { playerTextColorsIds[i] = playerTextColorsArray.getResourceId(i, -1); } // Get root view. ScrollView scrollView = (ScrollView) rootView.findViewById(R.id.scroll_view); // Create table. tableLayout = new TableLayout(context); TableLayout.LayoutParams tableLayoutParams = new TableLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT); tableLayout.setLayoutParams(tableLayoutParams); scrollView.addView(tableLayout); // Add header. { TableRow row = new TableRow(context); row.setLayoutParams(new TableRow.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT)); tableLayout.addView(row); TextView tv = new TextView(context); tv.setGravity(Gravity.CENTER); tv.setPadding(10, 10, 10, 10); tv.setText(resources.getString(R.string.player)); tv.setTypeface(null, Typeface.BOLD); row.addView(tv); tv = new TextView(context); tv.setGravity(Gravity.CENTER); tv.setPadding(10, 10, 10, 10); tv.setText(resources.getString(R.string.trains)); tv.setTypeface(null, Typeface.BOLD); row.addView(tv); tv = new TextView(context); tv.setGravity(Gravity.CENTER); tv.setPadding(10, 10, 10, 10); tv.setText(resources.getString(R.string.contracts)); tv.setTypeface(null, Typeface.BOLD); row.addView(tv); tv = new TextView(context); tv.setGravity(Gravity.CENTER); tv.setPadding(10, 10, 10, 10); tv.setText(resources.getString(R.string.bonuses)); tv.setTypeface(null, Typeface.BOLD); row.addView(tv); } // Add rows. for (int i = 0; i < players.getNum(); i++) { TableRow row = new TableRow(context); row.setLayoutParams(new TableRow.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT)); tableLayout.addView(row); ToggleButton toggleButton = new ToggleButton(context); toggleButton.setGravity(Gravity.CENTER); toggleButton.setPadding(10, 10, 10, 10); toggleButton.setText(playerNames[i]); toggleButton.setClickable(false); Drawable drawable = drawablesArray.getDrawable(i); int sdk = android.os.Build.VERSION.SDK_INT; if (sdk < android.os.Build.VERSION_CODES.JELLY_BEAN) { toggleButton.setBackgroundDrawable(drawable); } else { toggleButton.setBackground(drawable); } toggleButton.setTextColor(resources.getColor(playerTextColorsIds[i])); row.addView(toggleButton); TextView tv = new TextView(context); tv.setGravity(Gravity.CENTER); tv.setPadding(10, 10, 10, 10); row.addView(tv); tv = new TextView(context); tv.setGravity(Gravity.CENTER); tv.setPadding(10, 10, 10, 10); row.addView(tv); tv = new TextView(context); tv.setGravity(Gravity.CENTER); tv.setPadding(10, 10, 10, 10); row.addView(tv); } Bundle args = getArguments(); if (args == null) { Log.e(TAG, "onCreateView: missing arguments"); return rootView; } drawablesArray.recycle(); playerTextColorsArray.recycle(); // final int index = args.getInt(ARG_INDEX); // final String tabSpec = args.getString(ARG_TAB_SPEC); return rootView; }
From source file:com.anysoftkeyboard.keyboards.views.AnyKeyboardViewBase.java
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) { Resources res = getResources(); if (key.equals(res.getString(R.string.settings_key_swipe_distance_threshold)) || key.equals(res.getString(R.string.settings_key_swipe_velocity_threshold))) { reloadSwipeThresholdsSettings(res); } else if (key.equals(res.getString(R.string.settings_key_long_press_timeout)) || key.equals(res.getString(R.string.settings_key_multitap_timeout))) { closing();/* w ww. j ava2 s . c o m*/ mPointerTrackers.clear(); } else if (key.equals(res.getString(R.string.settings_key_key_press_preview_popup_position)) || key.equals(res.getString(R.string.settings_key_key_press_shows_preview_popup)) || key.equals(res.getString(R.string.settings_key_tweak_animations_level))) { mKeyPreviewsManager.destroy(); mKeyPreviewsManager = new KeyPreviewsManager(getContext(), this, mPreviewPopupTheme); } }
From source file:com.android.messaging.datamodel.media.VCardResourceEntry.java
private static List<VCardResourceEntryDestinationItem> getContactInfoFromVCardEntry(final VCardEntry vcard) { final Resources resources = Factory.get().getApplicationContext().getResources(); final List<VCardResourceEntry.VCardResourceEntryDestinationItem> retList = new ArrayList<VCardResourceEntry.VCardResourceEntryDestinationItem>(); if (vcard.getPhoneList() != null) { for (final PhoneData phone : vcard.getPhoneList()) { final Intent intent = new Intent(Intent.ACTION_DIAL); intent.setData(Uri.parse("tel:" + phone.getNumber())); retList.add(new VCardResourceEntryDestinationItem(phone.getNumber(), Phone.getTypeLabel(resources, phone.getType(), phone.getLabel()).toString(), intent)); }/* w w w . ja v a2 s. co m*/ } if (vcard.getEmailList() != null) { for (final EmailData email : vcard.getEmailList()) { final Intent intent = new Intent(Intent.ACTION_SENDTO); intent.setData(Uri.parse("mailto:")); intent.putExtra(Intent.EXTRA_EMAIL, new String[] { email.getAddress() }); retList.add(new VCardResourceEntryDestinationItem(email.getAddress(), Phone.getTypeLabel(resources, email.getType(), email.getLabel()).toString(), intent)); } } if (vcard.getPostalList() != null) { for (final PostalData postalData : vcard.getPostalList()) { String type; try { type = resources.getStringArray(android.R.array.postalAddressTypes)[postalData.getType() - 1]; } catch (final NotFoundException ex) { type = resources.getStringArray(android.R.array.postalAddressTypes)[2]; } catch (final Exception e) { LogUtil.e(LogUtil.BUGLE_TAG, "createContactItem postal Exception:" + e); type = resources.getStringArray(android.R.array.postalAddressTypes)[2]; } Intent intent = new Intent(Intent.ACTION_VIEW); final String address = formatAddress(postalData); try { intent.setData(Uri.parse("geo:0,0?q=" + URLEncoder.encode(address, "UTF-8"))); } catch (UnsupportedEncodingException e) { intent = null; } retList.add(new VCardResourceEntryDestinationItem(address, type, intent)); } } if (vcard.getImList() != null) { for (final ImData imData : vcard.getImList()) { String type = null; try { type = resources.getString(Im.getProtocolLabelResource(imData.getProtocol())); } catch (final NotFoundException ex) { // Do nothing since this implies an empty label. } retList.add(new VCardResourceEntryDestinationItem(imData.getAddress(), type, null)); } } if (vcard.getOrganizationList() != null) { for (final OrganizationData organtization : vcard.getOrganizationList()) { String type = null; try { type = resources.getString(Organization.getTypeLabelResource(organtization.getType())); } catch (final NotFoundException ex) { //set other kind as "other" type = resources.getStringArray(android.R.array.organizationTypes)[1]; } catch (final Exception e) { LogUtil.e(LogUtil.BUGLE_TAG, "createContactItem org Exception:" + e); type = resources.getStringArray(android.R.array.organizationTypes)[1]; } retList.add(new VCardResourceEntryDestinationItem(organtization.getOrganizationName(), type, null)); } } if (vcard.getWebsiteList() != null) { for (final WebsiteData web : vcard.getWebsiteList()) { if (web != null && TextUtils.isGraphic(web.getWebsite())) { String website = web.getWebsite(); if (!website.startsWith("http://") && !website.startsWith("https://")) { // Prefix required for parsing to end up with a scheme and result in // navigation website = "http://" + website; } final Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(website)); retList.add(new VCardResourceEntryDestinationItem(web.getWebsite(), null, intent)); } } } if (vcard.getBirthday() != null) { final String birthday = vcard.getBirthday(); if (TextUtils.isGraphic(birthday)) { retList.add(new VCardResourceEntryDestinationItem(birthday, resources.getString(R.string.vcard_detail_birthday_label), null)); } } if (vcard.getNotes() != null) { for (final NoteData note : vcard.getNotes()) { final ArrayMap<String, String> curChildMap = new ArrayMap<String, String>(); if (TextUtils.isGraphic(note.getNote())) { retList.add(new VCardResourceEntryDestinationItem(note.getNote(), resources.getString(R.string.vcard_detail_notes_label), null)); } } } return retList; }
From source file:com.hichinaschool.flashcards.async.DeckTask.java
private TaskData doInBackgroundOpenCollection(TaskData... params) { // Log.i(AnkiDroidApp.TAG, "doInBackgroundOpenCollection"); long time = Utils.intNow(1000); Resources res = AnkiDroidApp.getInstance().getBaseContext().getResources(); String collectionFile = params[0].getString(); SharedPreferences prefs = AnkiDroidApp.getSharedPrefs(AnkiDroidApp.getInstance().getBaseContext()); // see, if a collection is still opened Collection oldCol = AnkiDroidApp.getCol(); Collection col = null;/*from www .ja v a 2s .co m*/ publishProgress(new TaskData(res.getString(R.string.open_collection))); if (!(AnkiDroidApp.colIsOpen() && oldCol.getPath().equals(collectionFile))) { // do a safety backup if last backup is too old --> addresses // android's delete db bug if (BackupManager.safetyBackupNeeded(collectionFile)) { publishProgress(new TaskData(res.getString(R.string.backup_collection))); BackupManager.performBackup(collectionFile); } publishProgress(new TaskData(res.getString(R.string.open_collection))); // load collection try { col = AnkiDroidApp.openCollection(collectionFile); } catch (RuntimeException e) { BackupManager.restoreCollectionIfMissing(collectionFile); Log.e(AnkiDroidApp.TAG, "doInBackgroundOpenCollection - RuntimeException on opening collection: " + e); AnkiDroidApp.saveExceptionReportFile(e, "doInBackgroundOpenCollection"); return new TaskData(false); } // create tutorial deck if needed if (prefs.contains("createTutorial") && prefs.getBoolean("createTutorial", false)) { prefs.edit().remove("createTutorial").commit(); publishProgress(new TaskData(res.getString(R.string.tutorial_load))); doInBackgroundLoadTutorial(new TaskData(col)); } } else { // Log.i(AnkiDroidApp.TAG, "doInBackgroundOpenCollection: collection still open - reusing it"); col = oldCol; } Object[] counts = null; DeckTask.TaskData result = doInBackgroundLoadDeckCounts(new TaskData(col)); if (result != null) { counts = result.getObjArray(); } if (prefs.getBoolean("splashScreen", false)) { long millies = Utils.intNow(1000) - time; if (millies < 1000) { try { Thread.sleep(2200 - millies); } catch (InterruptedException e) { } } } return new TaskData(col, counts); }
From source file:com.nit.async.DeckTask.java
private TaskData doInBackgroundOpenCollection(TaskData... params) { // Log.i(AnkiDroidApp.TAG, "doInBackgroundOpenCollection"); long time = Utils.intNow(1000); Resources res = AnkiDroidApp.getInstance().getBaseContext().getResources(); String collectionFile = params[0].getString(); SharedPreferences prefs = AnkiDroidApp.getSharedPrefs(AnkiDroidApp.getInstance().getBaseContext()); // see, if a collection is still opened Collection oldCol = AnkiDroidApp.getCol(); Collection col = null;//ww w .j a v a 2 s . c om publishProgress(new TaskData(res.getString(R.string.open_collection))); if (!(AnkiDroidApp.colIsOpen() && oldCol.getPath().equals(collectionFile))) { // do a safety backup if last backup is too old --> addresses // android's delete db bug if (BackupManager.safetyBackupNeeded(collectionFile)) { publishProgress(new TaskData(res.getString(R.string.backup_collection))); BackupManager.performBackup(collectionFile); } publishProgress(new TaskData(res.getString(R.string.open_collection))); // load collection try { col = AnkiDroidApp.openCollection(collectionFile); } catch (RuntimeException e) { BackupManager.restoreCollectionIfMissing(collectionFile); Log.e(AnkiDroidApp.TAG, "doInBackgroundOpenCollection - RuntimeException on opening collection: " + e); AnkiDroidApp.saveExceptionReportFile(e, "doInBackgroundOpenCollection"); return new TaskData(false); } // create tutorial deck if needed if (prefs.contains("createTutorial") && prefs.getBoolean("createTutorial", false)) { prefs.edit().remove("createTutorial").commit(); publishProgress(new TaskData(res.getString(R.string.tutorial_load))); doInBackgroundLoadTutorial(new TaskData(col)); } } else { // Log.i(AnkiDroidApp.TAG, "doInBackgroundOpenCollection: collection still open - reusing it"); col = oldCol; } Object[] counts = null; DeckTask.TaskData result = doInBackgroundLoadDeckCounts(new TaskData(col)); if (result != null) { counts = result.getObjArray(); } if (prefs.getBoolean("splashScreen", false)) { long millies = Utils.intNow(1000) - time; if (millies < 1000) { try { Thread.sleep(1200 - millies); } catch (InterruptedException e) { } } } return new TaskData(col, counts); }
From source file:com.hichinaschool.flashcards.async.DeckTask.java
private TaskData doInBackgroundImportReplace(TaskData... params) { // Log.i(AnkiDroidApp.TAG, "doInBackgroundImportReplace"); Collection col = params[0].getCollection(); String path = params[0].getString(); Resources res = AnkiDroidApp.getInstance().getBaseContext().getResources(); // extract the deck from the zip file String fileDir = AnkiDroidApp.getCurrentAnkiDroidDirectory() + "/tmpzip"; File dir = new File(fileDir); if (dir.exists()) { BackupManager.removeDir(dir);/*w ww. j a va2 s . c om*/ } publishProgress(new TaskData(res.getString(R.string.import_unpacking))); // from anki2.py String colFile = fileDir + "/collection.anki2"; ZipFile zip; try { zip = new ZipFile(new File(path), ZipFile.OPEN_READ); } catch (IOException e) { Log.e(AnkiDroidApp.TAG, "doInBackgroundImportReplace - Error while unzipping: ", e); AnkiDroidApp.saveExceptionReportFile(e, "doInBackgroundImportReplace0"); return new TaskData(false); } if (!Utils.unzipFiles(zip, fileDir, new String[] { "collection.anki2", "media" }, null) || !(new File(colFile)).exists()) { return new TaskData(-2, null, false); } Collection tmpCol = null; try { tmpCol = Storage.Collection(colFile); if (!tmpCol.validCollection()) { tmpCol.close(); return new TaskData(-2, null, false); } } finally { if (tmpCol != null) { tmpCol.close(); } } publishProgress(new TaskData(res.getString(R.string.importing_collection))); String colPath; if (col != null) { // unload collection and trigger a backup colPath = col.getPath(); AnkiDroidApp.closeCollection(true); BackupManager.performBackup(colPath, true); } // overwrite collection colPath = AnkiDroidApp.getCollectionPath(); File f = new File(colFile); f.renameTo(new File(colPath)); int addedCount = -1; try { col = AnkiDroidApp.openCollection(colPath); // because users don't have a backup of media, it's safer to import new // data and rely on them running a media db check to get rid of any // unwanted media. in the future we might also want to duplicate this step // import media HashMap<String, String> nameToNum = new HashMap<String, String>(); HashMap<String, String> numToName = new HashMap<String, String>(); File mediaMapFile = new File(fileDir, "media"); if (mediaMapFile.exists()) { JsonReader jr = new JsonReader(new FileReader(mediaMapFile)); jr.beginObject(); String name; String num; while (jr.hasNext()) { num = jr.nextName(); name = jr.nextString(); nameToNum.put(name, num); numToName.put(num, name); } jr.endObject(); jr.close(); } String mediaDir = col.getMedia().getDir(); int total = nameToNum.size(); int i = 0; for (Map.Entry<String, String> entry : nameToNum.entrySet()) { String file = entry.getKey(); String c = entry.getValue(); File of = new File(mediaDir, file); if (!of.exists()) { Utils.unzipFiles(zip, mediaDir, new String[] { c }, numToName); } ++i; publishProgress(new TaskData(res.getString(R.string.import_media_count, (i + 1) * 100 / total))); } zip.close(); // delete tmp dir BackupManager.removeDir(dir); publishProgress(new TaskData(res.getString(R.string.import_update_counts))); // Update the counts DeckTask.TaskData result = doInBackgroundLoadDeckCounts(new TaskData(col)); if (result == null) { return null; } return new TaskData(addedCount, result.getObjArray(), true); } catch (RuntimeException e) { Log.e(AnkiDroidApp.TAG, "doInBackgroundImportReplace - RuntimeException: ", e); AnkiDroidApp.saveExceptionReportFile(e, "doInBackgroundImportReplace1"); return new TaskData(false); } catch (FileNotFoundException e) { Log.e(AnkiDroidApp.TAG, "doInBackgroundImportReplace - FileNotFoundException: ", e); AnkiDroidApp.saveExceptionReportFile(e, "doInBackgroundImportReplace2"); return new TaskData(false); } catch (IOException e) { Log.e(AnkiDroidApp.TAG, "doInBackgroundImportReplace - IOException: ", e); AnkiDroidApp.saveExceptionReportFile(e, "doInBackgroundImportReplace3"); return new TaskData(false); } }
From source file:com.nit.async.DeckTask.java
private TaskData doInBackgroundImportReplace(TaskData... params) { // Log.i(AnkiDroidApp.TAG, "doInBackgroundImportReplace"); Collection col = params[0].getCollection(); String path = params[0].getString(); Resources res = AnkiDroidApp.getInstance().getBaseContext().getResources(); // extract the deck from the zip file String fileDir = AnkiDroidApp.getCurrentAnkiDroidDirectory() + "/tmpzip"; File dir = new File(fileDir); if (dir.exists()) { BackupManager.removeDir(dir);/*from ww w .j a va2 s . co m*/ } publishProgress(new TaskData(res.getString(R.string.import_unpacking))); // from anki2.py String colFile = fileDir + "/collection.anki2"; ZipFile zip; try { zip = new ZipFile(new File(path)); } catch (IOException e) { Log.e(AnkiDroidApp.TAG, "doInBackgroundImportReplace - Error while unzipping: ", e); AnkiDroidApp.saveExceptionReportFile(e, "doInBackgroundImportReplace0"); return new TaskData(false); } if (!Utils.unzipFiles(zip, fileDir, new String[] { "collection.anki2", "media" }, null) || !(new File(colFile)).exists()) { return new TaskData(-2, null, false); } Collection tmpCol = null; try { tmpCol = Storage.Collection(colFile); if (!tmpCol.validCollection()) { tmpCol.close(); return new TaskData(-2, null, false); } } finally { if (tmpCol != null) { tmpCol.close(); } } publishProgress(new TaskData(res.getString(R.string.importing_collection))); String colPath; if (col != null) { // unload collection and trigger a backup colPath = col.getPath(); AnkiDroidApp.closeCollection(true); BackupManager.performBackup(colPath, true); } // overwrite collection colPath = AnkiDroidApp.getCollectionPath(); File f = new File(colFile); f.renameTo(new File(colPath)); int addedCount = -1; try { col = AnkiDroidApp.openCollection(colPath); // because users don't have a backup of media, it's safer to import new // data and rely on them running a media db check to get rid of any // unwanted media. in the future we might also want to duplicate this step // import media HashMap<String, String> nameToNum = new HashMap<String, String>(); HashMap<String, String> numToName = new HashMap<String, String>(); File mediaMapFile = new File(fileDir, "media"); if (mediaMapFile.exists()) { JsonReader jr = new JsonReader(new FileReader(mediaMapFile)); jr.beginObject(); String name; String num; while (jr.hasNext()) { num = jr.nextName(); name = jr.nextString(); nameToNum.put(name, num); numToName.put(num, name); } jr.endObject(); jr.close(); } String mediaDir = col.getMedia().getDir(); int total = nameToNum.size(); int i = 0; for (Map.Entry<String, String> entry : nameToNum.entrySet()) { String file = entry.getKey(); String c = entry.getValue(); File of = new File(mediaDir, file); if (!of.exists()) { Utils.unzipFiles(zip, mediaDir, new String[] { c }, numToName); } ++i; publishProgress(new TaskData(res.getString(R.string.import_media_count, (i + 1) * 100 / total))); } zip.close(); // delete tmp dir BackupManager.removeDir(dir); publishProgress(new TaskData(res.getString(R.string.import_update_counts))); // Update the counts DeckTask.TaskData result = doInBackgroundLoadDeckCounts(new TaskData(col)); if (result == null) { return null; } return new TaskData(addedCount, result.getObjArray(), true); } catch (RuntimeException e) { Log.e(AnkiDroidApp.TAG, "doInBackgroundImportReplace - RuntimeException: ", e); AnkiDroidApp.saveExceptionReportFile(e, "doInBackgroundImportReplace1"); return new TaskData(false); } catch (FileNotFoundException e) { Log.e(AnkiDroidApp.TAG, "doInBackgroundImportReplace - FileNotFoundException: ", e); AnkiDroidApp.saveExceptionReportFile(e, "doInBackgroundImportReplace2"); return new TaskData(false); } catch (IOException e) { Log.e(AnkiDroidApp.TAG, "doInBackgroundImportReplace - IOException: ", e); AnkiDroidApp.saveExceptionReportFile(e, "doInBackgroundImportReplace3"); return new TaskData(false); } }