]> gitweb.fperrin.net Git - Dictionary.git/blob - src/com/hughes/android/dictionary/DictionaryManagerActivity.java
Fix resource leaks due to missing close().
[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                 try {
168                     ZipFile zipFile = new ZipFile(localZipFile);
169                     final ZipEntry zipEntry = zipFile.entries().nextElement();
170                     Log.d(LOG, "Unzipping entry: " + zipEntry.getName());
171                     final InputStream zipIn = zipFile.getInputStream(zipEntry);
172                     File targetFile = new File(application.getDictDir(), zipEntry.getName());
173                     if (targetFile.exists()) {
174                         targetFile.renameTo(new File(targetFile.getAbsolutePath().replace(".quickdic", ".bak.quickdic")));
175                         targetFile = new File(application.getDictDir(), zipEntry.getName());
176                     }
177                     final OutputStream zipOut = new FileOutputStream(targetFile);
178                     copyStream(zipIn, zipOut);
179                     zipFile.close();
180                     zipOut.close();
181                     application.backgroundUpdateDictionaries(dictionaryUpdater);
182                     Toast.makeText(context, getString(R.string.installationFinished, dest),
183                             Toast.LENGTH_LONG).show();
184                 } catch (Exception e) {
185                     String msg = getString(R.string.unzippingFailed, dest);
186                     File dir = application.getDictDir();
187                     if (!dir.canWrite() || !application.checkFileCreate(dir)) {
188                         msg = getString(R.string.notWritable, dir.getAbsolutePath());
189                     }
190                     new AlertDialog.Builder(context).setTitle(getString(R.string.error)).setMessage(msg).setNeutralButton("Close", null).show();
191                     Log.e(LOG, "Failed to unzip.", e);
192                 } finally {
193                     localZipFile.delete();
194                 }
195             }
196         }
197     };
198
199     public static Intent getLaunchIntent(Context c) {
200         final Intent intent = new Intent(c, DictionaryManagerActivity.class);
201         intent.putExtra(C.CAN_AUTO_LAUNCH_DICT, false);
202         return intent;
203     }
204
205     @Override
206     public void onCreate(Bundle savedInstanceState) {
207         // This must be first, otherwise the actiona bar doesn't get
208         // styled properly.
209         setTheme(((DictionaryApplication) getApplication()).getSelectedTheme().themeId);
210
211         super.onCreate(savedInstanceState);
212         Log.d(LOG, "onCreate:" + this);
213
214         application = (DictionaryApplication) getApplication();
215
216         blockAutoLaunch = false;
217
218         // UI init.
219         setContentView(R.layout.dictionary_manager_activity);
220
221         dictionariesOnDeviceHeaderRow = (LinearLayout) LayoutInflater.from(
222                 getListView().getContext()).inflate(
223                 R.layout.dictionary_manager_header_row_on_device, getListView(), false);
224
225         downloadableDictionariesHeaderRow = (LinearLayout) LayoutInflater.from(
226                 getListView().getContext()).inflate(
227                 R.layout.dictionary_manager_header_row_downloadable, getListView(), false);
228
229         showDownloadable = (ToggleButton) downloadableDictionariesHeaderRow
230                 .findViewById(R.id.hideDownloadable);
231         showDownloadable.setOnCheckedChangeListener(new OnCheckedChangeListener() {
232             @Override
233             public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
234                 onShowDownloadableChanged();
235             }
236         });
237
238         final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
239         final String thanksForUpdatingLatestVersion = getString(R.string.thanksForUpdatingVersion);
240         if (!prefs.getString(C.THANKS_FOR_UPDATING_VERSION, "").equals(
241                 thanksForUpdatingLatestVersion)) {
242             blockAutoLaunch = true;
243             startActivity(HtmlDisplayActivity.getWhatsNewLaunchIntent(getApplicationContext()));
244             prefs.edit().putString(C.THANKS_FOR_UPDATING_VERSION, thanksForUpdatingLatestVersion)
245                     .commit();
246         }
247
248         registerReceiver(broadcastReceiver, new IntentFilter(
249                 DownloadManager.ACTION_DOWNLOAD_COMPLETE));
250
251         setMyListAdapater();
252         registerForContextMenu(getListView());
253
254         final File dictDir = application.getDictDir();
255         if (!dictDir.canRead() || !dictDir.canExecute()) {
256             blockAutoLaunch = true;
257
258             AlertDialog.Builder builder = new AlertDialog.Builder(getListView().getContext());
259             builder.setTitle(getString(R.string.error));
260             builder.setMessage(getString(
261                     R.string.unableToReadDictionaryDir,
262                     dictDir.getAbsolutePath(),
263                     Environment.getExternalStorageDirectory()));
264             builder.setNeutralButton("Close", null);
265             builder.create().show();
266         }
267
268         onCreateSetupActionBar();
269     }
270
271     private void onCreateSetupActionBar() {
272         ActionBar actionBar = getSupportActionBar();
273         actionBar.setDisplayShowTitleEnabled(false);
274         actionBar.setDisplayShowHomeEnabled(false);
275         actionBar.setDisplayHomeAsUpEnabled(false);
276
277         filterSearchView = new SearchView(getSupportActionBar().getThemedContext());
278         filterSearchView.setIconifiedByDefault(false);
279         // filterSearchView.setIconified(false); // puts the magnifying glass in
280         // the
281         // wrong place.
282         filterSearchView.setQueryHint(getString(R.string.searchText));
283         filterSearchView.setSubmitButtonEnabled(false);
284         FrameLayout.LayoutParams lp = new FrameLayout.LayoutParams(FrameLayout.LayoutParams.WRAP_CONTENT,
285                 FrameLayout.LayoutParams.WRAP_CONTENT);
286         filterSearchView.setLayoutParams(lp);
287         filterSearchView.setImeOptions(
288                 EditorInfo.IME_ACTION_DONE |
289                         EditorInfo.IME_FLAG_NO_EXTRACT_UI |
290                         // EditorInfo.IME_FLAG_NO_FULLSCREEN | // Requires API
291                         // 11
292                         EditorInfo.TYPE_TEXT_FLAG_NO_SUGGESTIONS);
293
294         filterSearchView.setOnQueryTextListener(new OnQueryTextListener() {
295             @Override
296             public boolean onQueryTextSubmit(String query) {
297                 filterSearchView.clearFocus();
298                 return false;
299             }
300
301             @Override
302             public boolean onQueryTextChange(String filterText) {
303                 setMyListAdapater();
304                 return true;
305             }
306         });
307         filterSearchView.setFocusable(true);
308
309         actionBar.setCustomView(filterSearchView);
310         actionBar.setDisplayShowCustomEnabled(true);
311
312         // Avoid wasting space on large left inset
313         Toolbar tb = (Toolbar)filterSearchView.getParent();
314         tb.setContentInsetsRelative(0, 0);
315     }
316
317     @Override
318     public void onDestroy() {
319         super.onDestroy();
320         unregisterReceiver(broadcastReceiver);
321     }
322
323     private static int copyStream(final InputStream in, final OutputStream out)
324             throws IOException {
325         int bytesRead;
326         final byte[] bytes = new byte[1024 * 16];
327         while ((bytesRead = in.read(bytes)) != -1) {
328             out.write(bytes, 0, bytesRead);
329         }
330         in.close();
331         out.close();
332         return bytesRead;
333     }
334
335     @Override
336     protected void onStart() {
337         super.onStart();
338         uiHandler = new Handler();
339     }
340
341     @Override
342     protected void onStop() {
343         super.onStop();
344         uiHandler = null;
345     }
346
347     @Override
348     protected void onResume() {
349         super.onResume();
350
351         if (PreferenceActivity.prefsMightHaveChanged) {
352             PreferenceActivity.prefsMightHaveChanged = false;
353             finish();
354             startActivity(getIntent());
355         }
356
357         final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
358         showDownloadable.setChecked(prefs.getBoolean(C.SHOW_DOWNLOADABLE, true));
359
360         if (!blockAutoLaunch &&
361                 getIntent().getBooleanExtra(C.CAN_AUTO_LAUNCH_DICT, true) &&
362                 prefs.contains(C.DICT_FILE) &&
363                 prefs.contains(C.INDEX_SHORT_NAME)) {
364             Log.d(LOG, "Skipping DictionaryManager, going straight to dictionary.");
365             startActivity(DictionaryActivity.getLaunchIntent(getApplicationContext(),
366                     new File(prefs.getString(C.DICT_FILE, "")),
367                     prefs.getString(C.INDEX_SHORT_NAME, ""),
368                     prefs.getString(C.SEARCH_TOKEN, "")));
369             finish();
370             return;
371         }
372
373         // Remove the active dictionary from the prefs so we won't autolaunch
374         // next time.
375         final Editor editor = prefs.edit();
376         editor.remove(C.DICT_FILE);
377         editor.remove(C.INDEX_SHORT_NAME);
378         editor.remove(C.SEARCH_TOKEN);
379         editor.commit();
380
381         application.backgroundUpdateDictionaries(dictionaryUpdater);
382
383         setMyListAdapater();
384     }
385
386     @Override
387     public boolean onCreateOptionsMenu(final Menu menu) {
388         application.onCreateGlobalOptionsMenu(this, menu);
389         return true;
390     }
391
392     @Override
393     public void onCreateContextMenu(final ContextMenu menu, final View view,
394             final ContextMenuInfo menuInfo) {
395         super.onCreateContextMenu(menu, view, menuInfo);
396         Log.d(LOG, "onCreateContextMenu, " + menuInfo);
397
398         final AdapterContextMenuInfo adapterContextMenuInfo =
399                 (AdapterContextMenuInfo) menuInfo;
400         final int position = adapterContextMenuInfo.position;
401         final MyListAdapter.Row row = (MyListAdapter.Row) getListAdapter().getItem(position);
402
403         if (row.dictionaryInfo == null) {
404             return;
405         }
406
407         if (position > 0 && row.onDevice) {
408             final android.view.MenuItem moveToTopMenuItem =
409                     menu.add(R.string.moveToTop);
410             moveToTopMenuItem.setOnMenuItemClickListener(new
411                     android.view.MenuItem.OnMenuItemClickListener() {
412                         @Override
413                         public boolean onMenuItemClick(android.view.MenuItem item) {
414                             application.moveDictionaryToTop(row.dictionaryInfo);
415                             setMyListAdapater();
416                             return true;
417                         }
418                     });
419         }
420
421         if (row.onDevice) {
422             final android.view.MenuItem deleteMenuItem = menu.add(R.string.deleteDictionary);
423             deleteMenuItem
424                     .setOnMenuItemClickListener(new android.view.MenuItem.OnMenuItemClickListener() {
425                         @Override
426                         public boolean onMenuItemClick(android.view.MenuItem item) {
427                             application.deleteDictionary(row.dictionaryInfo);
428                             setMyListAdapater();
429                             return true;
430                         }
431                     });
432         }
433     }
434
435     private void onShowDownloadableChanged() {
436         setMyListAdapater();
437         Editor prefs = PreferenceManager.getDefaultSharedPreferences(this).edit();
438         prefs.putBoolean(C.SHOW_DOWNLOADABLE, showDownloadable.isChecked());
439         prefs.commit();
440     }
441
442     class MyListAdapter extends BaseAdapter {
443
444         List<DictionaryInfo> dictionariesOnDevice;
445         List<DictionaryInfo> downloadableDictionaries;
446
447         class Row {
448             DictionaryInfo dictionaryInfo;
449             boolean onDevice;
450
451             private Row(DictionaryInfo dictinoaryInfo, boolean onDevice) {
452                 this.dictionaryInfo = dictinoaryInfo;
453                 this.onDevice = onDevice;
454             }
455         }
456
457         private MyListAdapter(final String[] filters) {
458             dictionariesOnDevice = application.getDictionariesOnDevice(filters);
459             if (showDownloadable.isChecked()) {
460                 downloadableDictionaries = application.getDownloadableDictionaries(filters);
461             } else {
462                 downloadableDictionaries = Collections.emptyList();
463             }
464         }
465
466         @Override
467         public int getCount() {
468             return 2 + dictionariesOnDevice.size() + downloadableDictionaries.size();
469         }
470
471         @Override
472         public Row getItem(int position) {
473             if (position == 0) {
474                 return new Row(null, true);
475             }
476             position -= 1;
477
478             if (position < dictionariesOnDevice.size()) {
479                 return new Row(dictionariesOnDevice.get(position), true);
480             }
481             position -= dictionariesOnDevice.size();
482
483             if (position == 0) {
484                 return new Row(null, false);
485             }
486             position -= 1;
487
488             assert position < downloadableDictionaries.size();
489             return new Row(downloadableDictionaries.get(position), false);
490         }
491
492         @Override
493         public long getItemId(int position) {
494             return position;
495         }
496
497         @Override
498         public View getView(int position, View convertView, ViewGroup parent) {
499             if (convertView instanceof LinearLayout &&
500                     convertView != dictionariesOnDeviceHeaderRow &&
501                     convertView != downloadableDictionariesHeaderRow) {
502                 /*
503                  * This is done to try to avoid leaking memory that used to
504                  * happen on Android 4.0.3
505                  */
506                 ((LinearLayout) convertView).removeAllViews();
507             }
508
509             final Row row = getItem(position);
510
511             if (row.onDevice) {
512                 if (row.dictionaryInfo == null) {
513                     return dictionariesOnDeviceHeaderRow;
514                 }
515                 return createDictionaryRow(row.dictionaryInfo, parent, true);
516             }
517
518             if (row.dictionaryInfo == null) {
519                 return downloadableDictionariesHeaderRow;
520             }
521             return createDictionaryRow(row.dictionaryInfo, parent, false);
522         }
523
524     }
525
526     private void setMyListAdapater() {
527         final String filter = filterSearchView == null ? "" : filterSearchView.getQuery()
528                 .toString();
529         final String[] filters = filter.trim().toLowerCase().split("(\\s|-)+");
530         setListAdapter(new MyListAdapter(filters));
531     }
532
533     private View createDictionaryRow(final DictionaryInfo dictionaryInfo,
534             final ViewGroup parent, boolean canLaunch) {
535
536         View row = LayoutInflater.from(parent.getContext()).inflate(
537                 R.layout.dictionary_manager_row, parent, false);
538         final TextView name = (TextView) row.findViewById(R.id.dictionaryName);
539         final TextView details = (TextView) row.findViewById(R.id.dictionaryDetails);
540         name.setText(application.getDictionaryName(dictionaryInfo.uncompressedFilename));
541
542         final boolean updateAvailable = application.updateAvailable(dictionaryInfo);
543         final Button downloadButton = (Button) row.findViewById(R.id.downloadButton);
544         final DictionaryInfo downloadable = application.getDownloadable(dictionaryInfo.uncompressedFilename);
545         boolean broken = false;
546         if (!dictionaryInfo.isValid()) {
547             broken = true;
548             canLaunch = false;
549         }
550         if (downloadable != null && (!canLaunch || updateAvailable)) {
551             downloadButton
552                     .setText(getString(
553                             R.string.downloadButton,
554                             downloadable.zipBytes / 1024.0 / 1024.0));
555             downloadButton.setMinWidth(application.languageButtonPixels * 3 / 2);
556             downloadButton.setOnClickListener(new OnClickListener() {
557                 @Override
558                 public void onClick(View arg0) {
559                     downloadDictionary(downloadable.downloadUrl, downloadable.zipBytes, downloadButton);
560                 }
561             });
562         } else {
563             downloadButton.setVisibility(View.INVISIBLE);
564         }
565
566         LinearLayout buttons = (LinearLayout) row.findViewById(R.id.dictionaryLauncherButtons);
567         final List<IndexInfo> sortedIndexInfos = application
568                 .sortedIndexInfos(dictionaryInfo.indexInfos);
569         final StringBuilder builder = new StringBuilder();
570         if (updateAvailable) {
571             builder.append(getString(R.string.updateAvailable));
572         }
573         for (IndexInfo indexInfo : sortedIndexInfos) {
574             final View button = application.createButton(buttons.getContext(), dictionaryInfo,
575                     indexInfo);
576             buttons.addView(button);
577
578             if (canLaunch) {
579                 button.setOnClickListener(
580                         new IntentLauncher(buttons.getContext(),
581                                 DictionaryActivity.getLaunchIntent(getApplicationContext(),
582                                         application.getPath(dictionaryInfo.uncompressedFilename),
583                                         indexInfo.shortName, "")));
584
585             } else {
586                 button.setEnabled(false);
587             }
588             if (builder.length() != 0) {
589                 builder.append("; ");
590             }
591             builder.append(getString(R.string.indexInfo, indexInfo.shortName,
592                     indexInfo.mainTokenCount));
593         }
594         builder.append("; ");
595         builder.append(getString(R.string.downloadButton, dictionaryInfo.uncompressedBytes / 1024.0 / 1024.0));
596         if (broken) {
597             name.setText("Broken: " + application.getDictionaryName(dictionaryInfo.uncompressedFilename));
598             builder.append("; Cannot be used, redownload, check hardware/file system");
599             // Allow deleting, but cannot open
600             row.setLongClickable(true);
601         }
602         details.setText(builder.toString());
603
604         if (canLaunch) {
605             row.setClickable(true);
606             row.setOnClickListener(new IntentLauncher(parent.getContext(),
607                     DictionaryActivity.getLaunchIntent(getApplicationContext(),
608                             application.getPath(dictionaryInfo.uncompressedFilename),
609                             dictionaryInfo.indexInfos.get(0).shortName, "")));
610             row.setFocusable(true);
611             row.setLongClickable(true);
612         }
613         row.setBackgroundResource(android.R.drawable.menuitem_background);
614
615         return row;
616     }
617
618     private void downloadDictionary(final String downloadUrl, long bytes, Button downloadButton) {
619         DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
620         final DownloadManager.Query query = new DownloadManager.Query();
621         query.setFilterByStatus(DownloadManager.STATUS_PAUSED | DownloadManager.STATUS_PENDING | DownloadManager.STATUS_RUNNING);
622         final Cursor cursor = downloadManager.query(query);
623
624         // Due to a bug, cursor is null instead of empty when
625         // the download manager is disabled.
626         if (cursor == null) {
627             new AlertDialog.Builder(DictionaryManagerActivity.this).setTitle(getString(R.string.error))
628                     .setMessage(getString(R.string.downloadFailed, R.string.downloadManagerQueryFailed))
629                     .setNeutralButton("Close", null).show();
630             return;
631         }
632
633         while (cursor.moveToNext()) {
634             if (downloadUrl.equals(cursor.getString(cursor.getColumnIndex(DownloadManager.COLUMN_URI))))
635                 break;
636         }
637         if (!cursor.isAfterLast()) {
638             downloadManager.remove(cursor.getLong(cursor.getColumnIndex(DownloadManager.COLUMN_ID)));
639             downloadButton
640                     .setText(getString(
641                             R.string.downloadButton,
642                             bytes / 1024.0 / 1024.0));
643             cursor.close();
644             return;
645         }
646         cursor.close();
647         Request request = new Request(
648                 Uri.parse(downloadUrl));
649         try {
650             final String destFile = new File(new URL(downloadUrl).getFile())
651                     .getName();
652             Log.d(LOG, "Downloading to: " + destFile);
653
654             try {
655                 request.setDestinationInExternalFilesDir(getApplicationContext(), null, destFile);
656             } catch (IllegalStateException e) {
657                 request.setDestinationUri(Uri.fromFile(new File(Environment
658                         .getExternalStorageDirectory(), destFile)));
659             }
660         } catch (MalformedURLException e) {
661             throw new RuntimeException(e);
662         }
663         downloadManager.enqueue(request);
664         downloadButton.setText("X");
665     }
666
667 }