-
Notifications
You must be signed in to change notification settings - Fork 61
/
SearchResultDetailFragment.java
1485 lines (1342 loc) · 59.9 KB
/
SearchResultDetailFragment.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package de.geeksfactory.opacclient.frontend;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.net.ConnectivityManager;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import androidx.preference.PreferenceManager;
import android.print.PrintAttributes;
import android.print.PrintDocumentAdapter;
import android.print.PrintManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.animation.AnimationUtils;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.CheckBox;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.material.appbar.AppBarLayout;
import com.google.android.material.appbar.CollapsingToolbarLayout;
import org.joda.time.LocalDate;
import org.joda.time.format.DateTimeFormat;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.List;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.widget.Toolbar;
import androidx.core.net.ConnectivityManagerCompat;
import androidx.fragment.app.Fragment;
import androidx.palette.graphics.Palette;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import de.geeksfactory.opacclient.OpacClient;
import de.geeksfactory.opacclient.R;
import de.geeksfactory.opacclient.apis.EbookServiceApi;
import de.geeksfactory.opacclient.apis.EbookServiceApi.BookingResult;
import de.geeksfactory.opacclient.apis.OpacApi;
import de.geeksfactory.opacclient.apis.OpacApi.MultiStepResult;
import de.geeksfactory.opacclient.apis.OpacApi.ReservationResult;
import de.geeksfactory.opacclient.frontend.MultiStepResultHelper.Callback;
import de.geeksfactory.opacclient.frontend.MultiStepResultHelper.StepTask;
import de.geeksfactory.opacclient.networking.CoverDownloadTask;
import de.geeksfactory.opacclient.objects.Account;
import de.geeksfactory.opacclient.objects.Copy;
import de.geeksfactory.opacclient.objects.CoverHolder;
import de.geeksfactory.opacclient.objects.Detail;
import de.geeksfactory.opacclient.objects.DetailedItem;
import de.geeksfactory.opacclient.objects.SearchResult;
import de.geeksfactory.opacclient.storage.AccountDataSource;
import de.geeksfactory.opacclient.storage.PreferenceDataSource;
import de.geeksfactory.opacclient.storage.StarDataSource;
import de.geeksfactory.opacclient.ui.AppCompatProgressDialog;
import de.geeksfactory.opacclient.ui.WhitenessUtils;
import de.geeksfactory.opacclient.utils.BitmapUtils;
import de.geeksfactory.opacclient.utils.CompatibilityUtils;
import de.geeksfactory.opacclient.utils.ErrorReporter;
import de.geeksfactory.opacclient.utils.PrintUtils;
import su.j2e.rvjoiner.JoinableAdapter;
import su.j2e.rvjoiner.JoinableLayout;
import su.j2e.rvjoiner.RvJoiner;
/**
* A fragment representing a single SearchResult detail screen. This fragment is either contained in
* a {@link SearchResultListActivity} in two-pane mode (on tablets) or a {@link
* SearchResultDetailActivity} on handsets.
*/
public class SearchResultDetailFragment extends Fragment
implements Toolbar.OnMenuItemClickListener {
/**
* The fragment argument representing the item ID that this fragment represents.
*/
public static final String ARG_ITEM_ID = "item_id";
public static final String ARG_ITEM_NR = "item_nr";
public static final String ARG_ITEM_COVER_BITMAP = "item_cover_bitmap";
public static final String ARG_ITEM_MEDIATYPE = "item_mediatype";
/**
* A dummy implementation of the {@link Callbacks} interface that does nothing. Used only when
* this fragment is not attached to an activity.
*/
private static Callbacks dummyCallbacks = new Callbacks() {
@Override
public void removeFragment() {
}
};
/**
* The fragment's current callback object, which is notified of list item clicks.
*/
private Callbacks callbacks = dummyCallbacks;
protected boolean back_button_visible = false;
protected boolean image_analyzed = false;
protected Toolbar toolbar;
protected ImageView ivCover;
protected FrameLayout coverWrapper;
protected View gradientBottom, gradientTop;
protected RecyclerView rvDetails;
protected ProgressBar progressBar;
protected FrameLayout errorView;
protected CollapsingToolbarLayout collapsingToolbar;
protected AppBarLayout appBarLayout;
/**
* The detailled item that this fragment represents.
*/
private DetailedItem item;
private String id;
private Integer nr;
private OpacClient app;
private View view;
private FetchTask ft;
private AppCompatProgressDialog dialog;
private AlertDialog adialog;
private boolean account_switched = false;
private boolean invalidated = false;
private boolean progress = false;
private Boolean[] cardAnimations;
/**
* Mandatory empty constructor for the fragment manager to instantiate the fragment (e.g. upon
* screen orientation changes).
*/
public SearchResultDetailFragment() {
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRetainInstance(true);
}
public void setProgress(boolean show, boolean animate) {
progress = show;
if (view != null) {
View content = rvDetails;
if (show) {
if (animate) {
progressBar.startAnimation(AnimationUtils.loadAnimation(
getActivity(), android.R.anim.fade_in));
content.startAnimation(AnimationUtils.loadAnimation(
getActivity(), android.R.anim.fade_out));
} else {
progressBar.clearAnimation();
content.clearAnimation();
}
progressBar.setVisibility(View.VISIBLE);
content.setVisibility(View.GONE);
} else {
if (animate) {
progressBar.startAnimation(AnimationUtils.loadAnimation(
getActivity(), android.R.anim.fade_out));
content.startAnimation(AnimationUtils.loadAnimation(
getActivity(), android.R.anim.fade_in));
} else {
progressBar.clearAnimation();
content.clearAnimation();
}
progressBar.setVisibility(View.GONE);
content.setVisibility(View.VISIBLE);
}
}
}
public void showConnectivityError() {
errorView.removeAllViews();
View connError = getActivity().getLayoutInflater().inflate(
R.layout.error_connectivity, errorView);
connError.findViewById(R.id.btRetry)
.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
errorView.removeAllViews();
reload();
}
});
progressBar.startAnimation(AnimationUtils.loadAnimation(getActivity(),
android.R.anim.fade_out));
rvDetails.startAnimation(AnimationUtils.loadAnimation(getActivity(),
android.R.anim.fade_out));
connError.startAnimation(AnimationUtils.loadAnimation(getActivity(),
android.R.anim.fade_in));
progressBar.setVisibility(View.GONE);
rvDetails.setVisibility(View.GONE);
connError.setVisibility(View.VISIBLE);
}
public void setProgress() {
setProgress(progress, false);
}
private void load(int nr, String id) {
setProgress(true, true);
this.id = id;
this.nr = nr;
ft = new FetchTask(nr, id);
ft.execute();
}
private void reload() {
load(nr, id);
}
@Override
public void onAttach(Context context) {
super.onAttach(context);
app = (OpacClient) context.getApplicationContext();
// Activities containing this fragment must implement its callbacks.
if (!(context instanceof Callbacks)) {
throw new IllegalStateException(
"Activity must implement fragment's callbacks.");
}
callbacks = (Callbacks) context;
}
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
if (item != null) {
display();
} else if (getArguments().containsKey(ARG_ITEM_ID)
|| getArguments().containsKey(ARG_ITEM_NR)) {
load(getArguments().getInt(ARG_ITEM_NR),
getArguments().getString(ARG_ITEM_ID));
}
}
@Override
public void onDetach() {
super.onDetach();
// Reset the active callbacks interface to the dummy implementation.
callbacks = dummyCallbacks;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_searchresult_detail,
container, false);
view = rootView;
findViews();
setHasOptionsMenu(false);
if (getActivity() instanceof SearchResultDetailActivity) {
// This applies on phones, where the Toolbar is also the
// main ActionBar of the Activity and needs a back button
toolbar.setNavigationIcon(R.drawable.ic_arrow_back_white_24dp);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
getActivity().supportFinishAfterTransition();
}
});
back_button_visible = true;
}
toolbar.inflateMenu(R.menu.search_result_details_activity);
refreshMenu(toolbar.getMenu());
toolbar.setOnMenuItemClickListener(this);
setRetainInstance(true);
setProgress();
if (getArguments().containsKey(ARG_ITEM_COVER_BITMAP)) {
Bitmap bitmap = getArguments().getParcelable(ARG_ITEM_COVER_BITMAP);
ivCover.setImageBitmap(bitmap);
analyzeCover(bitmap);
showCoverView(true);
} else {
showCoverView(false);
}
return rootView;
}
private void analyzeCover(Bitmap bitmap) {
try {
Palette.from(bitmap).generate(new Palette.PaletteAsyncListener() {
@Override
public void onGenerated(Palette palette) {
Palette.Swatch swatch = palette.getDarkVibrantSwatch();
if (swatch == null) swatch = palette.getDarkMutedSwatch();
if (swatch == null) swatch = palette.getLightVibrantSwatch();
if (swatch == null) swatch = palette.getLightMutedSwatch();
if (swatch == null && palette.getSwatches().size() > 0) {
swatch = palette.getSwatches().get(0);
}
if (swatch != null) {
appBarLayout.setBackgroundColor(swatch.getRgb());
collapsingToolbar.setContentScrimColor(swatch.getRgb());
if (getActivity() != null &&
getActivity() instanceof SearchResultDetailActivity &&
Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
// show darkened color in status bar
float[] hsv = swatch.getHsl();
hsv[2] *= 0.95f;
getActivity().getWindow().setStatusBarColor(Color.HSVToColor(hsv));
}
}
}
});
analyzeWhitenessOfCoverAsync(bitmap);
image_analyzed = true;
} catch (IllegalArgumentException ignored) {
Log.w("analyzeCover", "Invalid bitmap received");
gradientBottom.setVisibility(View.GONE);
gradientTop.setVisibility(View.GONE);
}
}
private void findViews() {
toolbar = (Toolbar) view.findViewById(R.id.toolbar);
ivCover = (ImageView) view.findViewById(R.id.ivCover);
coverWrapper = (FrameLayout) view.findViewById(R.id.coverWrapper);
gradientBottom = view.findViewById(R.id.gradient_bottom);
gradientTop = view.findViewById(R.id.gradient_top);
collapsingToolbar = (CollapsingToolbarLayout) view.findViewById(R.id.collapsingToolbar);
appBarLayout = (AppBarLayout) view.findViewById(R.id.appBarLayout);
rvDetails = (RecyclerView) view.findViewById(R.id.rvDetails);
progressBar = (ProgressBar) view.findViewById(R.id.progress);
errorView = (FrameLayout) view.findViewById(R.id.error_view);
}
/**
* Examine how many white pixels are in the bitmap in order to determine whether or not we need
* gradient overlays on top of the image.
*/
@SuppressLint("NewApi")
private void analyzeWhitenessOfCoverAsync(final Bitmap bitmap) {
AnalyzeWhitenessTask task = new AnalyzeWhitenessTask();
// Execute in parallel with FetchTask
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, bitmap);
} else {
task.execute(bitmap);
}
}
protected void display() {
try {
Log.i("result", getItem().toString());
} catch (Exception e) {
ErrorReporter.handleException(e);
}
collapsingToolbar.setTitle(getItem().getTitle());
rvDetails.setLayoutManager(new LinearLayoutManager(getActivity()));
RvJoiner joiner = new RvJoiner();
addSubhead(joiner, R.string.details_head);
joiner.add(new JoinableAdapter(new DetailsAdapter(item.getDetails(), getActivity())));
if (item.getCopies().size() != 0) {
addSubhead(joiner, R.string.copies_head);
joiner.add(new JoinableAdapter(new CopiesAdapter(item.getCopies(), getActivity())));
}
if (item.getVolumesearch() != null) {
addSubhead(joiner, R.string.volumes);
joiner.add(new JoinableLayout(
R.layout.listitem_details_volumesearch, new JoinableLayout.Callback() {
@Override
public void onInflateComplete(View view, ViewGroup parent) {
view.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
app.startVolumeSearch(getActivity(), getItem().getVolumesearch());
}
});
}
}));
} else if (item.getVolumes().size() > 0) {
addSubhead(joiner, R.string.volumes);
joiner.add(new JoinableAdapter(new VolumesAdapter(item.getVolumes(), getActivity())));
}
rvDetails.setAdapter(joiner.getAdapter());
if (id == null || id.equals("")) {
id = getItem().getId();
}
refreshMenu(toolbar.getMenu());
setProgress(false, true);
}
private void addSubhead(RvJoiner joiner, final int text) {
joiner.add(new JoinableLayout(
R.layout.listitem_details_subhead, new JoinableLayout.Callback() {
@Override
public void onInflateComplete(View view, ViewGroup parent) {
((TextView) view).setText(text);
}
}));
}
private void displayCover() {
if (getItem().getCoverBitmap() != null) {
coverWrapper.setVisibility(View.VISIBLE);
Bitmap bm = BitmapUtils.bitmapFromBytes(getItem().getCoverBitmap());
ivCover.setImageBitmap(bm);
if (!image_analyzed) {
analyzeCover(bm);
}
showCoverView(true);
} else if (getArguments().containsKey(ARG_ITEM_COVER_BITMAP)) {
showCoverView(true);
} else {
showCoverView(false);
collapsingToolbar.setTitle(getItem().getTitle());
}
}
private void showCoverView(boolean b) {
if (getActivity() == null) {
return;
}
coverWrapper.setVisibility(b ? View.VISIBLE : View.GONE);
if (!b) {
appBarLayout.setBackgroundResource(getToolbarBackgroundColor());
}
}
private int getToolbarBackgroundColor() {
if (getActivity() != null) {
if (getActivity() instanceof SearchResultDetailActivity) {
return R.color.primary_red;
} else {
return R.color.primary_red_dark;
}
} else {
return R.color.primary_red;
}
}
@Override
public void onViewStateRestored(Bundle savedInstanceState) {
super.onViewStateRestored(savedInstanceState);
if (item != null) {
display();
}
}
protected void dialog_wrong_credentials(String s, final boolean finish) {
if (getActivity() == null) {
return;
}
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setMessage(getString(R.string.opac_error) + " " + s)
.setCancelable(false)
.setNegativeButton(R.string.close,
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
if (finish) {
callbacks.removeFragment();
}
}
})
.setPositiveButton(R.string.prefs,
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int id) {
Intent intent = new Intent(getActivity(),
AccountEditActivity.class);
intent.putExtra(
AccountEditActivity.EXTRA_ACCOUNT_ID,
app.getAccount().getId());
startActivity(intent);
}
});
AlertDialog alert = builder.create();
alert.show();
}
@Override
public void onStop() {
super.onStop();
if (dialog != null) {
if (dialog.isShowing()) {
dialog.cancel();
}
}
try {
if (ft != null) {
if (!ft.isCancelled()) {
ft.cancel(true);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public void onDestroy() {
super.onDestroy();
// TODO: what was this?
/*OpacActivity.unbindDrawables(view.findViewById(R.id.rootView));
System.gc();*/
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.search_result_details_activity, menu);
refreshMenu(menu);
menu.findItem(R.id.action_print).setVisible(
Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT);
super.onCreateOptionsMenu(menu, inflater);
}
protected void refreshMenu(Menu menu) {
if (item != null) {
if (item.isReservable()) {
menu.findItem(R.id.action_reservation).setVisible(true);
} else {
menu.findItem(R.id.action_reservation).setVisible(false);
}
OpacApi api;
try {
api = app.getApi();
} catch (OpacClient.LibraryRemovedException e) {
return;
}
if (item.isBookable() && api instanceof EbookServiceApi) {
if (((EbookServiceApi) api).isEbook(item)) {
menu.findItem(R.id.action_lendebook).setVisible(true);
} else {
menu.findItem(R.id.action_lendebook).setVisible(false);
}
} else {
menu.findItem(R.id.action_lendebook).setVisible(false);
}
menu.findItem(R.id.action_tocollection).setVisible(
item.getCollectionId() != null);
} else {
menu.findItem(R.id.action_reservation).setVisible(false);
menu.findItem(R.id.action_lendebook).setVisible(false);
menu.findItem(R.id.action_tocollection).setVisible(false);
}
String bib = app.getLibrary().getIdent();
StarDataSource data = new StarDataSource(getActivity());
String _id = id;
if (item != null) {
_id = item.getId();
}
if ((_id == null || _id.equals("")) && item != null) {
if (data.isStarredTitle(bib, item.getTitle())) {
menu.findItem(R.id.action_star).setIcon(
R.drawable.ic_star_1_white_24dp);
}
} else {
if (data.isStarred(bib, _id)) {
menu.findItem(R.id.action_star).setIcon(
R.drawable.ic_star_1_white_24dp);
}
}
}
@Override
public boolean onMenuItemClick(MenuItem item) {
return onOptionsItemSelected(item);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
final String bib = app.getLibrary().getIdent();
if (item.getItemId() == R.id.action_reservation) {
reservationStart();
return true;
} else if (item.getItemId() == R.id.action_lendebook) {
bookingStart();
return true;
} else if (item.getItemId() == R.id.action_tocollection) {
if (getActivity().getIntent().getBooleanExtra("from_collection",
false)) {
getActivity().finish();
} else {
Intent intent = new Intent(getActivity(),
SearchResultDetailActivity.class);
intent.putExtra(SearchResultDetailFragment.ARG_ITEM_ID,
getItem().getCollectionId());
startActivity(intent);
getActivity().finish();
}
return true;
} else if (item.getItemId() == R.id.action_share) {
if (getItem() == null) {
Toast toast = Toast.makeText(getActivity(),
getString(R.string.share_wait), Toast.LENGTH_SHORT);
toast.show();
} else {
final String title = getItem().getTitle();
final String id = getItem().getId();
final CharSequence[] items = {getString(R.string.share_link),
getString(R.string.share_details)};
AlertDialog.Builder builder = new AlertDialog.Builder(
getActivity());
builder.setTitle(R.string.share_dialog_select);
builder.setItems(items, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int di) {
OpacApi api = null;
try {
api = app.getApi();
} catch (OpacClient.LibraryRemovedException e) {
return;
}
if (di == 0) {
// Share link
Intent intent = new Intent(
android.content.Intent.ACTION_SEND);
intent.setType("text/plain");
intent.addFlags(CompatibilityUtils.getNewDocumentIntentFlag());
// Add data to the intent, the receiving app will
// decide
// what to do with it.
intent.putExtra(Intent.EXTRA_SUBJECT, title);
String t = title;
try {
t = java.net.URLEncoder.encode(t, "UTF-8");
} catch (UnsupportedEncodingException e) {
}
String shareUrl = api.getShareUrl(id, t);
if (shareUrl != null) {
intent.putExtra(Intent.EXTRA_TEXT, shareUrl);
startActivity(Intent.createChooser(intent,
getResources()
.getString(R.string.share)));
} else {
Toast toast = Toast.makeText(getActivity(),
getString(R.string.share_notsupported),
Toast.LENGTH_SHORT);
toast.show();
}
} else { // Share details
Intent intent = new Intent(
android.content.Intent.ACTION_SEND);
intent.setType("text/plain");
intent.addFlags(CompatibilityUtils.getNewDocumentIntentFlag());
// Add data to the intent, the receiving app will
// decide
// what to do with it.
intent.putExtra(Intent.EXTRA_SUBJECT, title);
String t = title;
try {
t = t != null ? java.net.URLEncoder.encode(t, "UTF-8") : "";
} catch (UnsupportedEncodingException e) {
}
String text = title + "\n\n";
for (Detail detail : getItem().getDetails()) {
String colon = "";
if (!detail.getDesc().endsWith(":")) {
colon = ":";
}
text += detail.getDesc() + colon + "\n"
+ detail.getContent() + "\n\n";
}
List<Copy> copies = getItem().getCopies();
if (copies.size() > 0) {
text += getString(R.string.copies_head) + ":\n\n";
}
for (Copy copy : copies) {
String labelSeparator = ": ";
String infoTypeSeparator = "\n";
String branch = copy.getBranch();
String branchTxt = "";
if (branch != null && !branch.isEmpty()) {
branchTxt += getString(R.string.branch) + labelSeparator
+ branch + infoTypeSeparator;
}
String iss = copy.getIssue();
String issTxt = "";
if (iss != null && !iss.isEmpty()) {
issTxt += getString(R.string.issue) + labelSeparator
+ iss + infoTypeSeparator;
}
String dept = copy.getDepartment();
String deptTxt = "";
if (dept != null && !dept.isEmpty()) {
deptTxt += getString(R.string.department) + labelSeparator
+ dept + infoTypeSeparator;
}
String loc = copy.getLocation();
String locTxt = "";
if (loc != null && !loc.isEmpty()) {
locTxt += getString(R.string.location) + labelSeparator
+ loc + infoTypeSeparator;
}
String shelfMark = copy.getShelfmark();
String shelfMarkTxt = "";
if (shelfMark != null && !shelfMark.isEmpty()) {
shelfMarkTxt += getString(R.string.shelfmark) + labelSeparator
+ shelfMark + infoTypeSeparator;
}
String status = copy.getStatus();
String statusTxt = "";
if (status != null && !status.isEmpty()) {
statusTxt += getString(R.string.status) + labelSeparator
+ status + infoTypeSeparator;
}
String res = copy.getReservations();
String resTxt = "";
if (res != null && !res.isEmpty()) {
resTxt += getString(R.string.reservations) + labelSeparator
+ res + infoTypeSeparator;
}
String url = copy.getUrl();
String urlTxt = "";
if (url != null && !url.isEmpty()) {
urlTxt += getString(R.string.url) + labelSeparator + url + infoTypeSeparator;
}
LocalDate retDate = copy.getReturnDate();
String retDateTxt = "";
if (retDate != null) {
retDateTxt += getString(R.string.return_date) + labelSeparator +
DateTimeFormat.shortDate().print(copy.getReturnDate())
+ infoTypeSeparator;
}
text += branchTxt + deptTxt + locTxt + shelfMarkTxt + statusTxt +
resTxt + urlTxt + retDateTxt + "\n";
}
String shareUrl = api.getShareUrl(id, t);
if (shareUrl != null) {
text += shareUrl;
}
intent.putExtra(Intent.EXTRA_TEXT, text);
startActivity(Intent.createChooser(intent,
getResources().getString(R.string.share)));
}
}
});
AlertDialog alert = builder.create();
alert.show();
}
return true;
} else if (item.getItemId() == R.id.action_star) {
StarDataSource star = new StarDataSource(getActivity());
if (getItem() == null) {
Toast toast = Toast.makeText(getActivity(),
getString(R.string.star_wait), Toast.LENGTH_SHORT);
toast.show();
} else if (getItem().getId() == null
|| getItem().getId().equals("")) {
final String title = getItem().getTitle();
if (title == null || title.equals("")) {
Toast toast = Toast.makeText(getActivity(),
getString(R.string.star_unsupported), Toast.LENGTH_LONG);
toast.show();
} else {
if (star.isStarredTitle(bib, title)) {
star.remove(star.getItemByTitle(bib, title));
item.setIcon(R.drawable.ic_star_0_white_24dp);
} else {
star.star(null, title, bib, getItem().getMediaType());
Toast toast = Toast.makeText(getActivity(),
getString(R.string.starred), Toast.LENGTH_SHORT);
toast.show();
item.setIcon(R.drawable.ic_star_1_white_24dp);
}
}
} else {
final String title = getItem().getTitle();
final String id = getItem().getId();
if (star.isStarred(bib, id)) {
star.remove(star.getItem(bib, id));
item.setIcon(R.drawable.ic_star_0_white_24dp);
} else {
star.star(id, title, bib, getItem().getMediaType());
Toast toast = Toast.makeText(getActivity(),
getString(R.string.starred), Toast.LENGTH_SHORT);
toast.show();
item.setIcon(R.drawable.ic_star_1_white_24dp);
}
}
return true;
} else if (item.getItemId() == R.id.action_print) {
if (getItem() == null) {
Toast toast = Toast.makeText(getActivity(),
getString(R.string.print_wait), Toast.LENGTH_SHORT);
toast.show();
} else {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
print();
}
}
return true;
} else {
return super.onOptionsItemSelected(item);
}
}
@TargetApi(Build.VERSION_CODES.KITKAT)
private void print() {
WebView webView = new WebView(getActivity());
webView.setWebViewClient(new WebViewClient() {
@Override
public void onPageFinished(WebView webView, String url) {
PrintManager printManager = (PrintManager) getActivity()
.getSystemService(Context.PRINT_SERVICE);
PrintDocumentAdapter printAdapter = webView.createPrintDocumentAdapter();
String jobName = getItem().getTitle();
if (jobName == null || jobName.equals("")) {
jobName = getString(R.string.no_title);
}
printManager.print(jobName, printAdapter,
new PrintAttributes.Builder().build());
}
});
String templateDetailles = PrintUtils.printDetails(getItem(), getContext());
webView.loadDataWithBaseURL(null, templateDetailles, "text/HTML", "UTF-8", null);
}
public DetailedItem getItem() {
return item;
}
protected void dialog_no_credentials() {
if (getActivity() == null) {
return;
}
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setMessage(R.string.status_nouser)
.setCancelable(false)
.setNegativeButton(R.string.close,
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
})
.setPositiveButton(R.string.accounts_edit,
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int id) {
Intent intent = new Intent(getActivity(),
AccountEditActivity.class);
intent.putExtra(
AccountEditActivity.EXTRA_ACCOUNT_ID,
app.getAccount().getId());
startActivity(intent);
}
});
AlertDialog alert = builder.create();
alert.show();
}
protected void reservationStart() {
if (invalidated) {
new RestoreSessionTask(false).execute();
}
OpacApi api = null;
try {
api = app.getApi();
} catch (OpacClient.LibraryRemovedException e) {
return;
}
if (api instanceof EbookServiceApi) {
SharedPreferences sp = PreferenceManager
.getDefaultSharedPreferences(getActivity());
if (sp.getString("email", "").equals("")
&& ((EbookServiceApi) api).isEbook(item)) {
AlertDialog.Builder builder = new AlertDialog.Builder(
getActivity());
builder.setMessage(getString(R.string.opac_error_email))
.setCancelable(false)
.setNegativeButton(R.string.close,
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog,
int id) {
dialog.cancel();
}
})
.setPositiveButton(R.string.prefs,
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog,
int id) {
dialog.dismiss();
app.toPrefs(getActivity());
}
});
AlertDialog alert = builder.create();
alert.show();
return;
}
}
AccountDataSource data = new AccountDataSource(getActivity());
final List<Account> accounts = data.getAccountsWithPassword(app
.getLibrary().getIdent());
if (accounts.size() == 0) {
dialog_no_credentials();
} else if (accounts.size() > 1
&& !getActivity().getIntent().getBooleanExtra("reservation", false)
&& (api.getSupportFlags() & OpacApi.SUPPORT_FLAG_CHANGE_ACCOUNT) != 0
&& !(SearchResultDetailFragment.this.id == null
|| SearchResultDetailFragment.this.id.equals("null") ||
SearchResultDetailFragment.this.id
.equals(""))) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
// Get the layout inflater
LayoutInflater inflater = getActivity().getLayoutInflater();
View view = inflater.inflate(R.layout.dialog_simple_list, null, false);
ListView lv = (ListView) view.findViewById(R.id.lvBibs);
AccountListAdapter adapter = new AccountListAdapter(getActivity(),
accounts);
lv.setAdapter(adapter);
lv.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
if (accounts.get(position).getId() != app.getAccount()
.getId() || account_switched) {
if (SearchResultDetailFragment.this.id == null
|| SearchResultDetailFragment.this.id
.equals("null")
|| SearchResultDetailFragment.this.id
.equals("")) {
Toast.makeText(getActivity(),
R.string.accchange_sorry, Toast.LENGTH_LONG)
.show();
} else {
if (app.getAccount().getId() != accounts.get(position).getId()) {
app.setAccount(accounts.get(position).getId());
}
Intent intent = new Intent(getActivity(),
SearchResultDetailActivity.class);
intent.putExtra(
SearchResultDetailFragment.ARG_ITEM_ID,
SearchResultDetailFragment.this.id);
// TODO: refresh fragment instead
intent.putExtra("reservation", true);
startActivity(intent);
}
} else {