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