]> gitweb.fperrin.net Git - Dictionary.git/blob - src/com/hughes/android/dictionary/DictionaryManagerActivity.java
Fix some resource leaks.
[Dictionary.git] / src / com / hughes / android / dictionary / DictionaryManagerActivity.java
1 // Copyright 2011 Google Inc. All Rights Reserved.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 //     http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 package com.hughes.android.dictionary;
16
17 import android.app.AlertDialog;
18 import android.app.DownloadManager;
19 import android.app.DownloadManager.Request;
20 import android.content.BroadcastReceiver;
21 import android.content.Context;
22 import android.content.Intent;
23 import android.content.IntentFilter;
24 import android.content.SharedPreferences;
25 import android.content.SharedPreferences.Editor;
26 import android.database.Cursor;
27 import android.net.Uri;
28 import android.os.Bundle;
29 import android.os.Environment;
30 import android.os.Handler;
31 import android.preference.PreferenceManager;
32 import android.support.v7.app.ActionBar;
33 import android.support.v7.app.ActionBarActivity;
34 import android.support.v7.widget.SearchView;
35 import android.support.v7.widget.SearchView.OnQueryTextListener;
36 import android.support.v7.widget.Toolbar;
37 import android.util.Log;
38 import android.util.TypedValue;
39 import android.view.ContextMenu;
40 import android.view.ContextMenu.ContextMenuInfo;
41 import android.view.LayoutInflater;
42 import android.view.Menu;
43 import android.view.View;
44 import android.view.View.OnClickListener;
45 import android.view.ViewGroup;
46 import android.view.inputmethod.EditorInfo;
47 import android.view.inputmethod.InputMethodManager;
48 import android.widget.AdapterView.AdapterContextMenuInfo;
49 import android.widget.BaseAdapter;
50 import android.widget.Button;
51 import android.widget.CompoundButton;
52 import android.widget.CompoundButton.OnCheckedChangeListener;
53 import android.widget.FrameLayout;
54 import android.widget.LinearLayout;
55 import android.widget.ListAdapter;
56 import android.widget.ListView;
57 import android.widget.TextView;
58 import android.widget.Toast;
59 import android.widget.ToggleButton;
60
61 import com.hughes.android.dictionary.DictionaryInfo.IndexInfo;
62 import com.hughes.android.util.IntentLauncher;
63
64 import java.io.File;
65 import java.io.FileOutputStream;
66 import java.io.IOException;
67 import java.io.InputStream;
68 import java.io.OutputStream;
69 import java.net.MalformedURLException;
70 import java.net.URL;
71 import java.util.Collections;
72 import java.util.List;
73 import java.util.zip.ZipEntry;
74 import java.util.zip.ZipFile;
75
76 // Right-click:
77 //  Delete, move to top.
78
79 public class DictionaryManagerActivity extends ActionBarActivity {
80
81     static final String LOG = "QuickDic";
82     static boolean blockAutoLaunch = false;
83
84     private ListView listView;
85     private ListView getListView() {
86         if (listView == null) {
87             listView = (ListView)findViewById(android.R.id.list);
88         }
89         return listView;
90     }
91     private void setListAdapter(ListAdapter adapter) {
92         getListView().setAdapter(adapter);
93     }
94     private ListAdapter getListAdapter() {
95         return getListView().getAdapter();
96     }
97
98     DictionaryApplication application;
99
100     SearchView filterSearchView;
101     ToggleButton showDownloadable;
102
103     LinearLayout dictionariesOnDeviceHeaderRow;
104     LinearLayout downloadableDictionariesHeaderRow;
105
106     Handler uiHandler;
107
108     Runnable dictionaryUpdater = new Runnable() {
109         @Override
110         public void run() {
111             if (uiHandler == null) {
112                 return;
113             }
114             uiHandler.post(new Runnable() {
115                 @Override
116                 public void run() {
117                     setMyListAdapater();
118                 }
119             });
120         }
121     };
122
123     final BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
124         @Override
125         public void onReceive(Context context, Intent intent) {
126             final String action = intent.getAction();
127
128             if (DownloadManager.ACTION_DOWNLOAD_COMPLETE.equals(action)) {
129                 final long downloadId = intent.getLongExtra(
130                         DownloadManager.EXTRA_DOWNLOAD_ID, 0);
131                 final DownloadManager.Query query = new DownloadManager.Query();
132                 query.setFilterById(downloadId);
133                 final DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
134                 final Cursor cursor = downloadManager.query(query);
135
136                 if (cursor == null || !cursor.moveToFirst()) {
137                     Log.e(LOG, "Couldn't find download.");
138                     return;
139                 }
140
141                 final String dest = cursor
142                         .getString(cursor.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI));
143                 final int status = cursor
144                         .getInt(cursor
145                                 .getColumnIndex(DownloadManager.COLUMN_STATUS));
146                 if (DownloadManager.STATUS_SUCCESSFUL != status) {
147                     final int reason = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_REASON));
148                     Log.w(LOG,
149                             "Download failed: status=" + status +
150                                     ", reason=" + reason);
151                     String msg = Integer.toString(reason);
152                     switch (reason) {
153                     case DownloadManager.ERROR_FILE_ALREADY_EXISTS: msg = "File exists"; break;
154                     case DownloadManager.ERROR_FILE_ERROR: msg = "File error"; break;
155                     case DownloadManager.ERROR_INSUFFICIENT_SPACE: msg = "Not enough space"; break;
156                     }
157                     new AlertDialog.Builder(context).setTitle(getString(R.string.error)).setMessage(getString(R.string.downloadFailed, reason)).setNeutralButton("Close", null).show();
158                     return;
159                 }
160
161                 Log.w(LOG, "Download finished: " + dest);
162                 Toast.makeText(context, getString(R.string.unzippingDictionary, dest),
163                         Toast.LENGTH_LONG).show();
164                 
165                 
166                 final File localZipFile = new File(Uri.parse(dest).getPath());
167                 ZipFile zipFile = null;
168                 InputStream zipIn = null;
169                 OutputStream zipOut = null;
170                 try {
171                     zipFile = new ZipFile(localZipFile);
172                     final ZipEntry zipEntry = zipFile.entries().nextElement();
173                     Log.d(LOG, "Unzipping entry: " + zipEntry.getName());
174                     zipIn = zipFile.getInputStream(zipEntry);
175                     File targetFile = new File(application.getDictDir(), zipEntry.getName());
176                     if (targetFile.exists()) {
177                         targetFile.renameTo(new File(targetFile.getAbsolutePath().replace(".quickdic", ".bak.quickdic")));
178                         targetFile = new File(application.getDictDir(), zipEntry.getName());
179                     }
180                     zipOut = new FileOutputStream(targetFile);
181                     copyStream(zipIn, zipOut);
182                     application.backgroundUpdateDictionaries(dictionaryUpdater);
183                     Toast.makeText(context, getString(R.string.installationFinished, dest),
184                             Toast.LENGTH_LONG).show();
185                 } catch (Exception e) {
186                     String msg = getString(R.string.unzippingFailed, dest);
187                     File dir = application.getDictDir();
188                     if (!dir.canWrite() || !application.checkFileCreate(dir)) {
189                         msg = getString(R.string.notWritable, dir.getAbsolutePath());
190                     }
191                     new AlertDialog.Builder(context).setTitle(getString(R.string.error)).setMessage(msg).setNeutralButton("Close", null).show();
192                     Log.e(LOG, "Failed to unzip.", e);
193                 } finally {
194                     try { if (zipOut != null) zipOut.close(); } catch (IOException e) {}
195                     try { if (zipIn != null) zipIn.close(); } catch (IOException e) {}
196                     try { if (zipFile != null) zipFile.close(); } catch (IOException e) {}
197                     localZipFile.delete();
198                 }
199             }
200         }
201     };
202
203     public static Intent getLaunchIntent(Context c) {
204         final Intent intent = new Intent(c, DictionaryManagerActivity.class);
205         intent.putExtra(C.CAN_AUTO_LAUNCH_DICT, false);
206         return intent;
207     }
208
209     @Override
210     public void onCreate(Bundle savedInstanceState) {
211         // This must be first, otherwise the actiona bar doesn't get
212         // styled properly.
213         setTheme(((DictionaryApplication) getApplication()).getSelectedTheme().themeId);
214
215         super.onCreate(savedInstanceState);
216         Log.d(LOG, "onCreate:" + this);
217
218         application = (DictionaryApplication) getApplication();
219
220         blockAutoLaunch = false;
221
222         // UI init.
223         setContentView(R.layout.dictionary_manager_activity);
224
225         dictionariesOnDeviceHeaderRow = (LinearLayout) LayoutInflater.from(
226                 getListView().getContext()).inflate(
227                 R.layout.dictionary_manager_header_row_on_device, getListView(), false);
228
229         downloadableDictionariesHeaderRow = (LinearLayout) LayoutInflater.from(
230                 getListView().getContext()).inflate(
231                 R.layout.dictionary_manager_header_row_downloadable, getListView(), false);
232
233         showDownloadable = (ToggleButton) downloadableDictionariesHeaderRow
234                 .findViewById(R.id.hideDownloadable);
235         showDownloadable.setOnCheckedChangeListener(new OnCheckedChangeListener() {
236             @Override
237             public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
238                 onShowDownloadableChanged();
239             }
240         });
241
242         final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
243         final String thanksForUpdatingLatestVersion = getString(R.string.thanksForUpdatingVersion);
244         if (!prefs.getString(C.THANKS_FOR_UPDATING_VERSION, "").equals(
245                 thanksForUpdatingLatestVersion)) {
246             blockAutoLaunch = true;
247             startActivity(HtmlDisplayActivity.getWhatsNewLaunchIntent(getApplicationContext()));
248             prefs.edit().putString(C.THANKS_FOR_UPDATING_VERSION, thanksForUpdatingLatestVersion)
249                     .commit();
250         }
251
252         registerReceiver(broadcastReceiver, new IntentFilter(
253                 DownloadManager.ACTION_DOWNLOAD_COMPLETE));
254
255         setMyListAdapater();
256         registerForContextMenu(getListView());
257
258         final File dictDir = application.getDictDir();
259         if (!dictDir.canRead() || !dictDir.canExecute()) {
260             blockAutoLaunch = true;
261
262             AlertDialog.Builder builder = new AlertDialog.Builder(getListView().getContext());
263             builder.setTitle(getString(R.string.error));
264             builder.setMessage(getString(
265                     R.string.unableToReadDictionaryDir,
266                     dictDir.getAbsolutePath(),
267                     Environment.getExternalStorageDirectory()));
268             builder.setNeutralButton("Close", null);
269             builder.create().show();
270         }
271
272         onCreateSetupActionBar();
273     }
274
275     private void onCreateSetupActionBar() {
276         ActionBar actionBar = getSupportActionBar();
277         actionBar.setDisplayShowTitleEnabled(false);
278         actionBar.setDisplayShowHomeEnabled(false);
279         actionBar.setDisplayHomeAsUpEnabled(false);
280
281         filterSearchView = new SearchView(getSupportActionBar().getThemedContext());
282         filterSearchView.setIconifiedByDefault(false);
283         // filterSearchView.setIconified(false); // puts the magnifying glass in
284         // the
285         // wrong place.
286         filterSearchView.setQueryHint(getString(R.string.searchText));
287         filterSearchView.setSubmitButtonEnabled(false);
288         FrameLayout.LayoutParams lp = new FrameLayout.LayoutParams(FrameLayout.LayoutParams.WRAP_CONTENT,
289                 FrameLayout.LayoutParams.WRAP_CONTENT);
290         filterSearchView.setLayoutParams(lp);
291         filterSearchView.setImeOptions(
292                 EditorInfo.IME_ACTION_DONE |
293                         EditorInfo.IME_FLAG_NO_EXTRACT_UI |
294                         // EditorInfo.IME_FLAG_NO_FULLSCREEN | // Requires API
295                         // 11
296                         EditorInfo.TYPE_TEXT_FLAG_NO_SUGGESTIONS);
297
298         filterSearchView.setOnQueryTextListener(new OnQueryTextListener() {
299             @Override
300             public boolean onQueryTextSubmit(String query) {
301                 filterSearchView.clearFocus();
302                 return false;
303             }
304
305             @Override
306             public boolean onQueryTextChange(String filterText) {
307                 setMyListAdapater();
308                 return true;
309             }
310         });
311         filterSearchView.setFocusable(true);
312
313         actionBar.setCustomView(filterSearchView);
314         actionBar.setDisplayShowCustomEnabled(true);
315
316         // Avoid wasting space on large left inset
317         Toolbar tb = (Toolbar)filterSearchView.getParent();
318         tb.setContentInsetsRelative(0, 0);
319     }
320
321     @Override
322     public void onDestroy() {
323         super.onDestroy();
324         unregisterReceiver(broadcastReceiver);
325     }
326
327     private static int copyStream(final InputStream in, final OutputStream out)
328             throws IOException {
329         int bytesRead;
330         final byte[] bytes = new byte[1024 * 16];
331         while ((bytesRead = in.read(bytes)) != -1) {
332             out.write(bytes, 0, bytesRead);
333         }
334         in.close();
335         out.close();
336         return bytesRead;
337     }
338
339     @Override
340     protected void onStart() {
341         super.onStart();
342         uiHandler = new Handler();
343     }
344
345     @Override
346     protected void onStop() {
347         super.onStop();
348         uiHandler = null;
349     }
350
351     @Override
352     protected void onResume() {
353         super.onResume();
354
355         if (PreferenceActivity.prefsMightHaveChanged) {
356             PreferenceActivity.prefsMightHaveChanged = false;
357             finish();
358             startActivity(getIntent());
359         }
360
361         final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
362         showDownloadable.setChecked(prefs.getBoolean(C.SHOW_DOWNLOADABLE, true));
363
364         if (!blockAutoLaunch &&
365                 getIntent().getBooleanExtra(C.CAN_AUTO_LAUNCH_DICT, true) &&
366                 prefs.contains(C.DICT_FILE) &&
367                 prefs.contains(C.INDEX_SHORT_NAME)) {
368             Log.d(LOG, "Skipping DictionaryManager, going straight to dictionary.");
369             startActivity(DictionaryActivity.getLaunchIntent(getApplicationContext(),
370                     new File(prefs.getString(C.DICT_FILE, "")),
371                     prefs.getString(C.INDEX_SHORT_NAME, ""),
372                     prefs.getString(C.SEARCH_TOKEN, "")));
373             finish();
374             return;
375         }
376
377         // Remove the active dictionary from the prefs so we won't autolaunch
378         // next time.
379         final Editor editor = prefs.edit();
380         editor.remove(C.DICT_FILE);
381         editor.remove(C.INDEX_SHORT_NAME);
382         editor.remove(C.SEARCH_TOKEN);
383         editor.commit();
384
385         application.backgroundUpdateDictionaries(dictionaryUpdater);
386
387         setMyListAdapater();
388     }
389
390     @Override
391     public boolean onCreateOptionsMenu(final Menu menu) {
392         application.onCreateGlobalOptionsMenu(this, menu);
393         return true;
394     }
395
396     @Override
397     public void onCreateContextMenu(final ContextMenu menu, final View view,
398             final ContextMenuInfo menuInfo) {
399         super.onCreateContextMenu(menu, view, menuInfo);
400         Log.d(LOG, "onCreateContextMenu, " + menuInfo);
401
402         final AdapterContextMenuInfo adapterContextMenuInfo =
403                 (AdapterContextMenuInfo) menuInfo;
404         final int position = adapterContextMenuInfo.position;
405         final MyListAdapter.Row row = (MyListAdapter.Row) getListAdapter().getItem(position);
406
407         if (row.dictionaryInfo == null) {
408             return;
409         }
410
411         if (position > 0 && row.onDevice) {
412             final android.view.MenuItem moveToTopMenuItem =
413                     menu.add(R.string.moveToTop);
414             moveToTopMenuItem.setOnMenuItemClickListener(new
415                     android.view.MenuItem.OnMenuItemClickListener() {
416                         @Override
417                         public boolean onMenuItemClick(android.view.MenuItem item) {
418                             application.moveDictionaryToTop(row.dictionaryInfo);
419                             setMyListAdapater();
420                             return true;
421                         }
422                     });
423         }
424
425         if (row.onDevice) {
426             final android.view.MenuItem deleteMenuItem = menu.add(R.string.deleteDictionary);
427             deleteMenuItem
428                     .setOnMenuItemClickListener(new android.view.MenuItem.OnMenuItemClickListener() {
429                         @Override
430                         public boolean onMenuItemClick(android.view.MenuItem item) {
431                             application.deleteDictionary(row.dictionaryInfo);
432                             setMyListAdapater();
433                             return true;
434                         }
435                     });
436         }
437     }
438
439     private void onShowDownloadableChanged() {
440         setMyListAdapater();
441         Editor prefs = PreferenceManager.getDefaultSharedPreferences(this).edit();
442         prefs.putBoolean(C.SHOW_DOWNLOADABLE, showDownloadable.isChecked());
443         prefs.commit();
444     }
445
446     class MyListAdapter extends BaseAdapter {
447
448         List<DictionaryInfo> dictionariesOnDevice;
449         List<DictionaryInfo> downloadableDictionaries;
450
451         class Row {
452             DictionaryInfo dictionaryInfo;
453             boolean onDevice;
454
455             private Row(DictionaryInfo dictinoaryInfo, boolean onDevice) {
456                 this.dictionaryInfo = dictinoaryInfo;
457                 this.onDevice = onDevice;
458             }
459         }
460
461         private MyListAdapter(final String[] filters) {
462             dictionariesOnDevice = application.getDictionariesOnDevice(filters);
463             if (showDownloadable.isChecked()) {
464                 downloadableDictionaries = application.getDownloadableDictionaries(filters);
465             } else {
466                 downloadableDictionaries = Collections.emptyList();
467             }
468         }
469
470         @Override
471         public int getCount() {
472             return 2 + dictionariesOnDevice.size() + downloadableDictionaries.size();
473         }
474
475         @Override
476         public Row getItem(int position) {
477             if (position == 0) {
478                 return new Row(null, true);
479             }
480             position -= 1;
481
482             if (position < dictionariesOnDevice.size()) {
483                 return new Row(dictionariesOnDevice.get(position), true);
484             }
485             position -= dictionariesOnDevice.size();
486
487             if (position == 0) {
488                 return new Row(null, false);
489             }
490             position -= 1;
491
492             assert position < downloadableDictionaries.size();
493             return new Row(downloadableDictionaries.get(position), false);
494         }
495
496         @Override
497         public long getItemId(int position) {
498             return position;
499         }
500
501         @Override
502         public View getView(int position, View convertView, ViewGroup parent) {
503             if (convertView instanceof LinearLayout &&
504                     convertView != dictionariesOnDeviceHeaderRow &&
505                     convertView != downloadableDictionariesHeaderRow) {
506                 /*
507                  * This is done to try to avoid leaking memory that used to
508                  * happen on Android 4.0.3
509                  */
510                 ((LinearLayout) convertView).removeAllViews();
511             }
512
513             final Row row = getItem(position);
514
515             if (row.onDevice) {
516                 if (row.dictionaryInfo == null) {
517                     return dictionariesOnDeviceHeaderRow;
518                 }
519                 return createDictionaryRow(row.dictionaryInfo, parent, true);
520             }
521
522             if (row.dictionaryInfo == null) {
523                 return downloadableDictionariesHeaderRow;
524             }
525             return createDictionaryRow(row.dictionaryInfo, parent, false);
526         }
527
528     }
529
530     private void setMyListAdapater() {
531         final String filter = filterSearchView == null ? "" : filterSearchView.getQuery()
532                 .toString();
533         final String[] filters = filter.trim().toLowerCase().split("(\\s|-)+");
534         setListAdapter(new MyListAdapter(filters));
535     }
536
537     private View createDictionaryRow(final DictionaryInfo dictionaryInfo,
538             final ViewGroup parent, boolean canLaunch) {
539
540         View row = LayoutInflater.from(parent.getContext()).inflate(
541                 R.layout.dictionary_manager_row, parent, false);
542         final TextView name = (TextView) row.findViewById(R.id.dictionaryName);
543         final TextView details = (TextView) row.findViewById(R.id.dictionaryDetails);
544         name.setText(application.getDictionaryName(dictionaryInfo.uncompressedFilename));
545
546         final boolean updateAvailable = application.updateAvailable(dictionaryInfo);
547         final Button downloadButton = (Button) row.findViewById(R.id.downloadButton);
548         final DictionaryInfo downloadable = application.getDownloadable(dictionaryInfo.uncompressedFilename);
549         boolean broken = false;
550         if (!dictionaryInfo.isValid()) {
551             broken = true;
552             canLaunch = false;
553         }
554         if (downloadable != null && (!canLaunch || updateAvailable)) {
555             downloadButton
556                     .setText(getString(
557                             R.string.downloadButton,
558                             downloadable.zipBytes / 1024.0 / 1024.0));
559             downloadButton.setMinWidth(application.languageButtonPixels * 3 / 2);
560             downloadButton.setOnClickListener(new OnClickListener() {
561                 @Override
562                 public void onClick(View arg0) {
563                     downloadDictionary(downloadable.downloadUrl, downloadable.zipBytes, downloadButton);
564                 }
565             });
566         } else {
567             downloadButton.setVisibility(View.INVISIBLE);
568         }
569
570         LinearLayout buttons = (LinearLayout) row.findViewById(R.id.dictionaryLauncherButtons);
571         final List<IndexInfo> sortedIndexInfos = application
572                 .sortedIndexInfos(dictionaryInfo.indexInfos);
573         final StringBuilder builder = new StringBuilder();
574         if (updateAvailable) {
575             builder.append(getString(R.string.updateAvailable));
576         }
577         for (IndexInfo indexInfo : sortedIndexInfos) {
578             final View button = application.createButton(buttons.getContext(), dictionaryInfo,
579                     indexInfo);
580             buttons.addView(button);
581
582             if (canLaunch) {
583                 button.setOnClickListener(
584                         new IntentLauncher(buttons.getContext(),
585                                 DictionaryActivity.getLaunchIntent(getApplicationContext(),
586                                         application.getPath(dictionaryInfo.uncompressedFilename),
587                                         indexInfo.shortName, "")));
588
589             } else {
590                 button.setEnabled(false);
591             }
592             if (builder.length() != 0) {
593                 builder.append("; ");
594             }
595             builder.append(getString(R.string.indexInfo, indexInfo.shortName,
596                     indexInfo.mainTokenCount));
597         }
598         builder.append("; ");
599         builder.append(getString(R.string.downloadButton, dictionaryInfo.uncompressedBytes / 1024.0 / 1024.0));
600         if (broken) {
601             name.setText("Broken: " + application.getDictionaryName(dictionaryInfo.uncompressedFilename));
602             builder.append("; Cannot be used, redownload, check hardware/file system");
603             // Allow deleting, but cannot open
604             row.setLongClickable(true);
605         }
606         details.setText(builder.toString());
607
608         if (canLaunch) {
609             row.setClickable(true);
610             row.setOnClickListener(new IntentLauncher(parent.getContext(),
611                     DictionaryActivity.getLaunchIntent(getApplicationContext(),
612                             application.getPath(dictionaryInfo.uncompressedFilename),
613                             dictionaryInfo.indexInfos.get(0).shortName, "")));
614             row.setFocusable(true);
615             row.setLongClickable(true);
616         }
617         row.setBackgroundResource(android.R.drawable.menuitem_background);
618
619         return row;
620     }
621
622     private void downloadDictionary(final String downloadUrl, long bytes, Button downloadButton) {
623         DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
624         final DownloadManager.Query query = new DownloadManager.Query();
625         query.setFilterByStatus(DownloadManager.STATUS_PAUSED | DownloadManager.STATUS_PENDING | DownloadManager.STATUS_RUNNING);
626         final Cursor cursor = downloadManager.query(query);
627
628         // Due to a bug, cursor is null instead of empty when
629         // the download manager is disabled.
630         if (cursor == null) {
631             new AlertDialog.Builder(DictionaryManagerActivity.this).setTitle(getString(R.string.error))
632                     .setMessage(getString(R.string.downloadFailed, R.string.downloadManagerQueryFailed))
633                     .setNeutralButton("Close", null).show();
634             return;
635         }
636
637         while (cursor.moveToNext()) {
638             if (downloadUrl.equals(cursor.getString(cursor.getColumnIndex(DownloadManager.COLUMN_URI))))
639                 break;
640         }
641         if (!cursor.isAfterLast()) {
642             downloadManager.remove(cursor.getLong(cursor.getColumnIndex(DownloadManager.COLUMN_ID)));
643             downloadButton
644                     .setText(getString(
645                             R.string.downloadButton,
646                             bytes / 1024.0 / 1024.0));
647             cursor.close();
648             return;
649         }
650         cursor.close();
651         Request request = new Request(
652                 Uri.parse(downloadUrl));
653         try {
654             final String destFile = new File(new URL(downloadUrl).getFile())
655                     .getName();
656             Log.d(LOG, "Downloading to: " + destFile);
657
658             try {
659                 request.setDestinationInExternalFilesDir(getApplicationContext(), null, destFile);
660             } catch (IllegalStateException e) {
661                 request.setDestinationUri(Uri.fromFile(new File(Environment
662                         .getExternalStorageDirectory(), destFile)));
663             }
664         } catch (MalformedURLException e) {
665             throw new RuntimeException(e);
666         }
667         downloadManager.enqueue(request);
668         downloadButton.setText("X");
669     }
670
671 }