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