1
0
mirror of https://github.com/KokaKiwi/BarInsta synced 2024-11-22 14:47:29 +00:00

No more requireContext() as it is fail first. Instead use getContext() and check for null.

This commit is contained in:
Ammar Githam 2020-09-12 17:51:50 +09:00
parent ee7f0a5c95
commit 122d84fbf2
18 changed files with 392 additions and 274 deletions

View File

@ -1,6 +1,7 @@
package awais.instagrabber.dialogs; package awais.instagrabber.dialogs;
import android.app.Dialog; import android.app.Dialog;
import android.content.Context;
import android.content.pm.PackageManager; import android.content.pm.PackageManager;
import android.graphics.Color; import android.graphics.Color;
import android.graphics.drawable.Animatable; import android.graphics.drawable.Animatable;
@ -88,7 +89,9 @@ public class ProfilePicDialogFragment extends DialogFragment {
private void init() { private void init() {
binding.download.setOnClickListener(v -> { binding.download.setOnClickListener(v -> {
if (ContextCompat.checkSelfPermission(requireContext(), DownloadUtils.PERMS[0]) == PackageManager.PERMISSION_GRANTED) { final Context context = getContext();
if (context == null) return;
if (ContextCompat.checkSelfPermission(context, DownloadUtils.PERMS[0]) == PackageManager.PERMISSION_GRANTED) {
downloadProfilePicture(); downloadProfilePicture();
return; return;
} }
@ -140,21 +143,23 @@ public class ProfilePicDialogFragment extends DialogFragment {
private void downloadProfilePicture() { private void downloadProfilePicture() {
if (url == null) return; if (url == null) return;
final File dir = new File(Environment.getExternalStorageDirectory(), "Download"); final File dir = new File(Environment.getExternalStorageDirectory(), "Download");
final Context context = getContext();
if (context == null) return;
if (dir.exists() || dir.mkdirs()) { if (dir.exists() || dir.mkdirs()) {
final File saveFile = new File(dir, name + '_' + System.currentTimeMillis() + ".jpg"); final File saveFile = new File(dir, name + '_' + System.currentTimeMillis() + ".jpg");
new DownloadAsync(requireContext(), new DownloadAsync(context,
url, url,
saveFile, saveFile,
result -> { result -> {
final int toastRes = result != null && result.exists() ? final int toastRes = result != null && result.exists() ?
R.string.downloader_downloaded_in_folder : R.string.downloader_error_download_file; R.string.downloader_downloaded_in_folder : R.string.downloader_error_download_file;
Toast.makeText(requireContext(), toastRes, Toast.LENGTH_SHORT).show(); Toast.makeText(context, toastRes, Toast.LENGTH_SHORT).show();
}) })
.setItems(null, name) .setItems(null, name)
.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); .executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
return; return;
} }
Toast.makeText(requireContext(), R.string.downloader_error_creating_folder, Toast.LENGTH_SHORT).show(); Toast.makeText(context, R.string.downloader_error_creating_folder, Toast.LENGTH_SHORT).show();
} }
// private void showImageInfo() { // private void showImageInfo() {

View File

@ -1,5 +1,6 @@
package awais.instagrabber.fragments; package awais.instagrabber.fragments;
import android.content.Context;
import android.content.DialogInterface; import android.content.DialogInterface;
import android.content.res.Resources; import android.content.res.Resources;
import android.os.AsyncTask; import android.os.AsyncTask;
@ -41,12 +42,12 @@ import awais.instagrabber.dialogs.ProfilePicDialogFragment;
import awais.instagrabber.interfaces.MentionClickListener; import awais.instagrabber.interfaces.MentionClickListener;
import awais.instagrabber.models.CommentModel; import awais.instagrabber.models.CommentModel;
import awais.instagrabber.models.ProfileModel; import awais.instagrabber.models.ProfileModel;
import awais.instagrabber.webservices.MediaService;
import awais.instagrabber.webservices.ServiceCallback;
import awais.instagrabber.utils.Constants; import awais.instagrabber.utils.Constants;
import awais.instagrabber.utils.CookieUtils; import awais.instagrabber.utils.CookieUtils;
import awais.instagrabber.utils.TextUtils; import awais.instagrabber.utils.TextUtils;
import awais.instagrabber.utils.Utils; import awais.instagrabber.utils.Utils;
import awais.instagrabber.webservices.MediaService;
import awais.instagrabber.webservices.ServiceCallback;
import static android.content.Context.INPUT_METHOD_SERVICE; import static android.content.Context.INPUT_METHOD_SERVICE;
@ -178,8 +179,10 @@ public final class CommentsViewerFragment extends Fragment implements SwipeRefre
} }
final DialogInterface.OnClickListener profileDialogListener = (dialog, which) -> { final DialogInterface.OnClickListener profileDialogListener = (dialog, which) -> {
final Context context = getContext();
if (context == null) return;
if (commentModel == null) { if (commentModel == null) {
Toast.makeText(requireContext(), R.string.downloader_unknown_error, Toast.LENGTH_SHORT).show(); Toast.makeText(context, R.string.downloader_unknown_error, Toast.LENGTH_SHORT).show();
return; return;
} }
final ProfileModel profileModel = commentModel.getProfileModel(); final ProfileModel profileModel = commentModel.getProfileModel();
@ -198,10 +201,10 @@ public final class CommentsViewerFragment extends Fragment implements SwipeRefre
.commit(); .commit();
break; break;
case 2: // copy username case 2: // copy username
Utils.copyText(requireContext(), profileModel.getUsername()); Utils.copyText(context, profileModel.getUsername());
break; break;
case 3: // copy comment case 3: // copy comment
Utils.copyText(requireContext(), commentModel.getText().toString()); Utils.copyText(context, commentModel.getText().toString());
break; break;
case 4: // reply to comment case 4: // reply to comment
final View focus = binding.rvComments.findViewWithTag(commentModel); final View focus = binding.rvComments.findViewWithTag(commentModel);
@ -213,7 +216,7 @@ public final class CommentsViewerFragment extends Fragment implements SwipeRefre
binding.commentText.postDelayed(new Runnable() { binding.commentText.postDelayed(new Runnable() {
@Override @Override
public void run() { public void run() {
imm = (InputMethodManager) requireContext().getSystemService(INPUT_METHOD_SERVICE); imm = (InputMethodManager) context.getSystemService(INPUT_METHOD_SERVICE);
if (imm == null) return; if (imm == null) return;
imm.showSoftInput(binding.commentText, 0); imm.showSoftInput(binding.commentText, 0);
} }
@ -226,7 +229,7 @@ public final class CommentsViewerFragment extends Fragment implements SwipeRefre
public void onSuccess(final Boolean result) { public void onSuccess(final Boolean result) {
commentModel = null; commentModel = null;
if (!result) { if (!result) {
Toast.makeText(requireContext(), R.string.downloader_unknown_error, Toast.LENGTH_SHORT).show(); Toast.makeText(context, R.string.downloader_unknown_error, Toast.LENGTH_SHORT).show();
return; return;
} }
onRefresh(); onRefresh();
@ -235,7 +238,7 @@ public final class CommentsViewerFragment extends Fragment implements SwipeRefre
@Override @Override
public void onFailure(final Throwable t) { public void onFailure(final Throwable t) {
Log.e(TAG, "Error liking comment", t); Log.e(TAG, "Error liking comment", t);
Toast.makeText(requireContext(), t.getMessage(), Toast.LENGTH_SHORT).show(); Toast.makeText(context, t.getMessage(), Toast.LENGTH_SHORT).show();
} }
}); });
return; return;
@ -245,7 +248,7 @@ public final class CommentsViewerFragment extends Fragment implements SwipeRefre
public void onSuccess(final Boolean result) { public void onSuccess(final Boolean result) {
commentModel = null; commentModel = null;
if (!result) { if (!result) {
Toast.makeText(requireContext(), R.string.downloader_unknown_error, Toast.LENGTH_SHORT).show(); Toast.makeText(context, R.string.downloader_unknown_error, Toast.LENGTH_SHORT).show();
return; return;
} }
onRefresh(); onRefresh();
@ -254,7 +257,7 @@ public final class CommentsViewerFragment extends Fragment implements SwipeRefre
@Override @Override
public void onFailure(final Throwable t) { public void onFailure(final Throwable t) {
Log.e(TAG, "Error unliking comment", t); Log.e(TAG, "Error unliking comment", t);
Toast.makeText(requireContext(), t.getMessage(), Toast.LENGTH_SHORT).show(); Toast.makeText(context, t.getMessage(), Toast.LENGTH_SHORT).show();
} }
}); });
break; break;
@ -268,7 +271,7 @@ public final class CommentsViewerFragment extends Fragment implements SwipeRefre
public void onSuccess(final Boolean result) { public void onSuccess(final Boolean result) {
commentModel = null; commentModel = null;
if (!result) { if (!result) {
Toast.makeText(requireContext(), R.string.downloader_unknown_error, Toast.LENGTH_SHORT).show(); Toast.makeText(context, R.string.downloader_unknown_error, Toast.LENGTH_SHORT).show();
return; return;
} }
onRefresh(); onRefresh();
@ -277,7 +280,7 @@ public final class CommentsViewerFragment extends Fragment implements SwipeRefre
@Override @Override
public void onFailure(final Throwable t) { public void onFailure(final Throwable t) {
Log.e(TAG, "Error deleting comment", t); Log.e(TAG, "Error deleting comment", t);
Toast.makeText(requireContext(), t.getMessage(), Toast.LENGTH_SHORT).show(); Toast.makeText(context, t.getMessage(), Toast.LENGTH_SHORT).show();
} }
}); });
break; break;
@ -327,7 +330,9 @@ public final class CommentsViewerFragment extends Fragment implements SwipeRefre
resources.getString(R.string.comment_viewer_copy_comment) resources.getString(R.string.comment_viewer_copy_comment)
}; };
} }
new AlertDialog.Builder(requireContext()) final Context context = getContext();
if (context == null) return;
new AlertDialog.Builder(context)
.setTitle(title) .setTitle(title)
.setItems(commentDialogList, profileDialogListener) .setItems(commentDialogList, profileDialogListener)
.setNegativeButton(R.string.cancel, null) .setNegativeButton(R.string.cancel, null)
@ -346,8 +351,10 @@ public final class CommentsViewerFragment extends Fragment implements SwipeRefre
private final View.OnClickListener newCommentListener = v -> { private final View.OnClickListener newCommentListener = v -> {
final Editable text = binding.commentText.getText(); final Editable text = binding.commentText.getText();
final Context context = getContext();
if (context == null) return;
if (text == null || TextUtils.isEmpty(text.toString())) { if (text == null || TextUtils.isEmpty(text.toString())) {
Toast.makeText(requireContext(), R.string.comment_send_empty_comment, Toast.LENGTH_SHORT).show(); Toast.makeText(context, R.string.comment_send_empty_comment, Toast.LENGTH_SHORT).show();
return; return;
} }
final String userId = CookieUtils.getUserIdFromCookie(cookie); final String userId = CookieUtils.getUserIdFromCookie(cookie);
@ -362,7 +369,7 @@ public final class CommentsViewerFragment extends Fragment implements SwipeRefre
commentModel = null; commentModel = null;
binding.commentText.setText(""); binding.commentText.setText("");
if (!result) { if (!result) {
Toast.makeText(requireContext(), R.string.downloader_unknown_error, Toast.LENGTH_SHORT).show(); Toast.makeText(context, R.string.downloader_unknown_error, Toast.LENGTH_SHORT).show();
return; return;
} }
onRefresh(); onRefresh();
@ -371,7 +378,7 @@ public final class CommentsViewerFragment extends Fragment implements SwipeRefre
@Override @Override
public void onFailure(final Throwable t) { public void onFailure(final Throwable t) {
Log.e(TAG, "Error during comment", t); Log.e(TAG, "Error during comment", t);
Toast.makeText(requireContext(), t.getMessage(), Toast.LENGTH_SHORT).show(); Toast.makeText(context, t.getMessage(), Toast.LENGTH_SHORT).show();
} }
}); });
}; };

View File

@ -1,5 +1,6 @@
package awais.instagrabber.fragments; package awais.instagrabber.fragments;
import android.content.Context;
import android.content.res.ColorStateList; import android.content.res.ColorStateList;
import android.graphics.Typeface; import android.graphics.Typeface;
import android.os.AsyncTask; import android.os.AsyncTask;
@ -103,7 +104,9 @@ public class HashTagFragment extends Fragment {
if (postsAdapter == null || hashtag == null) { if (postsAdapter == null || hashtag == null) {
return false; return false;
} }
DownloadUtils.batchDownload(requireContext(), final Context context = getContext();
if (context == null) return false;
DownloadUtils.batchDownload(context,
hashtag, hashtag,
DownloadMethod.DOWNLOAD_MAIN, DownloadMethod.DOWNLOAD_MAIN,
postsAdapter.getSelectedModels()); postsAdapter.getSelectedModels());
@ -180,7 +183,9 @@ public class HashTagFragment extends Fragment {
private void setupPosts() { private void setupPosts() {
postsViewModel = new ViewModelProvider(this).get(PostsViewModel.class); postsViewModel = new ViewModelProvider(this).get(PostsViewModel.class);
final GridAutofitLayoutManager layoutManager = new GridAutofitLayoutManager(requireContext(), Utils.convertDpToPx(110)); final Context context = getContext();
if (context == null) return;
final GridAutofitLayoutManager layoutManager = new GridAutofitLayoutManager(context, Utils.convertDpToPx(110));
binding.mainPosts.setLayoutManager(layoutManager); binding.mainPosts.setLayoutManager(layoutManager);
binding.mainPosts.addItemDecoration(new GridSpacingItemDecoration(Utils.convertDpToPx(4))); binding.mainPosts.addItemDecoration(new GridSpacingItemDecoration(Utils.convertDpToPx(4)));
postsAdapter = new PostsAdapter((postModel, position) -> { postsAdapter = new PostsAdapter((postModel, position) -> {
@ -238,11 +243,12 @@ public class HashTagFragment extends Fragment {
stopCurrentExecutor(); stopCurrentExecutor();
binding.swipeRefreshLayout.setRefreshing(true); binding.swipeRefreshLayout.setRefreshing(true);
currentlyExecuting = new HashtagFetcher(hashtag.substring(1), result -> { currentlyExecuting = new HashtagFetcher(hashtag.substring(1), result -> {
if (getContext() == null) return; final Context context = getContext();
if (context == null) return;
hashtagModel = result; hashtagModel = result;
binding.swipeRefreshLayout.setRefreshing(false); binding.swipeRefreshLayout.setRefreshing(false);
if (hashtagModel == null) { if (hashtagModel == null) {
Toast.makeText(requireContext(), R.string.error_loading_profile, Toast.LENGTH_SHORT).show(); Toast.makeText(context, R.string.error_loading_profile, Toast.LENGTH_SHORT).show();
return; return;
} }
fetchPosts(); fetchPosts();
@ -256,6 +262,8 @@ public class HashTagFragment extends Fragment {
if (TextUtils.isEmpty(hashtag)) return; if (TextUtils.isEmpty(hashtag)) return;
currentlyExecuting = new PostsFetcher(hashtag.substring(1), PostItemType.HASHTAG, endCursor, postsFetchListener) currentlyExecuting = new PostsFetcher(hashtag.substring(1), PostItemType.HASHTAG, endCursor, postsFetchListener)
.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); .executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
final Context context = getContext();
if (context == null) return;
if (isLoggedIn) { if (isLoggedIn) {
new iStoryStatusFetcher(hashtagModel.getName(), null, false, true, false, false, stories -> { new iStoryStatusFetcher(hashtagModel.getName(), null, false, true, false, false, stories -> {
storyModels = stories; storyModels = stories;
@ -266,17 +274,17 @@ public class HashTagFragment extends Fragment {
binding.btnFollowTag.setText(hashtagModel.getFollowing() ? R.string.unfollow : R.string.follow); binding.btnFollowTag.setText(hashtagModel.getFollowing() ? R.string.unfollow : R.string.follow);
ViewCompat.setBackgroundTintList(binding.btnFollowTag, ColorStateList.valueOf( ViewCompat.setBackgroundTintList(binding.btnFollowTag, ColorStateList.valueOf(
ContextCompat.getColor(requireContext(), hashtagModel.getFollowing() ContextCompat.getColor(context, hashtagModel.getFollowing()
? R.color.btn_purple_background ? R.color.btn_purple_background
: R.color.btn_pink_background))); : R.color.btn_pink_background)));
} else { } else {
binding.btnFollowTag.setText(Utils.dataBox.getFavorite(hashtag) != null binding.btnFollowTag.setText(Utils.dataBox.getFavorite(hashtag) != null
? R.string.unfavorite_short ? R.string.unfavorite_short
: R.string.favorite_short); : R.string.favorite_short);
ViewCompat.setBackgroundTintList(binding.btnFollowTag, ColorStateList.valueOf( ViewCompat.setBackgroundTintList(binding.btnFollowTag, ColorStateList.valueOf(
ContextCompat.getColor(requireContext(), Utils.dataBox.getFavorite(hashtag) != null ContextCompat.getColor(context, Utils.dataBox.getFavorite(hashtag) != null
? R.color.btn_purple_background ? R.color.btn_purple_background
: R.color.btn_pink_background))); : R.color.btn_pink_background)));
} }
binding.mainHashtagImage.setImageURI(hashtagModel.getSdProfilePic()); binding.mainHashtagImage.setImageURI(hashtagModel.getSdProfilePic());
final String postCount = String.valueOf(hashtagModel.getPostCount()); final String postCount = String.valueOf(hashtagModel.getPostCount());

View File

@ -1,5 +1,6 @@
package awais.instagrabber.fragments; package awais.instagrabber.fragments;
import android.content.Context;
import android.content.Intent; import android.content.Intent;
import android.graphics.Typeface; import android.graphics.Typeface;
import android.net.Uri; import android.net.Uri;
@ -44,10 +45,6 @@ import awais.instagrabber.customviews.helpers.GridSpacingItemDecoration;
import awais.instagrabber.customviews.helpers.NestedCoordinatorLayout; import awais.instagrabber.customviews.helpers.NestedCoordinatorLayout;
import awais.instagrabber.customviews.helpers.RecyclerLazyLoader; import awais.instagrabber.customviews.helpers.RecyclerLazyLoader;
import awais.instagrabber.databinding.FragmentLocationBinding; import awais.instagrabber.databinding.FragmentLocationBinding;
import awais.instagrabber.utils.CookieUtils;
import awais.instagrabber.utils.DownloadUtils;
import awais.instagrabber.utils.TextUtils;
import awais.instagrabber.viewmodels.PostsViewModel;
import awais.instagrabber.interfaces.FetchListener; import awais.instagrabber.interfaces.FetchListener;
import awais.instagrabber.models.LocationModel; import awais.instagrabber.models.LocationModel;
import awais.instagrabber.models.PostModel; import awais.instagrabber.models.PostModel;
@ -55,7 +52,11 @@ import awais.instagrabber.models.StoryModel;
import awais.instagrabber.models.enums.DownloadMethod; import awais.instagrabber.models.enums.DownloadMethod;
import awais.instagrabber.models.enums.PostItemType; import awais.instagrabber.models.enums.PostItemType;
import awais.instagrabber.utils.Constants; import awais.instagrabber.utils.Constants;
import awais.instagrabber.utils.CookieUtils;
import awais.instagrabber.utils.DownloadUtils;
import awais.instagrabber.utils.TextUtils;
import awais.instagrabber.utils.Utils; import awais.instagrabber.utils.Utils;
import awais.instagrabber.viewmodels.PostsViewModel;
import awaisomereport.LogCollector; import awaisomereport.LogCollector;
import static awais.instagrabber.utils.Utils.logCollector; import static awais.instagrabber.utils.Utils.logCollector;
@ -106,7 +107,9 @@ public class LocationFragment extends Fragment {
if (postsAdapter == null || locationId == null) { if (postsAdapter == null || locationId == null) {
return false; return false;
} }
DownloadUtils.batchDownload(requireContext(), final Context context = getContext();
if (context == null) return false;
DownloadUtils.batchDownload(context,
locationId, locationId,
DownloadMethod.DOWNLOAD_MAIN, DownloadMethod.DOWNLOAD_MAIN,
postsAdapter.getSelectedModels()); postsAdapter.getSelectedModels());
@ -186,7 +189,9 @@ public class LocationFragment extends Fragment {
private void setupPosts() { private void setupPosts() {
postsViewModel = new ViewModelProvider(this).get(PostsViewModel.class); postsViewModel = new ViewModelProvider(this).get(PostsViewModel.class);
final GridAutofitLayoutManager layoutManager = new GridAutofitLayoutManager(requireContext(), Utils.convertDpToPx(110)); final Context context = getContext();
if (context == null) return;
final GridAutofitLayoutManager layoutManager = new GridAutofitLayoutManager(context, Utils.convertDpToPx(110));
binding.mainPosts.setLayoutManager(layoutManager); binding.mainPosts.setLayoutManager(layoutManager);
binding.mainPosts.addItemDecoration(new GridSpacingItemDecoration(Utils.convertDpToPx(4))); binding.mainPosts.addItemDecoration(new GridSpacingItemDecoration(Utils.convertDpToPx(4)));
postsAdapter = new PostsAdapter((postModel, position) -> { postsAdapter = new PostsAdapter((postModel, position) -> {
@ -247,7 +252,9 @@ public class LocationFragment extends Fragment {
locationModel = result; locationModel = result;
binding.swipeRefreshLayout.setRefreshing(false); binding.swipeRefreshLayout.setRefreshing(false);
if (locationModel == null) { if (locationModel == null) {
Toast.makeText(requireContext(), R.string.error_loading_profile, Toast.LENGTH_SHORT).show(); final Context context = getContext();
if (context == null) return;
Toast.makeText(context, R.string.error_loading_profile, Toast.LENGTH_SHORT).show();
return; return;
} }
setTitle(); setTitle();

View File

@ -1,5 +1,6 @@
package awais.instagrabber.fragments; package awais.instagrabber.fragments;
import android.content.Context;
import android.content.DialogInterface; import android.content.DialogInterface;
import android.content.pm.PackageManager; import android.content.pm.PackageManager;
import android.os.AsyncTask; import android.os.AsyncTask;
@ -35,13 +36,13 @@ import awais.instagrabber.interfaces.MentionClickListener;
import awais.instagrabber.models.ViewerPostModel; import awais.instagrabber.models.ViewerPostModel;
import awais.instagrabber.models.ViewerPostModelWrapper; import awais.instagrabber.models.ViewerPostModelWrapper;
import awais.instagrabber.models.enums.DownloadMethod; import awais.instagrabber.models.enums.DownloadMethod;
import awais.instagrabber.webservices.MediaService;
import awais.instagrabber.webservices.ServiceCallback;
import awais.instagrabber.utils.Constants; import awais.instagrabber.utils.Constants;
import awais.instagrabber.utils.CookieUtils; import awais.instagrabber.utils.CookieUtils;
import awais.instagrabber.utils.DownloadUtils; import awais.instagrabber.utils.DownloadUtils;
import awais.instagrabber.utils.Utils; import awais.instagrabber.utils.Utils;
import awais.instagrabber.viewmodels.ViewerPostViewModel; import awais.instagrabber.viewmodels.ViewerPostViewModel;
import awais.instagrabber.webservices.MediaService;
import awais.instagrabber.webservices.ServiceCallback;
import static androidx.core.content.ContextCompat.checkSelfPermission; import static androidx.core.content.ContextCompat.checkSelfPermission;
import static awais.instagrabber.utils.Utils.settingsHelper; import static awais.instagrabber.utils.Utils.settingsHelper;
@ -116,10 +117,6 @@ public class PostViewFragment extends Fragment {
case R.id.viewerCaption: case R.id.viewerCaption:
break; break;
case R.id.btnComments: case R.id.btnComments:
// startActivity(new Intent(requireContext(), CommentsViewerFragment.class)
// .putExtra(Constants.EXTRAS_SHORTCODE, postModel.getShortCode())
// .putExtra(Constants.EXTRAS_POST, postModel.getPostId())
// .putExtra(Constants.EXTRAS_USER, Utils.getUserIdFromCookie(COOKIE)));
String postId = postModel.getPostId(); String postId = postModel.getPostId();
if (postId.contains("_")) postId = postId.substring(0, postId.indexOf("_")); if (postId.contains("_")) postId = postId.substring(0, postId.indexOf("_"));
final NavDirections commentsAction = PostViewFragmentDirections.actionGlobalCommentsViewerFragment( final NavDirections commentsAction = PostViewFragmentDirections.actionGlobalCommentsViewerFragment(
@ -130,7 +127,9 @@ public class PostViewFragment extends Fragment {
NavHostFragment.findNavController(this).navigate(commentsAction); NavHostFragment.findNavController(this).navigate(commentsAction);
break; break;
case R.id.btnDownload: case R.id.btnDownload:
if (checkSelfPermission(requireContext(), final Context context = getContext();
if (context == null) return;
if (checkSelfPermission(context,
DownloadUtils.PERMS[0]) == PackageManager.PERMISSION_GRANTED) { DownloadUtils.PERMS[0]) == PackageManager.PERMISSION_GRANTED) {
showDownloadDialog(Arrays.asList(wrapper.getViewerPostModels()), showDownloadDialog(Arrays.asList(wrapper.getViewerPostModels()),
childPosition, childPosition,
@ -205,7 +204,11 @@ public class PostViewFragment extends Fragment {
break; break;
} }
}; };
private PostViewAdapter.OnPostCaptionLongClickListener captionLongClickListener = text -> Utils.copyText(requireContext(), text); private PostViewAdapter.OnPostCaptionLongClickListener captionLongClickListener = text -> {
final Context context = getContext();
if (context == null) return;
Utils.copyText(context, text);
};
@Override @Override
public void onCreate(@Nullable final Bundle savedInstanceState) { public void onCreate(@Nullable final Bundle savedInstanceState) {
@ -304,6 +307,8 @@ public class PostViewFragment extends Fragment {
final int childPosition, final int childPosition,
final String username) { final String username) {
final List<ViewerPostModel> postModelsToDownload = new ArrayList<>(); final List<ViewerPostModel> postModelsToDownload = new ArrayList<>();
final Context context = getContext();
if (context == null) return;
if (!session && postModels.size() > 1) { if (!session && postModels.size() > 1) {
final DialogInterface.OnClickListener clickListener = (dialog, which) -> { final DialogInterface.OnClickListener clickListener = (dialog, which) -> {
if (which == DialogInterface.BUTTON_NEGATIVE) { if (which == DialogInterface.BUTTON_NEGATIVE) {
@ -315,20 +320,20 @@ public class PostViewFragment extends Fragment {
postModelsToDownload.add(postModels.get(childPosition)); postModelsToDownload.add(postModels.get(childPosition));
} }
if (postModelsToDownload.size() > 0) { if (postModelsToDownload.size() > 0) {
DownloadUtils.batchDownload(requireContext(), DownloadUtils.batchDownload(context,
username, username,
DownloadMethod.DOWNLOAD_POST_VIEWER, DownloadMethod.DOWNLOAD_POST_VIEWER,
postModelsToDownload); postModelsToDownload);
} }
}; };
new AlertDialog.Builder(requireContext()) new AlertDialog.Builder(context)
.setTitle(R.string.post_viewer_download_dialog_title) .setTitle(R.string.post_viewer_download_dialog_title)
.setMessage(R.string.post_viewer_download_message) .setMessage(R.string.post_viewer_download_message)
.setNeutralButton(R.string.post_viewer_download_session, clickListener) .setNeutralButton(R.string.post_viewer_download_session, clickListener)
.setPositiveButton(R.string.post_viewer_download_current, clickListener) .setPositiveButton(R.string.post_viewer_download_current, clickListener)
.setNegativeButton(R.string.post_viewer_download_album, clickListener).show(); .setNegativeButton(R.string.post_viewer_download_album, clickListener).show();
} else { } else {
DownloadUtils.batchDownload(requireContext(), DownloadUtils.batchDownload(context,
username, username,
DownloadMethod.DOWNLOAD_POST_VIEWER, DownloadMethod.DOWNLOAD_POST_VIEWER,
Collections.singletonList(postModels.get(childPosition))); Collections.singletonList(postModels.get(childPosition)));

View File

@ -1,5 +1,6 @@
package awais.instagrabber.fragments; package awais.instagrabber.fragments;
import android.content.Context;
import android.content.pm.PackageManager; import android.content.pm.PackageManager;
import android.os.AsyncTask; import android.os.AsyncTask;
import android.os.Bundle; import android.os.Bundle;
@ -41,14 +42,14 @@ import awais.instagrabber.customviews.helpers.GridSpacingItemDecoration;
import awais.instagrabber.customviews.helpers.RecyclerLazyLoader; import awais.instagrabber.customviews.helpers.RecyclerLazyLoader;
import awais.instagrabber.databinding.FragmentSavedBinding; import awais.instagrabber.databinding.FragmentSavedBinding;
import awais.instagrabber.fragments.main.ProfileFragmentDirections; import awais.instagrabber.fragments.main.ProfileFragmentDirections;
import awais.instagrabber.utils.DownloadUtils;
import awais.instagrabber.utils.TextUtils;
import awais.instagrabber.viewmodels.PostsViewModel;
import awais.instagrabber.interfaces.FetchListener; import awais.instagrabber.interfaces.FetchListener;
import awais.instagrabber.models.PostModel; import awais.instagrabber.models.PostModel;
import awais.instagrabber.models.enums.DownloadMethod; import awais.instagrabber.models.enums.DownloadMethod;
import awais.instagrabber.models.enums.PostItemType; import awais.instagrabber.models.enums.PostItemType;
import awais.instagrabber.utils.DownloadUtils;
import awais.instagrabber.utils.TextUtils;
import awais.instagrabber.utils.Utils; import awais.instagrabber.utils.Utils;
import awais.instagrabber.viewmodels.PostsViewModel;
import awaisomereport.LogCollector; import awaisomereport.LogCollector;
import static awais.instagrabber.utils.Utils.logCollector; import static awais.instagrabber.utils.Utils.logCollector;
@ -94,7 +95,9 @@ public final class SavedViewerFragment extends Fragment implements SwipeRefreshL
if (postsAdapter == null || username == null) { if (postsAdapter == null || username == null) {
return false; return false;
} }
DownloadUtils.batchDownload(requireContext(), final Context context = getContext();
if (context == null) return false;
DownloadUtils.batchDownload(context,
username, username,
DownloadMethod.DOWNLOAD_SAVED, DownloadMethod.DOWNLOAD_SAVED,
postsAdapter.getSelectedModels()); postsAdapter.getSelectedModels());
@ -133,9 +136,10 @@ public final class SavedViewerFragment extends Fragment implements SwipeRefreshL
} }
model.setPageCursor(false, null); model.setPageCursor(false, null);
} }
} } else if (current == null) {
else if (current == null) { final Context context = getContext();
Toast.makeText(requireContext(), R.string.empty_list, Toast.LENGTH_SHORT).show(); if (context == null) return;
Toast.makeText(context, R.string.empty_list, Toast.LENGTH_SHORT).show();
NavHostFragment.findNavController(SavedViewerFragment.this).popBackStack(); NavHostFragment.findNavController(SavedViewerFragment.this).popBackStack();
} }
binding.swipeRefreshLayout.setRefreshing(false); binding.swipeRefreshLayout.setRefreshing(false);
@ -192,7 +196,9 @@ public final class SavedViewerFragment extends Fragment implements SwipeRefreshL
binding.swipeRefreshLayout.setOnRefreshListener(this); binding.swipeRefreshLayout.setOnRefreshListener(this);
// autoloadPosts = Utils.settingsHelper.getBoolean(AUTOLOAD_POSTS); // autoloadPosts = Utils.settingsHelper.getBoolean(AUTOLOAD_POSTS);
binding.mainPosts.setNestedScrollingEnabled(false); binding.mainPosts.setNestedScrollingEnabled(false);
final GridAutofitLayoutManager layoutManager = new GridAutofitLayoutManager(requireContext(), Utils.convertDpToPx(110)); final Context context = getContext();
if (context == null) return;
final GridAutofitLayoutManager layoutManager = new GridAutofitLayoutManager(context, Utils.convertDpToPx(110));
binding.mainPosts.setLayoutManager(layoutManager); binding.mainPosts.setLayoutManager(layoutManager);
binding.mainPosts.addItemDecoration(new GridSpacingItemDecoration(Utils.convertDpToPx(4))); binding.mainPosts.addItemDecoration(new GridSpacingItemDecoration(Utils.convertDpToPx(4)));
postsAdapter = new PostsAdapter((postModel, position) -> { postsAdapter = new PostsAdapter((postModel, position) -> {
@ -286,8 +292,11 @@ public final class SavedViewerFragment extends Fragment implements SwipeRefreshL
@Override @Override
public void onRequestPermissionsResult(final int requestCode, @NonNull final String[] permissions, @NonNull final int[] grantResults) { public void onRequestPermissionsResult(final int requestCode, @NonNull final String[] permissions, @NonNull final int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults); super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == 8020 && grantResults[0] == PackageManager.PERMISSION_GRANTED && selectedItems.size() > 0) if (requestCode == 8020 && grantResults[0] == PackageManager.PERMISSION_GRANTED && selectedItems.size() > 0) {
DownloadUtils.batchDownload(requireContext(), null, DownloadMethod.DOWNLOAD_SAVED, selectedItems); final Context context = getContext();
if (context == null) return;
DownloadUtils.batchDownload(context, null, DownloadMethod.DOWNLOAD_SAVED, selectedItems);
}
} }
public static void stopCurrentExecutor() { public static void stopCurrentExecutor() {

View File

@ -1,6 +1,7 @@
package awais.instagrabber.fragments; package awais.instagrabber.fragments;
import android.annotation.SuppressLint; import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent; import android.content.Intent;
import android.content.pm.PackageManager; import android.content.pm.PackageManager;
import android.graphics.drawable.Animatable; import android.graphics.drawable.Animatable;
@ -180,17 +181,19 @@ public class StoryViewerFragment extends Fragment {
@Override @Override
public boolean onOptionsItemSelected(@NonNull final MenuItem item) { public boolean onOptionsItemSelected(@NonNull final MenuItem item) {
final Context context = getContext();
if (context == null) return false;
switch (item.getItemId()) { switch (item.getItemId()) {
case R.id.action_download: case R.id.action_download:
if (ContextCompat.checkSelfPermission(requireContext(), DownloadUtils.PERMS[0]) == PackageManager.PERMISSION_GRANTED) if (ContextCompat.checkSelfPermission(context, DownloadUtils.PERMS[0]) == PackageManager.PERMISSION_GRANTED)
downloadStory(); downloadStory();
else else
ActivityCompat.requestPermissions(requireActivity(), DownloadUtils.PERMS, 8020); ActivityCompat.requestPermissions(requireActivity(), DownloadUtils.PERMS, 8020);
return true; return true;
case R.id.action_dms: case R.id.action_dms:
final EditText input = new EditText(requireContext()); final EditText input = new EditText(context);
input.setHint(R.string.reply_hint); input.setHint(R.string.reply_hint);
new AlertDialog.Builder(requireContext()) new AlertDialog.Builder(context)
.setTitle(R.string.reply_story) .setTitle(R.string.reply_story)
.setView(input) .setView(input)
.setPositiveButton(R.string.ok, (d, w) -> new CommentAction(cookie, currentStory, threadId -> { .setPositiveButton(R.string.ok, (d, w) -> new CommentAction(cookie, currentStory, threadId -> {
@ -202,7 +205,7 @@ public class StoryViewerFragment extends Fragment {
); );
final DirectThreadBroadcaster broadcast = new DirectThreadBroadcaster(threadId); final DirectThreadBroadcaster broadcast = new DirectThreadBroadcaster(threadId);
broadcast.setOnTaskCompleteListener(result -> Toast.makeText( broadcast.setOnTaskCompleteListener(result -> Toast.makeText(
requireContext(), context,
result != null ? R.string.answered_story : R.string.downloader_unknown_error, result != null ? R.string.answered_story : R.string.downloader_unknown_error,
Toast.LENGTH_SHORT Toast.LENGTH_SHORT
).show()); ).show());
@ -262,7 +265,9 @@ public class StoryViewerFragment extends Fragment {
private void setupStories() { private void setupStories() {
storiesViewModel = new ViewModelProvider(this).get(StoriesViewModel.class); storiesViewModel = new ViewModelProvider(this).get(StoriesViewModel.class);
setupListeners(); setupListeners();
binding.storiesList.setLayoutManager(new LinearLayoutManager(requireContext(), LinearLayoutManager.HORIZONTAL, false)); final Context context = getContext();
if (context == null) return;
binding.storiesList.setLayoutManager(new LinearLayoutManager(context, LinearLayoutManager.HORIZONTAL, false));
storiesAdapter = new StoriesAdapter((model, position) -> { storiesAdapter = new StoriesAdapter((model, position) -> {
currentStory = model; currentStory = model;
slidePos = position; slidePos = position;
@ -294,6 +299,8 @@ public class StoryViewerFragment extends Fragment {
} }
hasFeedStories = models != null && !models.isEmpty(); hasFeedStories = models != null && !models.isEmpty();
final List<?> finalModels = models; final List<?> finalModels = models;
final Context context = getContext();
if (context == null) return;
swipeEvent = isRightSwipe -> { swipeEvent = isRightSwipe -> {
final List<StoryModel> storyModels = storiesViewModel.getList().getValue(); final List<StoryModel> storyModels = storiesViewModel.getList().getValue();
final int storiesLen = storyModels == null ? 0 : storyModels.size(); final int storiesLen = storyModels == null ? 0 : storyModels.size();
@ -307,7 +314,7 @@ public class StoryViewerFragment extends Fragment {
new SeenAction(cookie, currentStory).execute(); new SeenAction(cookie, currentStory).execute();
} }
if ((isRightSwipe && index == 0) || (isLeftSwipe && index == finalModels.size() - 1)) { if ((isRightSwipe && index == 0) || (isLeftSwipe && index == finalModels.size() - 1)) {
Toast.makeText(requireContext(), R.string.no_more_stories, Toast.LENGTH_SHORT).show(); Toast.makeText(context, R.string.no_more_stories, Toast.LENGTH_SHORT).show();
return; return;
} }
final Object feedStoryModel = isRightSwipe final Object feedStoryModel = isRightSwipe
@ -315,7 +322,7 @@ public class StoryViewerFragment extends Fragment {
: finalModels.size() == index + 1 ? null : finalModels.get(index + 1); : finalModels.size() == index + 1 ? null : finalModels.get(index + 1);
if (feedStoryModel != null) { if (feedStoryModel != null) {
if (fetching) { if (fetching) {
Toast.makeText(requireContext(), R.string.be_patient, Toast.LENGTH_SHORT).show(); Toast.makeText(context, R.string.be_patient, Toast.LENGTH_SHORT).show();
return; return;
} }
fetching = true; fetching = true;
@ -334,7 +341,7 @@ public class StoryViewerFragment extends Fragment {
currentStory = storyModels.get(slidePos); currentStory = storyModels.get(slidePos);
refreshStory(); refreshStory();
}; };
gestureDetector = new GestureDetectorCompat(requireContext(), new SwipeGestureListener(swipeEvent)); gestureDetector = new GestureDetectorCompat(context, new SwipeGestureListener(swipeEvent));
binding.playerView.setOnTouchListener((v, event) -> gestureDetector.onTouchEvent(event)); binding.playerView.setOnTouchListener((v, event) -> gestureDetector.onTouchEvent(event));
final GestureDetector.SimpleOnGestureListener simpleOnGestureListener = new GestureDetector.SimpleOnGestureListener() { final GestureDetector.SimpleOnGestureListener simpleOnGestureListener = new GestureDetector.SimpleOnGestureListener() {
@Override @Override
@ -382,22 +389,22 @@ public class StoryViewerFragment extends Fragment {
if (tag instanceof PollModel) { if (tag instanceof PollModel) {
poll = (PollModel) tag; poll = (PollModel) tag;
if (poll.getMyChoice() > -1) { if (poll.getMyChoice() > -1) {
new AlertDialog.Builder(requireContext()).setTitle(R.string.voted_story_poll) new AlertDialog.Builder(context).setTitle(R.string.voted_story_poll)
.setAdapter(new ArrayAdapter<>(requireContext(), android.R.layout.simple_list_item_1, .setAdapter(new ArrayAdapter<>(context, android.R.layout.simple_list_item_1,
new String[]{ new String[]{
(poll.getMyChoice() == 0 ? "" : "") + poll (poll.getMyChoice() == 0 ? "" : "") + poll
.getLeftChoice() + " (" + poll .getLeftChoice() + " (" + poll
.getLeftCount() + ")", .getLeftCount() + ")",
(poll.getMyChoice() == 1 ? "" : "") + poll (poll.getMyChoice() == 1 ? "" : "") + poll
.getRightChoice() + " (" + poll .getRightChoice() + " (" + poll
.getRightCount() + ")" .getRightCount() + ")"
}), null) }), null)
.setPositiveButton(R.string.ok, null) .setPositiveButton(R.string.ok, null)
.show(); .show();
} else { } else {
new AlertDialog.Builder(requireContext()) new AlertDialog.Builder(context)
.setTitle(poll.getQuestion()) .setTitle(poll.getQuestion())
.setAdapter(new ArrayAdapter<>(requireContext(), android.R.layout.simple_list_item_1, new String[]{ .setAdapter(new ArrayAdapter<>(context, android.R.layout.simple_list_item_1, new String[]{
poll.getLeftChoice() + " (" + poll.getLeftCount() + ")", poll.getLeftChoice() + " (" + poll.getLeftCount() + ")",
poll.getRightChoice() + " (" + poll.getRightCount() + ")" poll.getRightChoice() + " (" + poll.getRightCount() + ")"
}), (d, w) -> { }), (d, w) -> {
@ -405,10 +412,10 @@ public class StoryViewerFragment extends Fragment {
new VoteAction(currentStory, poll, cookie, choice -> { new VoteAction(currentStory, poll, cookie, choice -> {
if (choice > -1) { if (choice > -1) {
poll.setMyChoice(choice); poll.setMyChoice(choice);
Toast.makeText(requireContext(), R.string.votef_story_poll, Toast.LENGTH_SHORT).show(); Toast.makeText(context, R.string.votef_story_poll, Toast.LENGTH_SHORT).show();
return; return;
} }
Toast.makeText(requireContext(), R.string.downloader_unknown_error, Toast.LENGTH_SHORT).show(); Toast.makeText(context, R.string.downloader_unknown_error, Toast.LENGTH_SHORT).show();
}).execute(w); }).execute(w);
}) })
.setPositiveButton(R.string.cancel, null) .setPositiveButton(R.string.cancel, null)
@ -416,24 +423,24 @@ public class StoryViewerFragment extends Fragment {
} }
} else if (tag instanceof QuestionModel) { } else if (tag instanceof QuestionModel) {
question = (QuestionModel) tag; question = (QuestionModel) tag;
final EditText input = new EditText(requireContext()); final EditText input = new EditText(context);
input.setHint(R.string.answer_hint); input.setHint(R.string.answer_hint);
new AlertDialog.Builder(requireContext()) new AlertDialog.Builder(context)
.setTitle(question.getQuestion()) .setTitle(question.getQuestion())
.setView(input) .setView(input)
.setPositiveButton(R.string.ok, (d, w) -> new RespondAction(currentStory, question, cookie, result -> { .setPositiveButton(R.string.ok, (d, w) -> new RespondAction(currentStory, question, cookie, result -> {
if (result) { if (result) {
Toast.makeText(requireContext(), R.string.answered_story, Toast.LENGTH_SHORT).show(); Toast.makeText(context, R.string.answered_story, Toast.LENGTH_SHORT).show();
} else } else
Toast.makeText(requireContext(), R.string.downloader_unknown_error, Toast.LENGTH_SHORT).show(); Toast.makeText(context, R.string.downloader_unknown_error, Toast.LENGTH_SHORT).show();
}).execute(input.getText().toString())) }).execute(input.getText().toString()))
.setNegativeButton(R.string.cancel, null) .setNegativeButton(R.string.cancel, null)
.show(); .show();
} else if (tag instanceof String[]) { } else if (tag instanceof String[]) {
mentions = (String[]) tag; mentions = (String[]) tag;
new AlertDialog.Builder(requireContext()) new AlertDialog.Builder(context)
.setTitle(R.string.story_mentions) .setTitle(R.string.story_mentions)
.setAdapter(new ArrayAdapter<>(requireContext(), android.R.layout.simple_list_item_1, mentions), (d, w) -> { .setAdapter(new ArrayAdapter<>(context, android.R.layout.simple_list_item_1, mentions), (d, w) -> {
// searchUsername(mentions[w]); // searchUsername(mentions[w]);
}) })
.setPositiveButton(R.string.cancel, null) .setPositiveButton(R.string.cancel, null)
@ -443,17 +450,17 @@ public class StoryViewerFragment extends Fragment {
for (int q = 0; q < choices.length; ++q) { for (int q = 0; q < choices.length; ++q) {
choices[q] = (quiz.getMyChoice() == q ? "" : "") + quiz.getChoices()[q] + " (" + quiz.getCounts()[q] + ")"; choices[q] = (quiz.getMyChoice() == q ? "" : "") + quiz.getChoices()[q] + " (" + quiz.getCounts()[q] + ")";
} }
new AlertDialog.Builder(requireContext()) new AlertDialog.Builder(context)
.setTitle(quiz.getMyChoice() > -1 ? getString(R.string.story_quizzed) : quiz.getQuestion()) .setTitle(quiz.getMyChoice() > -1 ? getString(R.string.story_quizzed) : quiz.getQuestion())
.setAdapter(new ArrayAdapter<>(requireContext(), android.R.layout.simple_list_item_1, choices), (d, w) -> { .setAdapter(new ArrayAdapter<>(context, android.R.layout.simple_list_item_1, choices), (d, w) -> {
if (quiz.getMyChoice() == -1 && !TextUtils.isEmpty(cookie)) if (quiz.getMyChoice() == -1 && !TextUtils.isEmpty(cookie))
new QuizAction(currentStory, quiz, cookie, choice -> { new QuizAction(currentStory, quiz, cookie, choice -> {
if (choice > -1) { if (choice > -1) {
quiz.setMyChoice(choice); quiz.setMyChoice(choice);
Toast.makeText(requireContext(), R.string.answered_story, Toast.LENGTH_SHORT).show(); Toast.makeText(context, R.string.answered_story, Toast.LENGTH_SHORT).show();
return; return;
} }
Toast.makeText(requireContext(), R.string.downloader_unknown_error, Toast.LENGTH_SHORT).show(); Toast.makeText(context, R.string.downloader_unknown_error, Toast.LENGTH_SHORT).show();
}).execute(w); }).execute(w);
}) })
.setPositiveButton(R.string.cancel, null) .setPositiveButton(R.string.cancel, null)
@ -614,6 +621,8 @@ public class StoryViewerFragment extends Fragment {
private void downloadStory() { private void downloadStory() {
int error = 0; int error = 0;
final Context context = getContext();
if (context == null) return;
if (currentStory != null) { if (currentStory != null) {
File dir = new File(Environment.getExternalStorageDirectory(), "Download"); File dir = new File(Environment.getExternalStorageDirectory(), "Download");
@ -632,19 +641,19 @@ public class StoryViewerFragment extends Fragment {
final File saveFile = new File(dir, currentStory.getStoryMediaId() + "_" + currentStory.getTimestamp() final File saveFile = new File(dir, currentStory.getStoryMediaId() + "_" + currentStory.getTimestamp()
+ DownloadUtils.getExtensionFromModel(storyUrl, currentStory)); + DownloadUtils.getExtensionFromModel(storyUrl, currentStory));
new DownloadAsync(requireContext(), storyUrl, saveFile, result -> { new DownloadAsync(context, storyUrl, saveFile, result -> {
final int toastRes = result != null && result.exists() ? R.string.downloader_complete final int toastRes = result != null && result.exists() ? R.string.downloader_complete
: R.string.downloader_error_download_file; : R.string.downloader_error_download_file;
Toast.makeText(requireContext(), toastRes, Toast.LENGTH_SHORT).show(); Toast.makeText(context, toastRes, Toast.LENGTH_SHORT).show();
}).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); }).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
} else error = 1; } else error = 1;
} else error = 2; } else error = 2;
if (error == 1) if (error == 1)
Toast.makeText(requireContext(), R.string.downloader_error_creating_folder, Toast.LENGTH_SHORT).show(); Toast.makeText(context, R.string.downloader_error_creating_folder, Toast.LENGTH_SHORT).show();
else if (error == 2) else if (error == 2)
Toast.makeText(requireContext(), R.string.downloader_unknown_error, Toast.LENGTH_SHORT).show(); Toast.makeText(context, R.string.downloader_unknown_error, Toast.LENGTH_SHORT).show();
} }
private void setupImage() { private void setupImage() {
@ -688,11 +697,13 @@ public class StoryViewerFragment extends Fragment {
binding.imageViewer.setVisibility(View.GONE); binding.imageViewer.setVisibility(View.GONE);
binding.imageViewer.setController(null); binding.imageViewer.setController(null);
player = new SimpleExoPlayer.Builder(requireContext()).build(); final Context context = getContext();
if (context == null) return;
player = new SimpleExoPlayer.Builder(context).build();
binding.playerView.setPlayer(player); binding.playerView.setPlayer(player);
player.setPlayWhenReady(settingsHelper.getBoolean(Constants.AUTOPLAY_VIDEOS)); player.setPlayWhenReady(settingsHelper.getBoolean(Constants.AUTOPLAY_VIDEOS));
final ProgressiveMediaSource mediaSource = new ProgressiveMediaSource.Factory(new DefaultDataSourceFactory(requireContext(), "instagram")) final ProgressiveMediaSource mediaSource = new ProgressiveMediaSource.Factory(new DefaultDataSourceFactory(context, "instagram"))
.createMediaSource(Uri.parse(url)); .createMediaSource(Uri.parse(url));
mediaSource.addEventListener(new Handler(), new MediaSourceEventListener() { mediaSource.addEventListener(new Handler(), new MediaSourceEventListener() {
@Override @Override

View File

@ -1,5 +1,6 @@
package awais.instagrabber.fragments.directmessages; package awais.instagrabber.fragments.directmessages;
import android.content.Context;
import android.os.AsyncTask; import android.os.AsyncTask;
import android.os.Bundle; import android.os.Bundle;
import android.util.Log; import android.util.Log;
@ -98,7 +99,9 @@ public class DirectMessageInboxFragment extends Fragment implements SwipeRefresh
binding.swipeRefreshLayout.setOnRefreshListener(this); binding.swipeRefreshLayout.setOnRefreshListener(this);
inboxList = binding.inboxList; inboxList = binding.inboxList;
inboxList.setHasFixedSize(true); inboxList.setHasFixedSize(true);
layoutManager = new LinearLayoutManager(requireContext()); final Context context = getContext();
if (context == null) return root;
layoutManager = new LinearLayoutManager(context);
inboxList.setLayoutManager(layoutManager); inboxList.setLayoutManager(layoutManager);
final DirectMessageInboxAdapter inboxAdapter = new DirectMessageInboxAdapter(inboxThreadModel -> { final DirectMessageInboxAdapter inboxAdapter = new DirectMessageInboxAdapter(inboxThreadModel -> {
final NavDirections action = DirectMessageInboxFragmentDirections final NavDirections action = DirectMessageInboxFragmentDirections

View File

@ -1,5 +1,6 @@
package awais.instagrabber.fragments.directmessages; package awais.instagrabber.fragments.directmessages;
import android.content.Context;
import android.content.DialogInterface; import android.content.DialogInterface;
import android.os.AsyncTask; import android.os.AsyncTask;
import android.os.Bundle; import android.os.Bundle;
@ -100,7 +101,9 @@ public class DirectMessageSettingsFragment extends Fragment implements SwipeRefr
final Object tag = v.getTag(); final Object tag = v.getTag();
if (tag instanceof ProfileModel) { if (tag instanceof ProfileModel) {
ProfileModel model = (ProfileModel) tag; ProfileModel model = (ProfileModel) tag;
final ArrayAdapter<String> adapter = new ArrayAdapter<>(requireContext(), android.R.layout.simple_list_item_1, new String[]{ final Context context = getContext();
if (context == null) return;
final ArrayAdapter<String> adapter = new ArrayAdapter<>(context, android.R.layout.simple_list_item_1, new String[]{
getString(R.string.open_profile), getString(R.string.open_profile),
getString(R.string.dms_action_kick), getString(R.string.dms_action_kick),
}); });
@ -113,33 +116,36 @@ public class DirectMessageSettingsFragment extends Fragment implements SwipeRefr
onRefresh(); onRefresh();
} }
}; };
new AlertDialog.Builder(requireContext()) new AlertDialog.Builder(context)
.setAdapter(adapter, clickListener) .setAdapter(adapter, clickListener)
.show(); .show();
} }
}; };
} }
@NonNull
@Override @Override
public View onCreateView(@NonNull final LayoutInflater inflater, public View onCreateView(@NonNull final LayoutInflater inflater,
final ViewGroup container, final ViewGroup container,
final Bundle savedInstanceState) { final Bundle savedInstanceState) {
final FragmentDirectMessagesSettingsBinding binding = FragmentDirectMessagesSettingsBinding.inflate(inflater, container, false); final FragmentDirectMessagesSettingsBinding binding = FragmentDirectMessagesSettingsBinding.inflate(inflater, container, false);
final LinearLayout root = binding.getRoot(); final LinearLayout root = binding.getRoot();
final LinearLayoutManager layoutManager = new LinearLayoutManager(requireContext()) { final Context context = getContext();
if (context == null) return root;
final LinearLayoutManager layoutManager = new LinearLayoutManager(context) {
@Override @Override
public boolean canScrollVertically() { public boolean canScrollVertically() {
return false; return false;
} }
}; };
final LinearLayoutManager layoutManagerDos = new LinearLayoutManager(requireContext()) { final LinearLayoutManager layoutManagerDos = new LinearLayoutManager(context) {
@Override @Override
public boolean canScrollVertically() { public boolean canScrollVertically() {
return false; return false;
} }
}; };
if (getArguments() == null) { if (getArguments() == null) {
return null; return root;
} }
threadId = DirectMessageSettingsFragmentArgs.fromBundle(getArguments()).getThreadId(); threadId = DirectMessageSettingsFragmentArgs.fromBundle(getArguments()).getThreadId();
threadTitle = DirectMessageSettingsFragmentArgs.fromBundle(getArguments()).getTitle(); threadTitle = DirectMessageSettingsFragmentArgs.fromBundle(getArguments()).getTitle();
@ -175,7 +181,7 @@ public class DirectMessageSettingsFragment extends Fragment implements SwipeRefr
}); });
final AppCompatButton btnLeave = binding.btnLeave; final AppCompatButton btnLeave = binding.btnLeave;
btnLeave.setOnClickListener(v -> new AlertDialog.Builder(requireContext()) btnLeave.setOnClickListener(v -> new AlertDialog.Builder(context)
.setTitle(R.string.dms_action_leave_question) .setTitle(R.string.dms_action_leave_question)
.setPositiveButton(R.string.yes, .setPositiveButton(R.string.yes,
(x, y) -> new ChangeSettings(titleText.getText().toString()).execute("leave")) (x, y) -> new ChangeSettings(titleText.getText().toString()).execute("leave"))
@ -250,8 +256,10 @@ public class DirectMessageSettingsFragment extends Fragment implements SwipeRefr
@Override @Override
protected void onPostExecute(Void result) { protected void onPostExecute(Void result) {
final Context context = getContext();
if (context == null) return;
if (ok) { if (ok) {
Toast.makeText(requireContext(), R.string.dms_action_success, Toast.LENGTH_SHORT).show(); Toast.makeText(context, R.string.dms_action_success, Toast.LENGTH_SHORT).show();
if (action.equals("update_title")) { if (action.equals("update_title")) {
threadTitle = titleText.getText().toString(); threadTitle = titleText.getText().toString();
titleSend.setVisibility(View.GONE); titleSend.setVisibility(View.GONE);
@ -263,7 +271,7 @@ public class DirectMessageSettingsFragment extends Fragment implements SwipeRefr
} else { } else {
DirectMessageThreadFragment.hasSentSomething = true; DirectMessageThreadFragment.hasSentSomething = true;
} }
} else Toast.makeText(requireContext(), R.string.downloader_unknown_error, Toast.LENGTH_SHORT).show(); } else Toast.makeText(context, R.string.downloader_unknown_error, Toast.LENGTH_SHORT).show();
} }
} }
} }

View File

@ -1,6 +1,7 @@
package awais.instagrabber.fragments.directmessages; package awais.instagrabber.fragments.directmessages;
import android.app.Activity; import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface; import android.content.DialogInterface;
import android.content.Intent; import android.content.Intent;
import android.graphics.Bitmap; import android.graphics.Bitmap;
@ -101,7 +102,9 @@ public class DirectMessageThreadFragment extends Fragment {
if (v == binding.commentSend) { if (v == binding.commentSend) {
final String text = binding.commentText.getText().toString(); final String text = binding.commentText.getText().toString();
if (TextUtils.isEmpty(text)) { if (TextUtils.isEmpty(text)) {
Toast.makeText(requireContext(), R.string.comment_send_empty_comment, Toast.LENGTH_SHORT).show(); final Context context = getContext();
if (context == null) return;
Toast.makeText(context, R.string.comment_send_empty_comment, Toast.LENGTH_SHORT).show();
return; return;
} }
sendText(text, null, false); sendText(text, null, false);
@ -123,8 +126,11 @@ public class DirectMessageThreadFragment extends Fragment {
@Override @Override
public void onResult(final InboxThreadModel result) { public void onResult(final InboxThreadModel result) {
if (result == null && ("MINCURSOR".equals(cursor) || "MAXCURSOR".equals(cursor) || TextUtils.isEmpty(cursor))) if (result == null && ("MINCURSOR".equals(cursor) || "MAXCURSOR".equals(cursor) || TextUtils.isEmpty(cursor))) {
Toast.makeText(requireContext(), R.string.downloader_unknown_error, Toast.LENGTH_SHORT).show(); final Context context = getContext();
if (context == null) return;
Toast.makeText(context, R.string.downloader_unknown_error, Toast.LENGTH_SHORT).show();
}
if (result != null) { if (result != null) {
cursor = result.getOldestCursor(); cursor = result.getOldestCursor();
@ -209,7 +215,9 @@ public class DirectMessageThreadFragment extends Fragment {
messageList.setHasFixedSize(true); messageList.setHasFixedSize(true);
binding.commentSend.setOnClickListener(clickListener); binding.commentSend.setOnClickListener(clickListener);
binding.image.setOnClickListener(clickListener); binding.image.setOnClickListener(clickListener);
final LinearLayoutManager layoutManager = new LinearLayoutManager(requireContext()); final Context context = getContext();
if (context == null) return;
final LinearLayoutManager layoutManager = new LinearLayoutManager(context);
layoutManager.setReverseLayout(true); layoutManager.setReverseLayout(true);
messageList.setLayoutManager(layoutManager); messageList.setLayoutManager(layoutManager);
messageList.addOnScrollListener(new RecyclerLazyLoader(layoutManager, (page, totalItemsCount) -> { messageList.addOnScrollListener(new RecyclerLazyLoader(layoutManager, (page, totalItemsCount) -> {
@ -238,14 +246,14 @@ public class DirectMessageThreadFragment extends Fragment {
break; break;
case LINK: case LINK:
Intent linkIntent = new Intent(Intent.ACTION_VIEW); Intent linkIntent = new Intent(Intent.ACTION_VIEW);
linkIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_SINGLE_TOP); linkIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP);
linkIntent.setData(Uri.parse(directItemModel.getLinkModel().getLinkContext().getLinkUrl())); linkIntent.setData(Uri.parse(directItemModel.getLinkModel().getLinkContext().getLinkUrl()));
startActivity(linkIntent); startActivity(linkIntent);
break; break;
case TEXT: case TEXT:
case REEL_SHARE: case REEL_SHARE:
Utils.copyText(requireContext(), directItemModel.getText()); Utils.copyText(context, directItemModel.getText());
Toast.makeText(requireContext(), R.string.clipboard_copied, Toast.LENGTH_SHORT).show(); Toast.makeText(context, R.string.clipboard_copied, Toast.LENGTH_SHORT).show();
break; break;
case RAVEN_MEDIA: case RAVEN_MEDIA:
case MEDIA: case MEDIA:
@ -256,10 +264,10 @@ public class DirectMessageThreadFragment extends Fragment {
? selectedItem.getVideoUrl() ? selectedItem.getVideoUrl()
: selectedItem.getThumbUrl(); : selectedItem.getThumbUrl();
if (url == null) { if (url == null) {
Toast.makeText(requireContext(), R.string.downloader_unknown_error, Toast.LENGTH_SHORT).show(); Toast.makeText(context, R.string.downloader_unknown_error, Toast.LENGTH_SHORT).show();
} else { } else {
DownloadUtils.dmDownload(requireContext(), user.getUsername(), DownloadMethod.DOWNLOAD_DIRECT, selectedItem); DownloadUtils.dmDownload(context, user.getUsername(), DownloadMethod.DOWNLOAD_DIRECT, selectedItem);
Toast.makeText(requireContext(), R.string.downloader_downloading_media, Toast.LENGTH_SHORT).show(); Toast.makeText(context, R.string.downloader_downloading_media, Toast.LENGTH_SHORT).show();
} }
break; break;
case STORY_SHARE: case STORY_SHARE:
@ -275,7 +283,7 @@ public class DirectMessageThreadFragment extends Fragment {
// ); // );
// sm.setVideoUrl(directItemModel.getReelShare().getMedia().getVideoUrl()); // sm.setVideoUrl(directItemModel.getReelShare().getMedia().getVideoUrl());
// StoryModel[] sms = {sm}; // StoryModel[] sms = {sm};
// startActivity(new Intent(requireContext(), StoryViewer.class) // startActivity(new Intent(getContext(), StoryViewer.class)
// .putExtra(Constants.EXTRAS_USERNAME, directItemModel.getReelShare().getReelOwnerName()) // .putExtra(Constants.EXTRAS_USERNAME, directItemModel.getReelShare().getReelOwnerName())
// .putExtra(Constants.EXTRAS_STORIES, sms) // .putExtra(Constants.EXTRAS_STORIES, sms)
// ); // );
@ -292,10 +300,9 @@ public class DirectMessageThreadFragment extends Fragment {
} }
} else if (which == 1) { } else if (which == 1) {
sendText(null, directItemModel.getItemId(), directItemModel.isLiked()); sendText(null, directItemModel.getItemId(), directItemModel.isLiked());
} } else if (which == 2) {
else if (which == 2) {
if (directItemModel == null) if (directItemModel == null)
Toast.makeText(requireContext(), R.string.downloader_unknown_error, Toast.LENGTH_SHORT).show(); Toast.makeText(context, R.string.downloader_unknown_error, Toast.LENGTH_SHORT).show();
else if (String.valueOf(directItemModel.getUserId()).equals(myId)) else if (String.valueOf(directItemModel.getUserId()).equals(myId))
new ThreadAction().execute("delete", directItemModel.getItemId()); new ThreadAction().execute("delete", directItemModel.getItemId());
else searchUsername(getUser(directItemModel.getUserId()).getUsername()); else searchUsername(getUser(directItemModel.getUserId()).getUsername());
@ -346,9 +353,9 @@ public class DirectMessageThreadFragment extends Fragment {
getString(String.valueOf(directItemModel.getUserId()).equals(myId) ? R.string.dms_inbox_unsend : R.string.dms_inbox_author) getString(String.valueOf(directItemModel.getUserId()).equals(myId) ? R.string.dms_inbox_unsend : R.string.dms_inbox_author)
}; };
dialogAdapter = new ArrayAdapter<>(requireContext(), android.R.layout.simple_list_item_1, dialogList); dialogAdapter = new ArrayAdapter<>(context, android.R.layout.simple_list_item_1, dialogList);
new AlertDialog.Builder(requireContext()) new AlertDialog.Builder(context)
.setAdapter(dialogAdapter, onDialogListener) .setAdapter(dialogAdapter, onDialogListener)
.show(); .show();
} }
@ -435,7 +442,9 @@ public class DirectMessageThreadFragment extends Fragment {
} }
broadcast(text != null ? textOptions : reactionOptions, result -> { broadcast(text != null ? textOptions : reactionOptions, result -> {
if (result == null || result.getResponseCode() != HttpURLConnection.HTTP_OK) { if (result == null || result.getResponseCode() != HttpURLConnection.HTTP_OK) {
Toast.makeText(requireContext(), R.string.downloader_unknown_error, Toast.LENGTH_SHORT).show(); final Context context = getContext();
if (context == null) return;
Toast.makeText(context, R.string.downloader_unknown_error, Toast.LENGTH_SHORT).show();
return; return;
} }
if (text != null) { if (text != null) {
@ -455,14 +464,16 @@ public class DirectMessageThreadFragment extends Fragment {
} }
private void sendImage(final Uri imageUri) { private void sendImage(final Uri imageUri) {
try (InputStream inputStream = requireContext().getContentResolver().openInputStream(imageUri)) { final Context context = getContext();
if (context == null) return;
try (InputStream inputStream = context.getContentResolver().openInputStream(imageUri)) {
final Bitmap bitmap = BitmapFactory.decodeStream(inputStream); final Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
Toast.makeText(requireContext(), R.string.uploading, Toast.LENGTH_SHORT).show(); Toast.makeText(context, R.string.uploading, Toast.LENGTH_SHORT).show();
// Upload Image // Upload Image
final ImageUploader imageUploader = new ImageUploader(); final ImageUploader imageUploader = new ImageUploader();
imageUploader.setOnTaskCompleteListener(response -> { imageUploader.setOnTaskCompleteListener(response -> {
if (response == null || response.getResponseCode() != HttpURLConnection.HTTP_OK) { if (response == null || response.getResponseCode() != HttpURLConnection.HTTP_OK) {
Toast.makeText(requireContext(), R.string.downloader_unknown_error, Toast.LENGTH_SHORT).show(); Toast.makeText(context, R.string.downloader_unknown_error, Toast.LENGTH_SHORT).show();
if (response != null && response.getResponse() != null) { if (response != null && response.getResponse() != null) {
Log.e(TAG, response.getResponse().toString()); Log.e(TAG, response.getResponse().toString());
} }
@ -484,7 +495,7 @@ public class DirectMessageThreadFragment extends Fragment {
final ImageUploadOptions options = ImageUploadOptions.builder(bitmap).build(); final ImageUploadOptions options = ImageUploadOptions.builder(bitmap).build();
imageUploader.execute(options); imageUploader.execute(options);
} catch (IOException e) { } catch (IOException e) {
Toast.makeText(requireContext(), R.string.downloader_unknown_error, Toast.LENGTH_SHORT).show(); Toast.makeText(context, R.string.downloader_unknown_error, Toast.LENGTH_SHORT).show();
Log.e(TAG, "Error opening file", e); Log.e(TAG, "Error opening file", e);
} }
} }
@ -509,7 +520,6 @@ public class DirectMessageThreadFragment extends Fragment {
} }
private void searchUsername(final String text) { private void searchUsername(final String text) {
// startActivity(new Intent(requireContext(), ProfileViewer.class).putExtra(Constants.EXTRAS_USERNAME, text));
final NavDirections action = DirectMessageThreadFragmentDirections.actionGlobalProfileFragment("@" + text); final NavDirections action = DirectMessageThreadFragmentDirections.actionGlobalProfileFragment("@" + text);
NavHostFragment.findNavController(this).navigate(action); NavHostFragment.findNavController(this).navigate(action);
} }

View File

@ -1,5 +1,6 @@
package awais.instagrabber.fragments.main; package awais.instagrabber.fragments.main;
import android.content.Context;
import android.os.AsyncTask; import android.os.AsyncTask;
import android.os.Bundle; import android.os.Bundle;
import android.view.ActionMode; import android.view.ActionMode;
@ -36,13 +37,13 @@ import awais.instagrabber.customviews.helpers.GridAutofitLayoutManager;
import awais.instagrabber.customviews.helpers.GridSpacingItemDecoration; import awais.instagrabber.customviews.helpers.GridSpacingItemDecoration;
import awais.instagrabber.customviews.helpers.RecyclerLazyLoader; import awais.instagrabber.customviews.helpers.RecyclerLazyLoader;
import awais.instagrabber.databinding.FragmentDiscoverBinding; import awais.instagrabber.databinding.FragmentDiscoverBinding;
import awais.instagrabber.utils.DownloadUtils;
import awais.instagrabber.viewmodels.DiscoverItemViewModel;
import awais.instagrabber.interfaces.FetchListener; import awais.instagrabber.interfaces.FetchListener;
import awais.instagrabber.models.DiscoverItemModel; import awais.instagrabber.models.DiscoverItemModel;
import awais.instagrabber.models.DiscoverTopicModel; import awais.instagrabber.models.DiscoverTopicModel;
import awais.instagrabber.models.enums.DownloadMethod; import awais.instagrabber.models.enums.DownloadMethod;
import awais.instagrabber.utils.DownloadUtils;
import awais.instagrabber.utils.Utils; import awais.instagrabber.utils.Utils;
import awais.instagrabber.viewmodels.DiscoverItemViewModel;
public class DiscoverFragment extends Fragment implements SwipeRefreshLayout.OnRefreshListener { public class DiscoverFragment extends Fragment implements SwipeRefreshLayout.OnRefreshListener {
@ -70,8 +71,10 @@ public class DiscoverFragment extends Fragment implements SwipeRefreshLayout.OnR
if (result != null) { if (result != null) {
topicIds = result.getIds(); topicIds = result.getIds();
rankToken = result.getToken(); rankToken = result.getToken();
final Context context = getContext();
if (context == null) return;
final ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<>( final ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<>(
requireContext(), context,
android.R.layout.simple_spinner_dropdown_item, android.R.layout.simple_spinner_dropdown_item,
result.getNames() result.getNames()
); );
@ -87,7 +90,9 @@ public class DiscoverFragment extends Fragment implements SwipeRefreshLayout.OnR
public void onResult(final DiscoverItemModel[] result) { public void onResult(final DiscoverItemModel[] result) {
if (result == null || result.length <= 0) { if (result == null || result.length <= 0) {
binding.discoverSwipeRefreshLayout.setRefreshing(false); binding.discoverSwipeRefreshLayout.setRefreshing(false);
Toast.makeText(requireContext(), R.string.discover_empty, Toast.LENGTH_SHORT).show(); final Context context = getContext();
if (context == null) return;
Toast.makeText(context, R.string.discover_empty, Toast.LENGTH_SHORT).show();
return; return;
} }
List<DiscoverItemModel> current = discoverItemViewModel.getList().getValue(); List<DiscoverItemModel> current = discoverItemViewModel.getList().getValue();
@ -130,7 +135,9 @@ public class DiscoverFragment extends Fragment implements SwipeRefreshLayout.OnR
public boolean onActionItemClicked(final ActionMode mode, final MenuItem item) { public boolean onActionItemClicked(final ActionMode mode, final MenuItem item) {
if (item.getItemId() == R.id.action_download) { if (item.getItemId() == R.id.action_download) {
if (discoverAdapter == null) return false; if (discoverAdapter == null) return false;
DownloadUtils.batchDownload(requireContext(), final Context context = getContext();
if (context == null) return false;
DownloadUtils.batchDownload(context,
null, null,
DownloadMethod.DOWNLOAD_DISCOVER, DownloadMethod.DOWNLOAD_DISCOVER,
discoverAdapter.getSelectedModels()); discoverAdapter.getSelectedModels());
@ -178,7 +185,9 @@ public class DiscoverFragment extends Fragment implements SwipeRefreshLayout.OnR
private void setupExplore() { private void setupExplore() {
discoverItemViewModel = new ViewModelProvider(fragmentActivity).get(DiscoverItemViewModel.class); discoverItemViewModel = new ViewModelProvider(fragmentActivity).get(DiscoverItemViewModel.class);
final GridAutofitLayoutManager layoutManager = new GridAutofitLayoutManager(requireContext(), Utils.convertDpToPx(110)); final Context context = getContext();
if (context == null) return;
final GridAutofitLayoutManager layoutManager = new GridAutofitLayoutManager(context, Utils.convertDpToPx(110));
binding.discoverPosts.setLayoutManager(layoutManager); binding.discoverPosts.setLayoutManager(layoutManager);
binding.discoverPosts.addItemDecoration(new GridSpacingItemDecoration(Utils.convertDpToPx(4))); binding.discoverPosts.addItemDecoration(new GridSpacingItemDecoration(Utils.convertDpToPx(4)));
binding.discoverType.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { binding.discoverType.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {

View File

@ -1,5 +1,6 @@
package awais.instagrabber.fragments.main; package awais.instagrabber.fragments.main;
import android.content.Context;
import android.content.DialogInterface; import android.content.DialogInterface;
import android.net.Uri; import android.net.Uri;
import android.os.AsyncTask; import android.os.AsyncTask;
@ -54,14 +55,14 @@ import awais.instagrabber.models.ProfileModel;
import awais.instagrabber.models.ViewerPostModel; import awais.instagrabber.models.ViewerPostModel;
import awais.instagrabber.models.enums.DownloadMethod; import awais.instagrabber.models.enums.DownloadMethod;
import awais.instagrabber.models.enums.MediaItemType; import awais.instagrabber.models.enums.MediaItemType;
import awais.instagrabber.webservices.ServiceCallback;
import awais.instagrabber.webservices.StoriesService;
import awais.instagrabber.utils.Constants; import awais.instagrabber.utils.Constants;
import awais.instagrabber.utils.DownloadUtils; import awais.instagrabber.utils.DownloadUtils;
import awais.instagrabber.utils.NumberUtils; import awais.instagrabber.utils.NumberUtils;
import awais.instagrabber.utils.Utils; import awais.instagrabber.utils.Utils;
import awais.instagrabber.viewmodels.FeedStoriesViewModel; import awais.instagrabber.viewmodels.FeedStoriesViewModel;
import awais.instagrabber.viewmodels.FeedViewModel; import awais.instagrabber.viewmodels.FeedViewModel;
import awais.instagrabber.webservices.ServiceCallback;
import awais.instagrabber.webservices.StoriesService;
import static awais.instagrabber.utils.Utils.settingsHelper; import static awais.instagrabber.utils.Utils.settingsHelper;
@ -229,9 +230,11 @@ public class FeedFragment extends Fragment implements SwipeRefreshLayout.OnRefre
final ViewerPostModel[] sliderItems = feedModel.getSliderItems(); final ViewerPostModel[] sliderItems = feedModel.getSliderItems();
final Context context = getContext();
if (context == null) return;
if (feedModel if (feedModel
.getItemType() != MediaItemType.MEDIA_TYPE_SLIDER || sliderItems == null || sliderItems.length == 1) .getItemType() != MediaItemType.MEDIA_TYPE_SLIDER || sliderItems == null || sliderItems.length == 1)
DownloadUtils.batchDownload(requireContext(), DownloadUtils.batchDownload(context,
username, username,
DownloadMethod.DOWNLOAD_FEED, DownloadMethod.DOWNLOAD_FEED,
Collections.singletonList(feedModel)); Collections.singletonList(feedModel));
@ -257,14 +260,14 @@ public class FeedFragment extends Fragment implements SwipeRefreshLayout.OnRefre
postModels.add(sliderItems[0]); postModels.add(sliderItems[0]);
} }
if (postModels.size() > 0) { if (postModels.size() > 0) {
DownloadUtils.batchDownload(requireContext(), DownloadUtils.batchDownload(context,
username, username,
DownloadMethod.DOWNLOAD_FEED, DownloadMethod.DOWNLOAD_FEED,
postModels); postModels);
} }
}; };
new AlertDialog.Builder(requireContext()) new AlertDialog.Builder(context)
.setTitle(R.string.post_viewer_download_dialog_title).setPositiveButton( .setTitle(R.string.post_viewer_download_dialog_title).setPositiveButton(
R.string.post_viewer_download_current, R.string.post_viewer_download_current,
clickListener1) clickListener1)
@ -337,7 +340,9 @@ public class FeedFragment extends Fragment implements SwipeRefreshLayout.OnRefre
private void setupFeed() { private void setupFeed() {
feedViewModel = new ViewModelProvider(fragmentActivity).get(FeedViewModel.class); feedViewModel = new ViewModelProvider(fragmentActivity).get(FeedViewModel.class);
final LinearLayoutManager layoutManager = new LinearLayoutManager(requireContext()); final Context context = getContext();
if (context == null) return;
final LinearLayoutManager layoutManager = new LinearLayoutManager(context);
binding.feedRecyclerView.setLayoutManager(layoutManager); binding.feedRecyclerView.setLayoutManager(layoutManager);
binding.feedRecyclerView.setHasFixedSize(true); binding.feedRecyclerView.setHasFixedSize(true);
final FeedAdapter feedAdapter = new FeedAdapter(postViewClickListener, mentionClickListener); final FeedAdapter feedAdapter = new FeedAdapter(postViewClickListener, mentionClickListener);
@ -368,7 +373,9 @@ public class FeedFragment extends Fragment implements SwipeRefreshLayout.OnRefre
final NavDirections action = FeedFragmentDirections.actionFeedFragmentToStoryViewerFragment(position, null, false, null, null); final NavDirections action = FeedFragmentDirections.actionFeedFragmentToStoryViewerFragment(position, null, false, null, null);
NavHostFragment.findNavController(this).navigate(action); NavHostFragment.findNavController(this).navigate(action);
}); });
binding.feedStoriesRecyclerView.setLayoutManager(new LinearLayoutManager(requireContext(), RecyclerView.HORIZONTAL, false)); final Context context = getContext();
if (context == null) return;
binding.feedStoriesRecyclerView.setLayoutManager(new LinearLayoutManager(context, RecyclerView.HORIZONTAL, false));
binding.feedStoriesRecyclerView.setAdapter(feedStoriesAdapter); binding.feedStoriesRecyclerView.setAdapter(feedStoriesAdapter);
feedStoriesViewModel.getList().observe(fragmentActivity, feedStoriesAdapter::submitList); feedStoriesViewModel.getList().observe(fragmentActivity, feedStoriesAdapter::submitList);
fetchStories(); fetchStories();

View File

@ -1,5 +1,6 @@
package awais.instagrabber.fragments.main; package awais.instagrabber.fragments.main;
import android.content.Context;
import android.content.DialogInterface; import android.content.DialogInterface;
import android.content.res.ColorStateList; import android.content.res.ColorStateList;
import android.graphics.Typeface; import android.graphics.Typeface;
@ -74,9 +75,6 @@ import awais.instagrabber.models.enums.PostItemType;
import awais.instagrabber.models.enums.StoryViewerChoice; import awais.instagrabber.models.enums.StoryViewerChoice;
import awais.instagrabber.repositories.responses.FriendshipRepoChangeRootResponse; import awais.instagrabber.repositories.responses.FriendshipRepoChangeRootResponse;
import awais.instagrabber.repositories.responses.FriendshipRepoRestrictRootResponse; import awais.instagrabber.repositories.responses.FriendshipRepoRestrictRootResponse;
import awais.instagrabber.webservices.AloService;
import awais.instagrabber.webservices.FriendshipService;
import awais.instagrabber.webservices.ServiceCallback;
import awais.instagrabber.utils.Constants; import awais.instagrabber.utils.Constants;
import awais.instagrabber.utils.CookieUtils; import awais.instagrabber.utils.CookieUtils;
import awais.instagrabber.utils.DataBox; import awais.instagrabber.utils.DataBox;
@ -85,6 +83,9 @@ import awais.instagrabber.utils.TextUtils;
import awais.instagrabber.utils.Utils; import awais.instagrabber.utils.Utils;
import awais.instagrabber.viewmodels.HighlightsViewModel; import awais.instagrabber.viewmodels.HighlightsViewModel;
import awais.instagrabber.viewmodels.PostsViewModel; import awais.instagrabber.viewmodels.PostsViewModel;
import awais.instagrabber.webservices.AloService;
import awais.instagrabber.webservices.FriendshipService;
import awais.instagrabber.webservices.ServiceCallback;
import awaisomereport.LogCollector; import awaisomereport.LogCollector;
import static awais.instagrabber.utils.Utils.logCollector; import static awais.instagrabber.utils.Utils.logCollector;
@ -148,7 +149,9 @@ public class ProfileFragment extends Fragment implements SwipeRefreshLayout.OnRe
if (postsAdapter == null || username == null) { if (postsAdapter == null || username == null) {
return false; return false;
} }
DownloadUtils.batchDownload(requireContext(), final Context context = getContext();
if (context == null) return false;
DownloadUtils.batchDownload(context,
username, username,
DownloadMethod.DOWNLOAD_MAIN, DownloadMethod.DOWNLOAD_MAIN,
postsAdapter.getSelectedModels()); postsAdapter.getSelectedModels());
@ -351,19 +354,21 @@ public class ProfileFragment extends Fragment implements SwipeRefreshLayout.OnRe
} }
private void setProfileDetails() { private void setProfileDetails() {
final Context context = getContext();
if (context == null) return;
if (profileModel == null) { if (profileModel == null) {
binding.swipeRefreshLayout.setRefreshing(false); binding.swipeRefreshLayout.setRefreshing(false);
Toast.makeText(requireContext(), R.string.error_loading_profile, Toast.LENGTH_SHORT).show(); Toast.makeText(context, R.string.error_loading_profile, Toast.LENGTH_SHORT).show();
return; return;
} }
binding.isVerified.setVisibility(profileModel.isVerified() ? View.VISIBLE : View.GONE); binding.isVerified.setVisibility(profileModel.isVerified() ? View.VISIBLE : View.GONE);
final String profileId = profileModel.getId(); final String profileId = profileModel.getId();
if (settingsHelper.getString(Constants.STORY_VIEWER) == StoryViewerChoice.STORIESIG.getValue() || isLoggedIn) { if (settingsHelper.getString(Constants.STORY_VIEWER).equals(StoryViewerChoice.STORIESIG.getValue()) || isLoggedIn) {
new iStoryStatusFetcher(profileId, new iStoryStatusFetcher(profileId,
profileModel.getUsername(), profileModel.getUsername(),
false, false,
false, false,
!isLoggedIn && settingsHelper.getString(Constants.STORY_VIEWER) == StoryViewerChoice.STORIESIG.getValue(), !isLoggedIn && settingsHelper.getString(Constants.STORY_VIEWER).equals(StoryViewerChoice.STORIESIG.getValue()),
false, false,
result -> { result -> {
storyModels = result; storyModels = result;
@ -372,19 +377,18 @@ public class ProfileFragment extends Fragment implements SwipeRefreshLayout.OnRe
} }
}).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); }).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
new HighlightsFetcher(profileId, new HighlightsFetcher(profileId,
!isLoggedIn && settingsHelper.getString(Constants.STORY_VIEWER) == StoryViewerChoice.STORIESIG.getValue(), !isLoggedIn && settingsHelper.getString(Constants.STORY_VIEWER).equals(StoryViewerChoice.STORIESIG.getValue()),
result -> { result -> {
if (result != null) { if (result != null) {
binding.highlightsList.setVisibility(View.VISIBLE); binding.highlightsList.setVisibility(View.VISIBLE);
highlightsViewModel.getList().postValue(result); highlightsViewModel.getList().postValue(result);
} else binding.highlightsList.setVisibility(View.GONE); } else binding.highlightsList.setVisibility(View.GONE);
}).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); }).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
} } else if (settingsHelper.getString(Constants.STORY_VIEWER).equals(StoryViewerChoice.ALOINSTAGRAM.getValue())) {
else if (settingsHelper.getString(Constants.STORY_VIEWER).equals(StoryViewerChoice.ALOINSTAGRAM.getValue())) {
Log.d("austin_debug", "alo triggered"); Log.d("austin_debug", "alo triggered");
aloService.getUserStory(profileId, profileModel.getUsername(), false, new ServiceCallback<List<StoryModel>>() { aloService.getUserStory(profileId, profileModel.getUsername(), false, new ServiceCallback<List<StoryModel>>() {
@Override @Override
public void onSuccess(final List<StoryModel> result){ public void onSuccess(final List<StoryModel> result) {
if (result != null && result.size() > 0) { if (result != null && result.size() > 0) {
storyModels = result.toArray(storyModels); storyModels = result.toArray(storyModels);
binding.mainProfileImage.setStoriesBorder(); binding.mainProfileImage.setStoriesBorder();
@ -406,7 +410,7 @@ public class ProfileFragment extends Fragment implements SwipeRefreshLayout.OnRe
binding.btnLiked.setVisibility(View.VISIBLE); binding.btnLiked.setVisibility(View.VISIBLE);
binding.btnSaved.setText(R.string.saved); binding.btnSaved.setText(R.string.saved);
ViewCompat.setBackgroundTintList(binding.btnSaved, ViewCompat.setBackgroundTintList(binding.btnSaved,
ColorStateList.valueOf(ContextCompat.getColor(requireContext(), R.color.btn_orange_background))); ColorStateList.valueOf(ContextCompat.getColor(context, R.color.btn_orange_background)));
} else { } else {
binding.btnTagged.setVisibility(View.GONE); binding.btnTagged.setVisibility(View.GONE);
binding.btnSaved.setVisibility(View.GONE); binding.btnSaved.setVisibility(View.GONE);
@ -415,54 +419,54 @@ public class ProfileFragment extends Fragment implements SwipeRefreshLayout.OnRe
if (profileModel.getFollowing()) { if (profileModel.getFollowing()) {
binding.btnFollow.setText(R.string.unfollow); binding.btnFollow.setText(R.string.unfollow);
ViewCompat.setBackgroundTintList(binding.btnFollow, ViewCompat.setBackgroundTintList(binding.btnFollow,
ColorStateList.valueOf(ContextCompat.getColor(requireContext(), R.color.btn_purple_background))); ColorStateList.valueOf(ContextCompat.getColor(context, R.color.btn_purple_background)));
} else if (profileModel.getRequested()) { } else if (profileModel.getRequested()) {
binding.btnFollow.setText(R.string.cancel); binding.btnFollow.setText(R.string.cancel);
ViewCompat.setBackgroundTintList(binding.btnFollow, ViewCompat.setBackgroundTintList(binding.btnFollow,
ColorStateList.valueOf(ContextCompat.getColor(requireContext(), R.color.btn_purple_background))); ColorStateList.valueOf(ContextCompat.getColor(context, R.color.btn_purple_background)));
} else { } else {
binding.btnFollow.setText(R.string.follow); binding.btnFollow.setText(R.string.follow);
ViewCompat.setBackgroundTintList(binding.btnFollow, ViewCompat.setBackgroundTintList(binding.btnFollow,
ColorStateList.valueOf(ContextCompat.getColor(requireContext(), R.color.btn_pink_background))); ColorStateList.valueOf(ContextCompat.getColor(context, R.color.btn_pink_background)));
} }
binding.btnRestrict.setVisibility(View.VISIBLE); binding.btnRestrict.setVisibility(View.VISIBLE);
if (profileModel.getRestricted()) { if (profileModel.getRestricted()) {
binding.btnRestrict.setText(R.string.unrestrict); binding.btnRestrict.setText(R.string.unrestrict);
ViewCompat.setBackgroundTintList(binding.btnRestrict, ViewCompat.setBackgroundTintList(binding.btnRestrict,
ColorStateList.valueOf(ContextCompat.getColor(requireContext(), R.color.btn_green_background))); ColorStateList.valueOf(ContextCompat.getColor(context, R.color.btn_green_background)));
} else { } else {
binding.btnRestrict.setText(R.string.restrict); binding.btnRestrict.setText(R.string.restrict);
ViewCompat.setBackgroundTintList(binding.btnRestrict, ViewCompat.setBackgroundTintList(binding.btnRestrict,
ColorStateList.valueOf(ContextCompat.getColor(requireContext(), R.color.btn_orange_background))); ColorStateList.valueOf(ContextCompat.getColor(context, R.color.btn_orange_background)));
} }
binding.btnBlock.setVisibility(View.VISIBLE); binding.btnBlock.setVisibility(View.VISIBLE);
binding.btnTagged.setVisibility(View.VISIBLE); binding.btnTagged.setVisibility(View.VISIBLE);
if (profileModel.getBlocked()) { if (profileModel.getBlocked()) {
binding.btnBlock.setText(R.string.unblock); binding.btnBlock.setText(R.string.unblock);
ViewCompat.setBackgroundTintList(binding.btnBlock, ViewCompat.setBackgroundTintList(binding.btnBlock,
ColorStateList.valueOf(ContextCompat.getColor(requireContext(), R.color.btn_green_background))); ColorStateList.valueOf(ContextCompat.getColor(context, R.color.btn_green_background)));
} else { } else {
binding.btnBlock.setText(R.string.block); binding.btnBlock.setText(R.string.block);
ViewCompat.setBackgroundTintList(binding.btnBlock, ViewCompat.setBackgroundTintList(binding.btnBlock,
ColorStateList.valueOf(ContextCompat.getColor(requireContext(), R.color.btn_red_background))); ColorStateList.valueOf(ContextCompat.getColor(context, R.color.btn_red_background)));
} }
} }
} else { } else {
if (Utils.dataBox.getFavorite(username) != null) { if (Utils.dataBox.getFavorite(username) != null) {
binding.btnFollow.setText(R.string.unfavorite_short); binding.btnFollow.setText(R.string.unfavorite_short);
ViewCompat.setBackgroundTintList(binding.btnFollow, ViewCompat.setBackgroundTintList(binding.btnFollow,
ColorStateList.valueOf(ContextCompat.getColor(requireContext(), R.color.btn_purple_background))); ColorStateList.valueOf(ContextCompat.getColor(context, R.color.btn_purple_background)));
} else { } else {
binding.btnFollow.setText(R.string.favorite_short); binding.btnFollow.setText(R.string.favorite_short);
ViewCompat.setBackgroundTintList(binding.btnFollow, ViewCompat.setBackgroundTintList(binding.btnFollow,
ColorStateList.valueOf(ContextCompat.getColor(requireContext(), R.color.btn_pink_background))); ColorStateList.valueOf(ContextCompat.getColor(context, R.color.btn_pink_background)));
} }
binding.btnFollow.setVisibility(View.VISIBLE); binding.btnFollow.setVisibility(View.VISIBLE);
if (!profileModel.isReallyPrivate()) { if (!profileModel.isReallyPrivate()) {
binding.btnRestrict.setVisibility(View.VISIBLE); binding.btnRestrict.setVisibility(View.VISIBLE);
binding.btnRestrict.setText(R.string.tagged); binding.btnRestrict.setText(R.string.tagged);
ViewCompat.setBackgroundTintList(binding.btnRestrict, ViewCompat.setBackgroundTintList(binding.btnRestrict,
ColorStateList.valueOf(ContextCompat.getColor(requireContext(), R.color.btn_blue_background))); ColorStateList.valueOf(ContextCompat.getColor(context, R.color.btn_blue_background)));
} }
} }
@ -717,7 +721,9 @@ public class ProfileFragment extends Fragment implements SwipeRefreshLayout.OnRe
} }
showProfilePicDialog(); showProfilePicDialog();
}; };
new AlertDialog.Builder(requireContext()) final Context context = getContext();
if (context == null) return;
new AlertDialog.Builder(context)
.setItems(options, profileDialogListener) .setItems(options, profileDialogListener)
.setNeutralButton(R.string.cancel, null) .setNeutralButton(R.string.cancel, null)
.show(); .show();
@ -742,7 +748,9 @@ public class ProfileFragment extends Fragment implements SwipeRefreshLayout.OnRe
private void setupPosts() { private void setupPosts() {
postsViewModel = new ViewModelProvider(this).get(PostsViewModel.class); postsViewModel = new ViewModelProvider(this).get(PostsViewModel.class);
final GridAutofitLayoutManager layoutManager = new GridAutofitLayoutManager(requireContext(), Utils.convertDpToPx(110)); final Context context = getContext();
if (context == null) return;
final GridAutofitLayoutManager layoutManager = new GridAutofitLayoutManager(context, Utils.convertDpToPx(110));
binding.mainPosts.setLayoutManager(layoutManager); binding.mainPosts.setLayoutManager(layoutManager);
binding.mainPosts.addItemDecoration(new GridSpacingItemDecoration(Utils.convertDpToPx(4))); binding.mainPosts.addItemDecoration(new GridSpacingItemDecoration(Utils.convertDpToPx(4)));
postsAdapter = new PostsAdapter((postModel, position) -> { postsAdapter = new PostsAdapter((postModel, position) -> {
@ -804,7 +812,9 @@ public class ProfileFragment extends Fragment implements SwipeRefreshLayout.OnRe
.actionProfileFragmentToStoryViewerFragment(position, model.getTitle(), false, null, null); .actionProfileFragmentToStoryViewerFragment(position, model.getTitle(), false, null, null);
NavHostFragment.findNavController(this).navigate(action); NavHostFragment.findNavController(this).navigate(action);
}); });
final RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(requireContext(), RecyclerView.HORIZONTAL, false); final Context context = getContext();
if (context == null) return;
final RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(context, RecyclerView.HORIZONTAL, false);
binding.highlightsList.setLayoutManager(layoutManager); binding.highlightsList.setLayoutManager(layoutManager);
binding.highlightsList.setAdapter(highlightsAdapter); binding.highlightsList.setAdapter(highlightsAdapter);
highlightsViewModel.getList().observe(getViewLifecycleOwner(), highlightModels -> highlightsAdapter.submitList(highlightModels)); highlightsViewModel.getList().observe(getViewLifecycleOwner(), highlightModels -> highlightsAdapter.submitList(highlightModels));

View File

@ -2,44 +2,23 @@ package awais.instagrabber.fragments.settings;
import android.content.Context; import android.content.Context;
import android.content.Intent; import android.content.Intent;
import android.content.res.TypedArray;
import android.net.Uri; import android.net.Uri;
import android.view.View;
import androidx.annotation.NonNull;
import androidx.appcompat.widget.AppCompatButton;
import androidx.appcompat.widget.AppCompatTextView; import androidx.appcompat.widget.AppCompatTextView;
import androidx.fragment.app.FragmentActivity;
import androidx.preference.ListPreference;
import androidx.preference.Preference; import androidx.preference.Preference;
import androidx.preference.PreferenceCategory; import androidx.preference.PreferenceCategory;
import androidx.preference.PreferenceScreen; import androidx.preference.PreferenceScreen;
import androidx.preference.PreferenceViewHolder;
import androidx.preference.SwitchPreferenceCompat;
import com.google.android.material.switchmaterial.SwitchMaterial;
import java.text.SimpleDateFormat;
import java.util.Date;
import awais.instagrabber.R; import awais.instagrabber.R;
import awais.instagrabber.dialogs.TimeSettingsDialog;
import awais.instagrabber.utils.Constants;
import awais.instagrabber.utils.CookieUtils;
import awais.instagrabber.utils.DirectoryChooser;
import awais.instagrabber.utils.TextUtils;
import awais.instagrabber.utils.Utils;
import static awais.instagrabber.utils.Constants.FOLDER_PATH;
import static awais.instagrabber.utils.Constants.FOLDER_SAVE_TO;
import static awais.instagrabber.utils.Utils.settingsHelper;
public class AboutFragment extends BasePreferencesFragment { public class AboutFragment extends BasePreferencesFragment {
private static AppCompatTextView customPathTextView; private static AppCompatTextView customPathTextView;
@Override @Override
void setupPreferenceScreen(final PreferenceScreen screen) { void setupPreferenceScreen(final PreferenceScreen screen) {
final PreferenceCategory generalCategory = new PreferenceCategory(requireContext()); final Context context = getContext();
if (context == null) return;
final PreferenceCategory generalCategory = new PreferenceCategory(context);
screen.addPreference(generalCategory); screen.addPreference(generalCategory);
generalCategory.setTitle(R.string.pref_category_general); generalCategory.setTitle(R.string.pref_category_general);
generalCategory.setIconSpaceReserved(false); generalCategory.setIconSpaceReserved(false);
@ -47,7 +26,7 @@ public class AboutFragment extends BasePreferencesFragment {
generalCategory.addPreference(getRepoPreference()); generalCategory.addPreference(getRepoPreference());
generalCategory.addPreference(getFeedbackPreference()); generalCategory.addPreference(getFeedbackPreference());
final PreferenceCategory thirdPartyCategory = new PreferenceCategory(requireContext()); final PreferenceCategory thirdPartyCategory = new PreferenceCategory(context);
screen.addPreference(thirdPartyCategory); screen.addPreference(thirdPartyCategory);
thirdPartyCategory.setTitle(R.string.about_category_3pt); thirdPartyCategory.setTitle(R.string.about_category_3pt);
thirdPartyCategory.setSummary(R.string.about_category_3pt_summary); thirdPartyCategory.setSummary(R.string.about_category_3pt_summary);
@ -58,7 +37,7 @@ public class AboutFragment extends BasePreferencesFragment {
thirdPartyCategory.addPreference(getJsoupPreference()); thirdPartyCategory.addPreference(getJsoupPreference());
thirdPartyCategory.addPreference(getRetrofitPreference()); thirdPartyCategory.addPreference(getRetrofitPreference());
final PreferenceCategory licenseCategory = new PreferenceCategory(requireContext()); final PreferenceCategory licenseCategory = new PreferenceCategory(context);
screen.addPreference(licenseCategory); screen.addPreference(licenseCategory);
licenseCategory.setTitle(R.string.about_category_license); licenseCategory.setTitle(R.string.about_category_license);
licenseCategory.setIconSpaceReserved(false); licenseCategory.setIconSpaceReserved(false);
@ -67,7 +46,9 @@ public class AboutFragment extends BasePreferencesFragment {
} }
private Preference getDocsPreference() { private Preference getDocsPreference() {
final Preference preference = new Preference(requireContext()); final Context context = getContext();
if (context == null) return null;
final Preference preference = new Preference(context);
preference.setTitle(R.string.about_documentation); preference.setTitle(R.string.about_documentation);
preference.setSummary(R.string.about_documentation_summary); preference.setSummary(R.string.about_documentation_summary);
preference.setIconSpaceReserved(false); preference.setIconSpaceReserved(false);
@ -81,7 +62,9 @@ public class AboutFragment extends BasePreferencesFragment {
} }
private Preference getRepoPreference() { private Preference getRepoPreference() {
final Preference preference = new Preference(requireContext()); final Context context = getContext();
if (context == null) return null;
final Preference preference = new Preference(context);
preference.setTitle(R.string.about_repository); preference.setTitle(R.string.about_repository);
preference.setSummary(R.string.about_repository_summary); preference.setSummary(R.string.about_repository_summary);
preference.setIconSpaceReserved(false); preference.setIconSpaceReserved(false);
@ -95,21 +78,25 @@ public class AboutFragment extends BasePreferencesFragment {
} }
private Preference getFeedbackPreference() { private Preference getFeedbackPreference() {
final Preference preference = new Preference(requireContext()); final Context context = getContext();
if (context == null) return null;
final Preference preference = new Preference(context);
preference.setTitle(R.string.about_feedback); preference.setTitle(R.string.about_feedback);
preference.setSummary(R.string.about_feedback_summary); preference.setSummary(R.string.about_feedback_summary);
preference.setIconSpaceReserved(false); preference.setIconSpaceReserved(false);
preference.setOnPreferenceClickListener(p -> { preference.setOnPreferenceClickListener(p -> {
final Intent intent = new Intent(Intent.ACTION_SENDTO); final Intent intent = new Intent(Intent.ACTION_SENDTO);
intent.setData(Uri.parse(getString(R.string.about_feedback_summary))); intent.setData(Uri.parse(getString(R.string.about_feedback_summary)));
if (intent.resolveActivity(requireContext().getPackageManager()) != null) startActivity(intent); if (intent.resolveActivity(context.getPackageManager()) != null) startActivity(intent);
return true; return true;
}); });
return preference; return preference;
} }
private Preference getRetrofitPreference() { private Preference getRetrofitPreference() {
final Preference preference = new Preference(requireContext()); final Context context = getContext();
if (context == null) return null;
final Preference preference = new Preference(context);
preference.setTitle("Retrofit"); preference.setTitle("Retrofit");
preference.setSummary("Copyright 2013 Square, Inc. Apache Version 2.0."); preference.setSummary("Copyright 2013 Square, Inc. Apache Version 2.0.");
preference.setIconSpaceReserved(false); preference.setIconSpaceReserved(false);
@ -123,7 +110,9 @@ public class AboutFragment extends BasePreferencesFragment {
} }
private Preference getJsoupPreference() { private Preference getJsoupPreference() {
final Preference preference = new Preference(requireContext()); final Context context = getContext();
if (context == null) return null;
final Preference preference = new Preference(context);
preference.setTitle("jsoup"); preference.setTitle("jsoup");
preference.setSummary("Copyright (c) 2009-2020 Jonathan Hedley. MIT License."); preference.setSummary("Copyright (c) 2009-2020 Jonathan Hedley. MIT License.");
preference.setIconSpaceReserved(false); preference.setIconSpaceReserved(false);
@ -137,7 +126,9 @@ public class AboutFragment extends BasePreferencesFragment {
} }
private Preference getFrescoPreference() { private Preference getFrescoPreference() {
final Preference preference = new Preference(requireContext()); final Context context = getContext();
if (context == null) return null;
final Preference preference = new Preference(context);
preference.setTitle("Fresco"); preference.setTitle("Fresco");
preference.setSummary("Copyright (c) Facebook, Inc. and its affiliates. MIT License."); preference.setSummary("Copyright (c) Facebook, Inc. and its affiliates. MIT License.");
preference.setIconSpaceReserved(false); preference.setIconSpaceReserved(false);
@ -151,7 +142,9 @@ public class AboutFragment extends BasePreferencesFragment {
} }
private Preference getExoPlayerPreference() { private Preference getExoPlayerPreference() {
final Preference preference = new Preference(requireContext()); final Context context = getContext();
if (context == null) return null;
final Preference preference = new Preference(context);
preference.setTitle("ExoPlayer"); preference.setTitle("ExoPlayer");
preference.setSummary("Copyright (C) 2016 The Android Open Source Project. Apache Version 2.0."); preference.setSummary("Copyright (C) 2016 The Android Open Source Project. Apache Version 2.0.");
preference.setIconSpaceReserved(false); preference.setIconSpaceReserved(false);
@ -165,7 +158,9 @@ public class AboutFragment extends BasePreferencesFragment {
} }
private Preference getLicensePreference() { private Preference getLicensePreference() {
final Preference preference = new Preference(requireContext()); final Context context = getContext();
if (context == null) return null;
final Preference preference = new Preference(context);
preference.setSummary(R.string.license); preference.setSummary(R.string.license);
preference.setEnabled(false); preference.setEnabled(false);
preference.setIcon(R.drawable.ic_outline_info_24); preference.setIcon(R.drawable.ic_outline_info_24);
@ -174,7 +169,9 @@ public class AboutFragment extends BasePreferencesFragment {
} }
private Preference getLiabilityPreference() { private Preference getLiabilityPreference() {
final Preference preference = new Preference(requireContext()); final Context context = getContext();
if (context == null) return null;
final Preference preference = new Preference(context);
preference.setSummary(R.string.liability); preference.setSummary(R.string.liability);
preference.setEnabled(false); preference.setEnabled(false);
preference.setIcon(R.drawable.ic_warning); preference.setIcon(R.drawable.ic_warning);

View File

@ -1,5 +1,6 @@
package awais.instagrabber.fragments.settings; package awais.instagrabber.fragments.settings;
import android.content.Context;
import android.content.SharedPreferences; import android.content.SharedPreferences;
import android.os.Bundle; import android.os.Bundle;
@ -19,7 +20,9 @@ public abstract class BasePreferencesFragment extends PreferenceFragmentCompat i
final PreferenceManager preferenceManager = getPreferenceManager(); final PreferenceManager preferenceManager = getPreferenceManager();
preferenceManager.setSharedPreferencesName("settings"); preferenceManager.setSharedPreferencesName("settings");
preferenceManager.getSharedPreferences().registerOnSharedPreferenceChangeListener(this); preferenceManager.getSharedPreferences().registerOnSharedPreferenceChangeListener(this);
final PreferenceScreen screen = preferenceManager.createPreferenceScreen(requireContext()); final Context context = getContext();
if (context == null) return;
final PreferenceScreen screen = preferenceManager.createPreferenceScreen(context);
setupPreferenceScreen(screen); setupPreferenceScreen(screen);
setPreferenceScreen(screen); setPreferenceScreen(screen);
} }

View File

@ -9,7 +9,6 @@ import android.view.View;
import android.widget.ArrayAdapter; import android.widget.ArrayAdapter;
import android.widget.Toast; import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable; import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog; import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity; import androidx.appcompat.app.AppCompatActivity;
@ -21,6 +20,7 @@ import androidx.preference.PreferenceCategory;
import androidx.preference.PreferenceScreen; import androidx.preference.PreferenceScreen;
import androidx.preference.PreferenceViewHolder; import androidx.preference.PreferenceViewHolder;
import java.util.ArrayList;
import java.util.Collections; import java.util.Collections;
import java.util.List; import java.util.List;
@ -31,14 +31,14 @@ import awais.instagrabber.adapters.AccountSwitcherListAdapter;
import awais.instagrabber.adapters.AccountSwitcherListAdapter.OnAccountClickListener; import awais.instagrabber.adapters.AccountSwitcherListAdapter.OnAccountClickListener;
import awais.instagrabber.databinding.PrefAccountSwitcherBinding; import awais.instagrabber.databinding.PrefAccountSwitcherBinding;
import awais.instagrabber.repositories.responses.UserInfo; import awais.instagrabber.repositories.responses.UserInfo;
import awais.instagrabber.webservices.ProfileService;
import awais.instagrabber.webservices.ServiceCallback;
import awais.instagrabber.utils.Constants; import awais.instagrabber.utils.Constants;
import awais.instagrabber.utils.CookieUtils; import awais.instagrabber.utils.CookieUtils;
import awais.instagrabber.utils.DataBox; import awais.instagrabber.utils.DataBox;
import awais.instagrabber.utils.FlavorTown; import awais.instagrabber.utils.FlavorTown;
import awais.instagrabber.utils.TextUtils; import awais.instagrabber.utils.TextUtils;
import awais.instagrabber.utils.Utils; import awais.instagrabber.utils.Utils;
import awais.instagrabber.webservices.ProfileService;
import awais.instagrabber.webservices.ServiceCallback;
import static awais.instagrabber.adapters.AccountSwitcherListAdapter.OnAccountLongClickListener; import static awais.instagrabber.adapters.AccountSwitcherListAdapter.OnAccountLongClickListener;
import static awais.instagrabber.utils.Utils.settingsHelper; import static awais.instagrabber.utils.Utils.settingsHelper;
@ -53,21 +53,15 @@ public class MorePreferencesFragment extends BasePreferencesFragment {
void setupPreferenceScreen(final PreferenceScreen screen) { void setupPreferenceScreen(final PreferenceScreen screen) {
final String cookie = settingsHelper.getString(Constants.COOKIE); final String cookie = settingsHelper.getString(Constants.COOKIE);
final boolean isLoggedIn = !TextUtils.isEmpty(cookie) && CookieUtils.getUserIdFromCookie(cookie) != null; final boolean isLoggedIn = !TextUtils.isEmpty(cookie) && CookieUtils.getUserIdFromCookie(cookie) != null;
// screen.addPreference(new MoreHeaderPreference(requireContext())); // screen.addPreference(new MoreHeaderPreference(getContext()));
final PreferenceCategory accountCategory = new PreferenceCategory(requireContext()); final Context context = getContext();
if (context == null) return;
final PreferenceCategory accountCategory = new PreferenceCategory(context);
accountCategory.setTitle(R.string.account); accountCategory.setTitle(R.string.account);
accountCategory.setIconSpaceReserved(false); accountCategory.setIconSpaceReserved(false);
screen.addPreference(accountCategory); screen.addPreference(accountCategory);
// To re-login, user can just add the same account back from account switcher dialog final ArrayList<DataBox.CookieModel> allCookies = Utils.dataBox.getAllCookies();
// accountCategory.addPreference(getPreference(
// isLoggedIn ? R.string.relogin : R.string.login,
// isLoggedIn ? R.string.relogin_summary : -1,
// -1,
// preference -> {
// startActivityForResult(new Intent(requireContext(), Login.class), Constants.LOGIN_RESULT_CODE);
// return true;
// }));
if (isLoggedIn) { if (isLoggedIn) {
accountCategory.setSummary(R.string.account_hint); accountCategory.setSummary(R.string.account_hint);
accountCategory.addPreference(getAccountSwitcherPreference(cookie)); accountCategory.addPreference(getAccountSwitcherPreference(cookie));
@ -75,12 +69,12 @@ public class MorePreferencesFragment extends BasePreferencesFragment {
if (getContext() == null) return false; if (getContext() == null) return false;
CookieUtils.setupCookies("LOGOUT"); CookieUtils.setupCookies("LOGOUT");
shouldRecreate(); shouldRecreate();
Toast.makeText(requireContext(), R.string.logout_success, Toast.LENGTH_SHORT).show(); Toast.makeText(context, R.string.logout_success, Toast.LENGTH_SHORT).show();
settingsHelper.putString(Constants.COOKIE, ""); settingsHelper.putString(Constants.COOKIE, "");
return true; return true;
})); }));
} else { } else {
if (Utils.dataBox.getAllCookies().size() > 0) { if (allCookies != null && allCookies.size() > 0) {
accountCategory.addPreference(getAccountSwitcherPreference(null)); accountCategory.addPreference(getAccountSwitcherPreference(null));
} }
// Need to show something to trigger login activity // Need to show something to trigger login activity
@ -90,7 +84,7 @@ public class MorePreferencesFragment extends BasePreferencesFragment {
})); }));
} }
if (Utils.dataBox.getAllCookies().size() > 0) { if (allCookies != null && allCookies.size() > 0) {
accountCategory.addPreference(getPreference(R.string.remove_all_acc, null, R.drawable.ic_delete, preference -> { accountCategory.addPreference(getPreference(R.string.remove_all_acc, null, R.drawable.ic_delete, preference -> {
if (getContext() == null) return false; if (getContext() == null) return false;
new AlertDialog.Builder(getContext()) new AlertDialog.Builder(getContext())
@ -99,7 +93,7 @@ public class MorePreferencesFragment extends BasePreferencesFragment {
.setPositiveButton(R.string.yes, (dialog, which) -> { .setPositiveButton(R.string.yes, (dialog, which) -> {
CookieUtils.setupCookies("REMOVE"); CookieUtils.setupCookies("REMOVE");
shouldRecreate(); shouldRecreate();
Toast.makeText(requireContext(), R.string.logout_success, Toast.LENGTH_SHORT).show(); Toast.makeText(context, R.string.logout_success, Toast.LENGTH_SHORT).show();
settingsHelper.putString(Constants.COOKIE, ""); settingsHelper.putString(Constants.COOKIE, "");
}) })
.setNegativeButton(R.string.cancel, null) .setNegativeButton(R.string.cancel, null)
@ -108,7 +102,7 @@ public class MorePreferencesFragment extends BasePreferencesFragment {
})); }));
} }
final PreferenceCategory generalCategory = new PreferenceCategory(requireContext()); final PreferenceCategory generalCategory = new PreferenceCategory(context);
generalCategory.setTitle(R.string.pref_category_general); generalCategory.setTitle(R.string.pref_category_general);
generalCategory.setIconSpaceReserved(false); generalCategory.setIconSpaceReserved(false);
screen.addPreference(generalCategory); screen.addPreference(generalCategory);
@ -131,15 +125,15 @@ public class MorePreferencesFragment extends BasePreferencesFragment {
}); });
generalCategory.addPreference(aboutPreference); generalCategory.addPreference(aboutPreference);
final Preference divider = new Preference(requireContext()); final Preference divider = new Preference(context);
divider.setLayoutResource(R.layout.item_pref_divider); divider.setLayoutResource(R.layout.item_pref_divider);
screen.addPreference(divider); screen.addPreference(divider);
final Preference versionPreference = getPreference(R.string.version, final Preference versionPreference = getPreference(R.string.version,
BuildConfig.VERSION_NAME + " (" + BuildConfig.VERSION_CODE + ")", -1, preference -> { BuildConfig.VERSION_NAME + " (" + BuildConfig.VERSION_CODE + ")", -1, preference -> {
FlavorTown.updateCheck((AppCompatActivity) requireActivity(), true); FlavorTown.updateCheck((AppCompatActivity) requireActivity(), true);
return true; return true;
}); });
screen.addPreference(versionPreference); screen.addPreference(versionPreference);
final Preference reminderPreference = getPreference(R.string.reminder, R.string.reminder_summary, R.drawable.ic_warning, null); final Preference reminderPreference = getPreference(R.string.reminder, R.string.reminder_summary, R.drawable.ic_warning, null);
@ -155,7 +149,7 @@ public class MorePreferencesFragment extends BasePreferencesFragment {
CookieUtils.setupCookies(cookie); CookieUtils.setupCookies(cookie);
settingsHelper.putString(Constants.COOKIE, cookie); settingsHelper.putString(Constants.COOKIE, cookie);
// No use as the timing of show is unreliable // No use as the timing of show is unreliable
// Toast.makeText(requireContext(), R.string.login_success_loading_cookies, Toast.LENGTH_SHORT).show(); // Toast.makeText(getContext(), R.string.login_success_loading_cookies, Toast.LENGTH_SHORT).show();
// adds cookies to database for quick access // adds cookies to database for quick access
final String uid = CookieUtils.getUserIdFromCookie(cookie); final String uid = CookieUtils.getUserIdFromCookie(cookie);
@ -180,7 +174,6 @@ public class MorePreferencesFragment extends BasePreferencesFragment {
} }
} }
@NonNull
private AccountSwitcherPreference getAccountSwitcherPreference(final String cookie) { private AccountSwitcherPreference getAccountSwitcherPreference(final String cookie) {
final List<DataBox.CookieModel> allUsers = Utils.dataBox.getAllCookies(); final List<DataBox.CookieModel> allUsers = Utils.dataBox.getAllCookies();
if (getContext() != null && allUsers != null) { if (getContext() != null && allUsers != null) {
@ -239,7 +232,9 @@ public class MorePreferencesFragment extends BasePreferencesFragment {
}); });
} }
final AlertDialog finalDialog = accountSwitchDialog; final AlertDialog finalDialog = accountSwitchDialog;
return new AccountSwitcherPreference(requireContext(), cookie, v -> { final Context context = getContext();
if (context == null) return null;
return new AccountSwitcherPreference(context, cookie, v -> {
if (finalDialog == null) return; if (finalDialog == null) return;
finalDialog.show(); finalDialog.show();
}); });
@ -278,14 +273,12 @@ public class MorePreferencesFragment extends BasePreferencesFragment {
}); });
} }
@NonNull
private Preference getPreference(final int title, private Preference getPreference(final int title,
final int icon, final int icon,
final Preference.OnPreferenceClickListener clickListener) { final Preference.OnPreferenceClickListener clickListener) {
return getPreference(title, -1, icon, clickListener); return getPreference(title, -1, icon, clickListener);
} }
@NonNull
private Preference getPreference(final int title, private Preference getPreference(final int title,
final int summary, final int summary,
final int icon, final int icon,
@ -301,12 +294,13 @@ public class MorePreferencesFragment extends BasePreferencesFragment {
return getPreference(title, string, icon, clickListener); return getPreference(title, string, icon, clickListener);
} }
@NonNull
private Preference getPreference(final int title, private Preference getPreference(final int title,
final String summary, final String summary,
final int icon, final int icon,
final Preference.OnPreferenceClickListener clickListener) { final Preference.OnPreferenceClickListener clickListener) {
final Preference preference = new Preference(requireContext()); final Context context = getContext();
if (context == null) return null;
final Preference preference = new Preference(context);
if (icon <= 0) preference.setIconSpaceReserved(false); if (icon <= 0) preference.setIconSpaceReserved(false);
if (icon > 0) preference.setIcon(icon); if (icon > 0) preference.setIcon(icon);
preference.setTitle(title); preference.setTitle(title);

View File

@ -4,7 +4,6 @@ import android.content.Context;
import android.content.res.TypedArray; import android.content.res.TypedArray;
import android.view.View; import android.view.View;
import androidx.annotation.NonNull;
import androidx.appcompat.widget.AppCompatButton; import androidx.appcompat.widget.AppCompatButton;
import androidx.appcompat.widget.AppCompatTextView; import androidx.appcompat.widget.AppCompatTextView;
import androidx.fragment.app.FragmentActivity; import androidx.fragment.app.FragmentActivity;
@ -41,7 +40,9 @@ public class SettingsPreferencesFragment extends BasePreferencesFragment {
void setupPreferenceScreen(final PreferenceScreen screen) { void setupPreferenceScreen(final PreferenceScreen screen) {
final String cookie = settingsHelper.getString(Constants.COOKIE); final String cookie = settingsHelper.getString(Constants.COOKIE);
isLoggedIn = !TextUtils.isEmpty(cookie) && CookieUtils.getUserIdFromCookie(cookie) != null; isLoggedIn = !TextUtils.isEmpty(cookie) && CookieUtils.getUserIdFromCookie(cookie) != null;
final PreferenceCategory generalCategory = new PreferenceCategory(requireContext()); final Context context = getContext();
if (context == null) return;
final PreferenceCategory generalCategory = new PreferenceCategory(context);
screen.addPreference(generalCategory); screen.addPreference(generalCategory);
generalCategory.setTitle(R.string.pref_category_general); generalCategory.setTitle(R.string.pref_category_general);
generalCategory.setIconSpaceReserved(false); generalCategory.setIconSpaceReserved(false);
@ -50,21 +51,21 @@ public class SettingsPreferencesFragment extends BasePreferencesFragment {
generalCategory.addPreference(getAutoPlayVideosPreference()); generalCategory.addPreference(getAutoPlayVideosPreference());
generalCategory.addPreference(getAlwaysMuteVideosPreference()); generalCategory.addPreference(getAlwaysMuteVideosPreference());
final PreferenceCategory themeCategory = new PreferenceCategory(requireContext()); final PreferenceCategory themeCategory = new PreferenceCategory(context);
screen.addPreference(themeCategory); screen.addPreference(themeCategory);
themeCategory.setTitle(R.string.pref_category_theme); themeCategory.setTitle(R.string.pref_category_theme);
themeCategory.setIconSpaceReserved(false); themeCategory.setIconSpaceReserved(false);
themeCategory.addPreference(getThemePreference()); themeCategory.addPreference(getThemePreference());
themeCategory.addPreference(getAmoledThemePreference()); themeCategory.addPreference(getAmoledThemePreference());
final PreferenceCategory downloadsCategory = new PreferenceCategory(requireContext()); final PreferenceCategory downloadsCategory = new PreferenceCategory(context);
screen.addPreference(downloadsCategory); screen.addPreference(downloadsCategory);
downloadsCategory.setTitle(R.string.pref_category_downloads); downloadsCategory.setTitle(R.string.pref_category_downloads);
downloadsCategory.setIconSpaceReserved(false); downloadsCategory.setIconSpaceReserved(false);
downloadsCategory.addPreference(getDownloadUserFolderPreference()); downloadsCategory.addPreference(getDownloadUserFolderPreference());
downloadsCategory.addPreference(getSaveToCustomFolderPreference()); downloadsCategory.addPreference(getSaveToCustomFolderPreference());
final PreferenceCategory localeCategory = new PreferenceCategory(requireContext()); final PreferenceCategory localeCategory = new PreferenceCategory(context);
screen.addPreference(localeCategory); screen.addPreference(localeCategory);
localeCategory.setTitle(R.string.pref_category_locale); localeCategory.setTitle(R.string.pref_category_locale);
localeCategory.setIconSpaceReserved(false); localeCategory.setIconSpaceReserved(false);
@ -72,7 +73,7 @@ public class SettingsPreferencesFragment extends BasePreferencesFragment {
localeCategory.addPreference(getPostTimePreference()); localeCategory.addPreference(getPostTimePreference());
if (isLoggedIn) { if (isLoggedIn) {
final PreferenceCategory loggedInUsersPreferenceCategory = new PreferenceCategory(requireContext()); final PreferenceCategory loggedInUsersPreferenceCategory = new PreferenceCategory(context);
screen.addPreference(loggedInUsersPreferenceCategory); screen.addPreference(loggedInUsersPreferenceCategory);
loggedInUsersPreferenceCategory.setIconSpaceReserved(false); loggedInUsersPreferenceCategory.setIconSpaceReserved(false);
loggedInUsersPreferenceCategory.setTitle(R.string.login_settings); loggedInUsersPreferenceCategory.setTitle(R.string.login_settings);
@ -80,7 +81,7 @@ public class SettingsPreferencesFragment extends BasePreferencesFragment {
loggedInUsersPreferenceCategory.addPreference(getMarkDMSeenPreference()); loggedInUsersPreferenceCategory.addPreference(getMarkDMSeenPreference());
loggedInUsersPreferenceCategory.addPreference(getEnableActivityNotificationsPreference()); loggedInUsersPreferenceCategory.addPreference(getEnableActivityNotificationsPreference());
} else { } else {
final PreferenceCategory anonUsersPreferenceCategory = new PreferenceCategory(requireContext()); final PreferenceCategory anonUsersPreferenceCategory = new PreferenceCategory(context);
screen.addPreference(anonUsersPreferenceCategory); screen.addPreference(anonUsersPreferenceCategory);
anonUsersPreferenceCategory.setIconSpaceReserved(false); anonUsersPreferenceCategory.setIconSpaceReserved(false);
anonUsersPreferenceCategory.setTitle(R.string.anonymous_settings); anonUsersPreferenceCategory.setTitle(R.string.anonymous_settings);
@ -90,9 +91,10 @@ public class SettingsPreferencesFragment extends BasePreferencesFragment {
} }
@NonNull
private Preference getLanguagePreference() { private Preference getLanguagePreference() {
final ListPreference preference = new ListPreference(requireContext()); final Context context = getContext();
if (context == null) return null;
final ListPreference preference = new ListPreference(context);
preference.setSummaryProvider(ListPreference.SimpleSummaryProvider.getInstance()); preference.setSummaryProvider(ListPreference.SimpleSummaryProvider.getInstance());
final int length = getResources().getStringArray(R.array.languages).length; final int length = getResources().getStringArray(R.array.languages).length;
final String[] values = new String[length]; final String[] values = new String[length];
@ -113,7 +115,9 @@ public class SettingsPreferencesFragment extends BasePreferencesFragment {
} }
private Preference getDefaultTabPreference() { private Preference getDefaultTabPreference() {
final ListPreference preference = new ListPreference(requireContext()); final Context context = getContext();
if (context == null) return null;
final ListPreference preference = new ListPreference(context);
preference.setEnabled(isLoggedIn); preference.setEnabled(isLoggedIn);
preference.setSummaryProvider(ListPreference.SimpleSummaryProvider.getInstance()); preference.setSummaryProvider(ListPreference.SimpleSummaryProvider.getInstance());
final FragmentActivity activity = getActivity(); final FragmentActivity activity = getActivity();
@ -139,16 +143,19 @@ public class SettingsPreferencesFragment extends BasePreferencesFragment {
} }
private Preference getUpdateCheckPreference() { private Preference getUpdateCheckPreference() {
final SwitchPreferenceCompat preference = new SwitchPreferenceCompat(requireContext()); final Context context = getContext();
if (context == null) return null;
final SwitchPreferenceCompat preference = new SwitchPreferenceCompat(context);
preference.setKey(Constants.CHECK_UPDATES); preference.setKey(Constants.CHECK_UPDATES);
preference.setTitle(R.string.update_check); preference.setTitle(R.string.update_check);
preference.setIconSpaceReserved(false); preference.setIconSpaceReserved(false);
return preference; return preference;
} }
@NonNull
private Preference getThemePreference() { private Preference getThemePreference() {
final ListPreference preference = new ListPreference(requireContext()); final Context context = getContext();
if (context == null) return null;
final ListPreference preference = new ListPreference(context);
preference.setSummaryProvider(ListPreference.SimpleSummaryProvider.getInstance()); preference.setSummaryProvider(ListPreference.SimpleSummaryProvider.getInstance());
final int length = getResources().getStringArray(R.array.theme_presets).length; final int length = getResources().getStringArray(R.array.theme_presets).length;
final String[] values = new String[length]; final String[] values = new String[length];
@ -169,12 +176,14 @@ public class SettingsPreferencesFragment extends BasePreferencesFragment {
} }
private SwitchPreferenceCompat getAmoledThemePreference() { private SwitchPreferenceCompat getAmoledThemePreference() {
final SwitchPreferenceCompat preference = new SwitchPreferenceCompat(requireContext()); final Context context = getContext();
if (context == null) return null;
final SwitchPreferenceCompat preference = new SwitchPreferenceCompat(context);
preference.setKey(Constants.AMOLED_THEME); preference.setKey(Constants.AMOLED_THEME);
preference.setTitle(R.string.use_amoled_dark_theme); preference.setTitle(R.string.use_amoled_dark_theme);
preference.setIconSpaceReserved(false); preference.setIconSpaceReserved(false);
preference.setOnPreferenceChangeListener((preference1, newValue) -> { preference.setOnPreferenceChangeListener((preference1, newValue) -> {
final boolean isNight = Utils.isNight(requireContext(), settingsHelper.getThemeCode(true)); final boolean isNight = Utils.isNight(context, settingsHelper.getThemeCode(true));
if (isNight) shouldRecreate(); if (isNight) shouldRecreate();
return true; return true;
}); });
@ -182,7 +191,9 @@ public class SettingsPreferencesFragment extends BasePreferencesFragment {
} }
private Preference getDownloadUserFolderPreference() { private Preference getDownloadUserFolderPreference() {
final SwitchPreferenceCompat preference = new SwitchPreferenceCompat(requireContext()); final Context context = getContext();
if (context == null) return null;
final SwitchPreferenceCompat preference = new SwitchPreferenceCompat(context);
preference.setKey(Constants.DOWNLOAD_USER_FOLDER); preference.setKey(Constants.DOWNLOAD_USER_FOLDER);
preference.setTitle("Download to username folder"); preference.setTitle("Download to username folder");
preference.setSummary(R.string.download_user_folder); preference.setSummary(R.string.download_user_folder);
@ -191,19 +202,21 @@ public class SettingsPreferencesFragment extends BasePreferencesFragment {
} }
private Preference getSaveToCustomFolderPreference() { private Preference getSaveToCustomFolderPreference() {
return new SaveToCustomFolderPreference(requireContext(), (resultCallback) -> { final Context context = getContext();
new DirectoryChooser() if (context == null) return null;
.setInitialDirectory(settingsHelper.getString(FOLDER_PATH)) return new SaveToCustomFolderPreference(context, (resultCallback) -> new DirectoryChooser()
.setInteractionListener(path -> { .setInitialDirectory(settingsHelper.getString(FOLDER_PATH))
settingsHelper.putString(FOLDER_PATH, path); .setInteractionListener(path -> {
resultCallback.onResult(path); settingsHelper.putString(FOLDER_PATH, path);
}) resultCallback.onResult(path);
.show(getParentFragmentManager(), null); })
}); .show(getParentFragmentManager(), null));
} }
private Preference getAutoPlayVideosPreference() { private Preference getAutoPlayVideosPreference() {
final SwitchPreferenceCompat preference = new SwitchPreferenceCompat(requireContext()); final Context context = getContext();
if (context == null) return null;
final SwitchPreferenceCompat preference = new SwitchPreferenceCompat(context);
preference.setKey(Constants.AUTOPLAY_VIDEOS); preference.setKey(Constants.AUTOPLAY_VIDEOS);
preference.setTitle(R.string.post_viewer_autoplay_video); preference.setTitle(R.string.post_viewer_autoplay_video);
preference.setIconSpaceReserved(false); preference.setIconSpaceReserved(false);
@ -211,7 +224,9 @@ public class SettingsPreferencesFragment extends BasePreferencesFragment {
} }
private Preference getAlwaysMuteVideosPreference() { private Preference getAlwaysMuteVideosPreference() {
final SwitchPreferenceCompat preference = new SwitchPreferenceCompat(requireContext()); final Context context = getContext();
if (context == null) return null;
final SwitchPreferenceCompat preference = new SwitchPreferenceCompat(context);
preference.setKey(Constants.MUTED_VIDEOS); preference.setKey(Constants.MUTED_VIDEOS);
preference.setTitle(R.string.post_viewer_muted_autoplay); preference.setTitle(R.string.post_viewer_muted_autoplay);
preference.setIconSpaceReserved(false); preference.setIconSpaceReserved(false);
@ -219,7 +234,9 @@ public class SettingsPreferencesFragment extends BasePreferencesFragment {
} }
private Preference getMarkStoriesSeenPreference() { private Preference getMarkStoriesSeenPreference() {
final SwitchPreferenceCompat preference = new SwitchPreferenceCompat(requireContext()); final Context context = getContext();
if (context == null) return null;
final SwitchPreferenceCompat preference = new SwitchPreferenceCompat(context);
preference.setKey(Constants.MARK_AS_SEEN); preference.setKey(Constants.MARK_AS_SEEN);
preference.setTitle(R.string.mark_as_seen_setting); preference.setTitle(R.string.mark_as_seen_setting);
preference.setSummary(R.string.mark_as_seen_setting_summary); preference.setSummary(R.string.mark_as_seen_setting_summary);
@ -228,7 +245,9 @@ public class SettingsPreferencesFragment extends BasePreferencesFragment {
} }
private Preference getMarkDMSeenPreference() { private Preference getMarkDMSeenPreference() {
final SwitchPreferenceCompat preference = new SwitchPreferenceCompat(requireContext()); final Context context = getContext();
if (context == null) return null;
final SwitchPreferenceCompat preference = new SwitchPreferenceCompat(context);
preference.setKey(Constants.DM_MARK_AS_SEEN); preference.setKey(Constants.DM_MARK_AS_SEEN);
preference.setTitle(R.string.dm_mark_as_seen_setting); preference.setTitle(R.string.dm_mark_as_seen_setting);
preference.setSummary(R.string.dm_mark_as_seen_setting_summary); preference.setSummary(R.string.dm_mark_as_seen_setting_summary);
@ -237,7 +256,9 @@ public class SettingsPreferencesFragment extends BasePreferencesFragment {
} }
private Preference getEnableActivityNotificationsPreference() { private Preference getEnableActivityNotificationsPreference() {
final SwitchPreferenceCompat preference = new SwitchPreferenceCompat(requireContext()); final Context context = getContext();
if (context == null) return null;
final SwitchPreferenceCompat preference = new SwitchPreferenceCompat(context);
preference.setKey(Constants.CHECK_ACTIVITY); preference.setKey(Constants.CHECK_ACTIVITY);
preference.setTitle(R.string.activity_setting); preference.setTitle(R.string.activity_setting);
preference.setIconSpaceReserved(false); preference.setIconSpaceReserved(false);
@ -249,16 +270,19 @@ public class SettingsPreferencesFragment extends BasePreferencesFragment {
} }
private Preference getUseInstaDpPreference() { private Preference getUseInstaDpPreference() {
final SwitchPreferenceCompat preference = new SwitchPreferenceCompat(requireContext()); final Context context = getContext();
if (context == null) return null;
final SwitchPreferenceCompat preference = new SwitchPreferenceCompat(context);
preference.setKey(Constants.INSTADP); preference.setKey(Constants.INSTADP);
preference.setTitle(R.string.instadp_settings); preference.setTitle(R.string.instadp_settings);
preference.setIconSpaceReserved(false); preference.setIconSpaceReserved(false);
return preference; return preference;
} }
@NonNull
private Preference getStoryViewerPreference() { private Preference getStoryViewerPreference() {
final ListPreference preference = new ListPreference(requireContext()); final Context context = getContext();
if (context == null) return null;
final ListPreference preference = new ListPreference(context);
preference.setSummaryProvider(ListPreference.SimpleSummaryProvider.getInstance()); preference.setSummaryProvider(ListPreference.SimpleSummaryProvider.getInstance());
final int length = getResources().getStringArray(R.array.anonymous_story_viewer).length; final int length = getResources().getStringArray(R.array.anonymous_story_viewer).length;
final String[] values = new String[length]; final String[] values = new String[length];
@ -275,7 +299,9 @@ public class SettingsPreferencesFragment extends BasePreferencesFragment {
} }
private Preference getPostTimePreference() { private Preference getPostTimePreference() {
final Preference preference = new Preference(requireContext()); final Context context = getContext();
if (context == null) return null;
final Preference preference = new Preference(context);
preference.setTitle(R.string.time_settings); preference.setTitle(R.string.time_settings);
preference.setSummary(Utils.datetimeParser.format(new Date())); preference.setSummary(Utils.datetimeParser.format(new Date()));
preference.setIconSpaceReserved(false); preference.setIconSpaceReserved(false);

View File

@ -110,17 +110,16 @@ public final class Utils {
} }
} }
public static void copyText(final Context context, final CharSequence string) { public static void copyText(@NonNull final Context context, final CharSequence string) {
final boolean ctxNotNull = context != null; if (clipboardManager == null)
if (ctxNotNull && clipboardManager == null)
clipboardManager = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE); clipboardManager = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
int toastMessage = R.string.clipboard_error; int toastMessage = R.string.clipboard_error;
if (clipboardManager != null && ctxNotNull) { if (clipboardManager != null) {
clipboardManager.setPrimaryClip(ClipData.newPlainText(context.getString(R.string.app_name), string)); clipboardManager.setPrimaryClip(ClipData.newPlainText(context.getString(R.string.app_name), string));
toastMessage = R.string.clipboard_copied; toastMessage = R.string.clipboard_copied;
} }
if (ctxNotNull) Toast.makeText(context, toastMessage, Toast.LENGTH_SHORT).show(); Toast.makeText(context, toastMessage, Toast.LENGTH_SHORT).show();
} }
public static void showImportExportDialog(final Context context) { public static void showImportExportDialog(final Context context) {