1
0
mirror of https://github.com/KokaKiwi/BarInsta synced 2024-12-22 21:16:57 +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;
import android.app.Dialog;
import android.content.Context;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.graphics.drawable.Animatable;
@ -88,7 +89,9 @@ public class ProfilePicDialogFragment extends DialogFragment {
private void init() {
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();
return;
}
@ -140,21 +143,23 @@ public class ProfilePicDialogFragment extends DialogFragment {
private void downloadProfilePicture() {
if (url == null) return;
final File dir = new File(Environment.getExternalStorageDirectory(), "Download");
final Context context = getContext();
if (context == null) return;
if (dir.exists() || dir.mkdirs()) {
final File saveFile = new File(dir, name + '_' + System.currentTimeMillis() + ".jpg");
new DownloadAsync(requireContext(),
new DownloadAsync(context,
url,
saveFile,
result -> {
final int toastRes = result != null && result.exists() ?
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)
.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
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() {

View File

@ -1,5 +1,6 @@
package awais.instagrabber.fragments;
import android.content.Context;
import android.content.DialogInterface;
import android.content.res.Resources;
import android.os.AsyncTask;
@ -41,12 +42,12 @@ import awais.instagrabber.dialogs.ProfilePicDialogFragment;
import awais.instagrabber.interfaces.MentionClickListener;
import awais.instagrabber.models.CommentModel;
import awais.instagrabber.models.ProfileModel;
import awais.instagrabber.webservices.MediaService;
import awais.instagrabber.webservices.ServiceCallback;
import awais.instagrabber.utils.Constants;
import awais.instagrabber.utils.CookieUtils;
import awais.instagrabber.utils.TextUtils;
import awais.instagrabber.utils.Utils;
import awais.instagrabber.webservices.MediaService;
import awais.instagrabber.webservices.ServiceCallback;
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 Context context = getContext();
if (context == null) return;
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;
}
final ProfileModel profileModel = commentModel.getProfileModel();
@ -198,10 +201,10 @@ public final class CommentsViewerFragment extends Fragment implements SwipeRefre
.commit();
break;
case 2: // copy username
Utils.copyText(requireContext(), profileModel.getUsername());
Utils.copyText(context, profileModel.getUsername());
break;
case 3: // copy comment
Utils.copyText(requireContext(), commentModel.getText().toString());
Utils.copyText(context, commentModel.getText().toString());
break;
case 4: // reply to comment
final View focus = binding.rvComments.findViewWithTag(commentModel);
@ -213,7 +216,7 @@ public final class CommentsViewerFragment extends Fragment implements SwipeRefre
binding.commentText.postDelayed(new Runnable() {
@Override
public void run() {
imm = (InputMethodManager) requireContext().getSystemService(INPUT_METHOD_SERVICE);
imm = (InputMethodManager) context.getSystemService(INPUT_METHOD_SERVICE);
if (imm == null) return;
imm.showSoftInput(binding.commentText, 0);
}
@ -226,7 +229,7 @@ public final class CommentsViewerFragment extends Fragment implements SwipeRefre
public void onSuccess(final Boolean result) {
commentModel = null;
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;
}
onRefresh();
@ -235,7 +238,7 @@ public final class CommentsViewerFragment extends Fragment implements SwipeRefre
@Override
public void onFailure(final Throwable 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;
@ -245,7 +248,7 @@ public final class CommentsViewerFragment extends Fragment implements SwipeRefre
public void onSuccess(final Boolean result) {
commentModel = null;
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;
}
onRefresh();
@ -254,7 +257,7 @@ public final class CommentsViewerFragment extends Fragment implements SwipeRefre
@Override
public void onFailure(final Throwable 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;
@ -268,7 +271,7 @@ public final class CommentsViewerFragment extends Fragment implements SwipeRefre
public void onSuccess(final Boolean result) {
commentModel = null;
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;
}
onRefresh();
@ -277,7 +280,7 @@ public final class CommentsViewerFragment extends Fragment implements SwipeRefre
@Override
public void onFailure(final Throwable 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;
@ -327,7 +330,9 @@ public final class CommentsViewerFragment extends Fragment implements SwipeRefre
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)
.setItems(commentDialogList, profileDialogListener)
.setNegativeButton(R.string.cancel, null)
@ -346,8 +351,10 @@ public final class CommentsViewerFragment extends Fragment implements SwipeRefre
private final View.OnClickListener newCommentListener = v -> {
final Editable text = binding.commentText.getText();
final Context context = getContext();
if (context == null) return;
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;
}
final String userId = CookieUtils.getUserIdFromCookie(cookie);
@ -362,7 +369,7 @@ public final class CommentsViewerFragment extends Fragment implements SwipeRefre
commentModel = null;
binding.commentText.setText("");
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;
}
onRefresh();
@ -371,7 +378,7 @@ public final class CommentsViewerFragment extends Fragment implements SwipeRefre
@Override
public void onFailure(final Throwable 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;
import android.content.Context;
import android.content.res.ColorStateList;
import android.graphics.Typeface;
import android.os.AsyncTask;
@ -103,7 +104,9 @@ public class HashTagFragment extends Fragment {
if (postsAdapter == null || hashtag == null) {
return false;
}
DownloadUtils.batchDownload(requireContext(),
final Context context = getContext();
if (context == null) return false;
DownloadUtils.batchDownload(context,
hashtag,
DownloadMethod.DOWNLOAD_MAIN,
postsAdapter.getSelectedModels());
@ -180,7 +183,9 @@ public class HashTagFragment extends Fragment {
private void setupPosts() {
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.addItemDecoration(new GridSpacingItemDecoration(Utils.convertDpToPx(4)));
postsAdapter = new PostsAdapter((postModel, position) -> {
@ -238,11 +243,12 @@ public class HashTagFragment extends Fragment {
stopCurrentExecutor();
binding.swipeRefreshLayout.setRefreshing(true);
currentlyExecuting = new HashtagFetcher(hashtag.substring(1), result -> {
if (getContext() == null) return;
final Context context = getContext();
if (context == null) return;
hashtagModel = result;
binding.swipeRefreshLayout.setRefreshing(false);
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;
}
fetchPosts();
@ -256,6 +262,8 @@ public class HashTagFragment extends Fragment {
if (TextUtils.isEmpty(hashtag)) return;
currentlyExecuting = new PostsFetcher(hashtag.substring(1), PostItemType.HASHTAG, endCursor, postsFetchListener)
.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
final Context context = getContext();
if (context == null) return;
if (isLoggedIn) {
new iStoryStatusFetcher(hashtagModel.getName(), null, false, true, false, false, stories -> {
storyModels = stories;
@ -266,17 +274,17 @@ public class HashTagFragment extends Fragment {
binding.btnFollowTag.setText(hashtagModel.getFollowing() ? R.string.unfollow : R.string.follow);
ViewCompat.setBackgroundTintList(binding.btnFollowTag, ColorStateList.valueOf(
ContextCompat.getColor(requireContext(), hashtagModel.getFollowing()
? R.color.btn_purple_background
: R.color.btn_pink_background)));
ContextCompat.getColor(context, hashtagModel.getFollowing()
? R.color.btn_purple_background
: R.color.btn_pink_background)));
} else {
binding.btnFollowTag.setText(Utils.dataBox.getFavorite(hashtag) != null
? R.string.unfavorite_short
: R.string.favorite_short);
ViewCompat.setBackgroundTintList(binding.btnFollowTag, ColorStateList.valueOf(
ContextCompat.getColor(requireContext(), Utils.dataBox.getFavorite(hashtag) != null
? R.color.btn_purple_background
: R.color.btn_pink_background)));
ContextCompat.getColor(context, Utils.dataBox.getFavorite(hashtag) != null
? R.color.btn_purple_background
: R.color.btn_pink_background)));
}
binding.mainHashtagImage.setImageURI(hashtagModel.getSdProfilePic());
final String postCount = String.valueOf(hashtagModel.getPostCount());

View File

@ -1,5 +1,6 @@
package awais.instagrabber.fragments;
import android.content.Context;
import android.content.Intent;
import android.graphics.Typeface;
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.RecyclerLazyLoader;
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.models.LocationModel;
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.PostItemType;
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.viewmodels.PostsViewModel;
import awaisomereport.LogCollector;
import static awais.instagrabber.utils.Utils.logCollector;
@ -106,7 +107,9 @@ public class LocationFragment extends Fragment {
if (postsAdapter == null || locationId == null) {
return false;
}
DownloadUtils.batchDownload(requireContext(),
final Context context = getContext();
if (context == null) return false;
DownloadUtils.batchDownload(context,
locationId,
DownloadMethod.DOWNLOAD_MAIN,
postsAdapter.getSelectedModels());
@ -186,7 +189,9 @@ public class LocationFragment extends Fragment {
private void setupPosts() {
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.addItemDecoration(new GridSpacingItemDecoration(Utils.convertDpToPx(4)));
postsAdapter = new PostsAdapter((postModel, position) -> {
@ -247,7 +252,9 @@ public class LocationFragment extends Fragment {
locationModel = result;
binding.swipeRefreshLayout.setRefreshing(false);
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;
}
setTitle();

View File

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

View File

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

View File

@ -1,6 +1,7 @@
package awais.instagrabber.fragments;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.drawable.Animatable;
@ -180,17 +181,19 @@ public class StoryViewerFragment extends Fragment {
@Override
public boolean onOptionsItemSelected(@NonNull final MenuItem item) {
final Context context = getContext();
if (context == null) return false;
switch (item.getItemId()) {
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();
else
ActivityCompat.requestPermissions(requireActivity(), DownloadUtils.PERMS, 8020);
return true;
case R.id.action_dms:
final EditText input = new EditText(requireContext());
final EditText input = new EditText(context);
input.setHint(R.string.reply_hint);
new AlertDialog.Builder(requireContext())
new AlertDialog.Builder(context)
.setTitle(R.string.reply_story)
.setView(input)
.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);
broadcast.setOnTaskCompleteListener(result -> Toast.makeText(
requireContext(),
context,
result != null ? R.string.answered_story : R.string.downloader_unknown_error,
Toast.LENGTH_SHORT
).show());
@ -262,7 +265,9 @@ public class StoryViewerFragment extends Fragment {
private void setupStories() {
storiesViewModel = new ViewModelProvider(this).get(StoriesViewModel.class);
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) -> {
currentStory = model;
slidePos = position;
@ -294,6 +299,8 @@ public class StoryViewerFragment extends Fragment {
}
hasFeedStories = models != null && !models.isEmpty();
final List<?> finalModels = models;
final Context context = getContext();
if (context == null) return;
swipeEvent = isRightSwipe -> {
final List<StoryModel> storyModels = storiesViewModel.getList().getValue();
final int storiesLen = storyModels == null ? 0 : storyModels.size();
@ -307,7 +314,7 @@ public class StoryViewerFragment extends Fragment {
new SeenAction(cookie, currentStory).execute();
}
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;
}
final Object feedStoryModel = isRightSwipe
@ -315,7 +322,7 @@ public class StoryViewerFragment extends Fragment {
: finalModels.size() == index + 1 ? null : finalModels.get(index + 1);
if (feedStoryModel != null) {
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;
}
fetching = true;
@ -334,7 +341,7 @@ public class StoryViewerFragment extends Fragment {
currentStory = storyModels.get(slidePos);
refreshStory();
};
gestureDetector = new GestureDetectorCompat(requireContext(), new SwipeGestureListener(swipeEvent));
gestureDetector = new GestureDetectorCompat(context, new SwipeGestureListener(swipeEvent));
binding.playerView.setOnTouchListener((v, event) -> gestureDetector.onTouchEvent(event));
final GestureDetector.SimpleOnGestureListener simpleOnGestureListener = new GestureDetector.SimpleOnGestureListener() {
@Override
@ -382,22 +389,22 @@ public class StoryViewerFragment extends Fragment {
if (tag instanceof PollModel) {
poll = (PollModel) tag;
if (poll.getMyChoice() > -1) {
new AlertDialog.Builder(requireContext()).setTitle(R.string.voted_story_poll)
.setAdapter(new ArrayAdapter<>(requireContext(), android.R.layout.simple_list_item_1,
new String[]{
(poll.getMyChoice() == 0 ? "" : "") + poll
.getLeftChoice() + " (" + poll
.getLeftCount() + ")",
(poll.getMyChoice() == 1 ? "" : "") + poll
.getRightChoice() + " (" + poll
.getRightCount() + ")"
}), null)
.setPositiveButton(R.string.ok, null)
.show();
new AlertDialog.Builder(context).setTitle(R.string.voted_story_poll)
.setAdapter(new ArrayAdapter<>(context, android.R.layout.simple_list_item_1,
new String[]{
(poll.getMyChoice() == 0 ? "" : "") + poll
.getLeftChoice() + " (" + poll
.getLeftCount() + ")",
(poll.getMyChoice() == 1 ? "" : "") + poll
.getRightChoice() + " (" + poll
.getRightCount() + ")"
}), null)
.setPositiveButton(R.string.ok, null)
.show();
} else {
new AlertDialog.Builder(requireContext())
new AlertDialog.Builder(context)
.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.getRightChoice() + " (" + poll.getRightCount() + ")"
}), (d, w) -> {
@ -405,10 +412,10 @@ public class StoryViewerFragment extends Fragment {
new VoteAction(currentStory, poll, cookie, choice -> {
if (choice > -1) {
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;
}
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);
})
.setPositiveButton(R.string.cancel, null)
@ -416,24 +423,24 @@ public class StoryViewerFragment extends Fragment {
}
} else if (tag instanceof QuestionModel) {
question = (QuestionModel) tag;
final EditText input = new EditText(requireContext());
final EditText input = new EditText(context);
input.setHint(R.string.answer_hint);
new AlertDialog.Builder(requireContext())
new AlertDialog.Builder(context)
.setTitle(question.getQuestion())
.setView(input)
.setPositiveButton(R.string.ok, (d, w) -> new RespondAction(currentStory, question, cookie, 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
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()))
.setNegativeButton(R.string.cancel, null)
.show();
} else if (tag instanceof String[]) {
mentions = (String[]) tag;
new AlertDialog.Builder(requireContext())
new AlertDialog.Builder(context)
.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]);
})
.setPositiveButton(R.string.cancel, null)
@ -443,17 +450,17 @@ public class StoryViewerFragment extends Fragment {
for (int q = 0; q < choices.length; ++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())
.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))
new QuizAction(currentStory, quiz, cookie, choice -> {
if (choice > -1) {
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;
}
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);
})
.setPositiveButton(R.string.cancel, null)
@ -614,6 +621,8 @@ public class StoryViewerFragment extends Fragment {
private void downloadStory() {
int error = 0;
final Context context = getContext();
if (context == null) return;
if (currentStory != null) {
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()
+ 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
: 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);
} else error = 1;
} else error = 2;
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)
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() {
@ -688,11 +697,13 @@ public class StoryViewerFragment extends Fragment {
binding.imageViewer.setVisibility(View.GONE);
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);
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));
mediaSource.addEventListener(new Handler(), new MediaSourceEventListener() {
@Override

View File

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

View File

@ -1,5 +1,6 @@
package awais.instagrabber.fragments.directmessages;
import android.content.Context;
import android.content.DialogInterface;
import android.os.AsyncTask;
import android.os.Bundle;
@ -100,7 +101,9 @@ public class DirectMessageSettingsFragment extends Fragment implements SwipeRefr
final Object tag = v.getTag();
if (tag instanceof ProfileModel) {
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.dms_action_kick),
});
@ -113,33 +116,36 @@ public class DirectMessageSettingsFragment extends Fragment implements SwipeRefr
onRefresh();
}
};
new AlertDialog.Builder(requireContext())
new AlertDialog.Builder(context)
.setAdapter(adapter, clickListener)
.show();
}
};
}
@NonNull
@Override
public View onCreateView(@NonNull final LayoutInflater inflater,
final ViewGroup container,
final Bundle savedInstanceState) {
final FragmentDirectMessagesSettingsBinding binding = FragmentDirectMessagesSettingsBinding.inflate(inflater, container, false);
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
public boolean canScrollVertically() {
return false;
}
};
final LinearLayoutManager layoutManagerDos = new LinearLayoutManager(requireContext()) {
final LinearLayoutManager layoutManagerDos = new LinearLayoutManager(context) {
@Override
public boolean canScrollVertically() {
return false;
}
};
if (getArguments() == null) {
return null;
return root;
}
threadId = DirectMessageSettingsFragmentArgs.fromBundle(getArguments()).getThreadId();
threadTitle = DirectMessageSettingsFragmentArgs.fromBundle(getArguments()).getTitle();
@ -175,7 +181,7 @@ public class DirectMessageSettingsFragment extends Fragment implements SwipeRefr
});
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)
.setPositiveButton(R.string.yes,
(x, y) -> new ChangeSettings(titleText.getText().toString()).execute("leave"))
@ -250,8 +256,10 @@ public class DirectMessageSettingsFragment extends Fragment implements SwipeRefr
@Override
protected void onPostExecute(Void result) {
final Context context = getContext();
if (context == null) return;
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")) {
threadTitle = titleText.getText().toString();
titleSend.setVisibility(View.GONE);
@ -263,7 +271,7 @@ public class DirectMessageSettingsFragment extends Fragment implements SwipeRefr
} else {
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;
import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
@ -101,7 +102,9 @@ public class DirectMessageThreadFragment extends Fragment {
if (v == binding.commentSend) {
final String text = binding.commentText.getText().toString();
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;
}
sendText(text, null, false);
@ -123,8 +126,11 @@ public class DirectMessageThreadFragment extends Fragment {
@Override
public void onResult(final InboxThreadModel result) {
if (result == null && ("MINCURSOR".equals(cursor) || "MAXCURSOR".equals(cursor) || TextUtils.isEmpty(cursor)))
Toast.makeText(requireContext(), R.string.downloader_unknown_error, Toast.LENGTH_SHORT).show();
if (result == null && ("MINCURSOR".equals(cursor) || "MAXCURSOR".equals(cursor) || TextUtils.isEmpty(cursor))) {
final Context context = getContext();
if (context == null) return;
Toast.makeText(context, R.string.downloader_unknown_error, Toast.LENGTH_SHORT).show();
}
if (result != null) {
cursor = result.getOldestCursor();
@ -209,7 +215,9 @@ public class DirectMessageThreadFragment extends Fragment {
messageList.setHasFixedSize(true);
binding.commentSend.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);
messageList.setLayoutManager(layoutManager);
messageList.addOnScrollListener(new RecyclerLazyLoader(layoutManager, (page, totalItemsCount) -> {
@ -238,14 +246,14 @@ public class DirectMessageThreadFragment extends Fragment {
break;
case LINK:
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()));
startActivity(linkIntent);
break;
case TEXT:
case REEL_SHARE:
Utils.copyText(requireContext(), directItemModel.getText());
Toast.makeText(requireContext(), R.string.clipboard_copied, Toast.LENGTH_SHORT).show();
Utils.copyText(context, directItemModel.getText());
Toast.makeText(context, R.string.clipboard_copied, Toast.LENGTH_SHORT).show();
break;
case RAVEN_MEDIA:
case MEDIA:
@ -256,10 +264,10 @@ public class DirectMessageThreadFragment extends Fragment {
? selectedItem.getVideoUrl()
: selectedItem.getThumbUrl();
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 {
DownloadUtils.dmDownload(requireContext(), user.getUsername(), DownloadMethod.DOWNLOAD_DIRECT, selectedItem);
Toast.makeText(requireContext(), R.string.downloader_downloading_media, Toast.LENGTH_SHORT).show();
DownloadUtils.dmDownload(context, user.getUsername(), DownloadMethod.DOWNLOAD_DIRECT, selectedItem);
Toast.makeText(context, R.string.downloader_downloading_media, Toast.LENGTH_SHORT).show();
}
break;
case STORY_SHARE:
@ -275,7 +283,7 @@ public class DirectMessageThreadFragment extends Fragment {
// );
// sm.setVideoUrl(directItemModel.getReelShare().getMedia().getVideoUrl());
// 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_STORIES, sms)
// );
@ -292,10 +300,9 @@ public class DirectMessageThreadFragment extends Fragment {
}
} else if (which == 1) {
sendText(null, directItemModel.getItemId(), directItemModel.isLiked());
}
else if (which == 2) {
} else if (which == 2) {
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))
new ThreadAction().execute("delete", directItemModel.getItemId());
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)
};
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)
.show();
}
@ -435,7 +442,9 @@ public class DirectMessageThreadFragment extends Fragment {
}
broadcast(text != null ? textOptions : reactionOptions, result -> {
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;
}
if (text != null) {
@ -455,14 +464,16 @@ public class DirectMessageThreadFragment extends Fragment {
}
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);
Toast.makeText(requireContext(), R.string.uploading, Toast.LENGTH_SHORT).show();
Toast.makeText(context, R.string.uploading, Toast.LENGTH_SHORT).show();
// Upload Image
final ImageUploader imageUploader = new ImageUploader();
imageUploader.setOnTaskCompleteListener(response -> {
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) {
Log.e(TAG, response.getResponse().toString());
}
@ -484,7 +495,7 @@ public class DirectMessageThreadFragment extends Fragment {
final ImageUploadOptions options = ImageUploadOptions.builder(bitmap).build();
imageUploader.execute(options);
} 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);
}
}
@ -509,7 +520,6 @@ public class DirectMessageThreadFragment extends Fragment {
}
private void searchUsername(final String text) {
// startActivity(new Intent(requireContext(), ProfileViewer.class).putExtra(Constants.EXTRAS_USERNAME, text));
final NavDirections action = DirectMessageThreadFragmentDirections.actionGlobalProfileFragment("@" + text);
NavHostFragment.findNavController(this).navigate(action);
}

View File

@ -1,5 +1,6 @@
package awais.instagrabber.fragments.main;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
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.RecyclerLazyLoader;
import awais.instagrabber.databinding.FragmentDiscoverBinding;
import awais.instagrabber.utils.DownloadUtils;
import awais.instagrabber.viewmodels.DiscoverItemViewModel;
import awais.instagrabber.interfaces.FetchListener;
import awais.instagrabber.models.DiscoverItemModel;
import awais.instagrabber.models.DiscoverTopicModel;
import awais.instagrabber.models.enums.DownloadMethod;
import awais.instagrabber.utils.DownloadUtils;
import awais.instagrabber.utils.Utils;
import awais.instagrabber.viewmodels.DiscoverItemViewModel;
public class DiscoverFragment extends Fragment implements SwipeRefreshLayout.OnRefreshListener {
@ -70,8 +71,10 @@ public class DiscoverFragment extends Fragment implements SwipeRefreshLayout.OnR
if (result != null) {
topicIds = result.getIds();
rankToken = result.getToken();
final Context context = getContext();
if (context == null) return;
final ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<>(
requireContext(),
context,
android.R.layout.simple_spinner_dropdown_item,
result.getNames()
);
@ -87,7 +90,9 @@ public class DiscoverFragment extends Fragment implements SwipeRefreshLayout.OnR
public void onResult(final DiscoverItemModel[] result) {
if (result == null || result.length <= 0) {
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;
}
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) {
if (item.getItemId() == R.id.action_download) {
if (discoverAdapter == null) return false;
DownloadUtils.batchDownload(requireContext(),
final Context context = getContext();
if (context == null) return false;
DownloadUtils.batchDownload(context,
null,
DownloadMethod.DOWNLOAD_DISCOVER,
discoverAdapter.getSelectedModels());
@ -178,7 +185,9 @@ public class DiscoverFragment extends Fragment implements SwipeRefreshLayout.OnR
private void setupExplore() {
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.addItemDecoration(new GridSpacingItemDecoration(Utils.convertDpToPx(4)));
binding.discoverType.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {

View File

@ -1,5 +1,6 @@
package awais.instagrabber.fragments.main;
import android.content.Context;
import android.content.DialogInterface;
import android.net.Uri;
import android.os.AsyncTask;
@ -54,14 +55,14 @@ import awais.instagrabber.models.ProfileModel;
import awais.instagrabber.models.ViewerPostModel;
import awais.instagrabber.models.enums.DownloadMethod;
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.DownloadUtils;
import awais.instagrabber.utils.NumberUtils;
import awais.instagrabber.utils.Utils;
import awais.instagrabber.viewmodels.FeedStoriesViewModel;
import awais.instagrabber.viewmodels.FeedViewModel;
import awais.instagrabber.webservices.ServiceCallback;
import awais.instagrabber.webservices.StoriesService;
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 Context context = getContext();
if (context == null) return;
if (feedModel
.getItemType() != MediaItemType.MEDIA_TYPE_SLIDER || sliderItems == null || sliderItems.length == 1)
DownloadUtils.batchDownload(requireContext(),
DownloadUtils.batchDownload(context,
username,
DownloadMethod.DOWNLOAD_FEED,
Collections.singletonList(feedModel));
@ -257,14 +260,14 @@ public class FeedFragment extends Fragment implements SwipeRefreshLayout.OnRefre
postModels.add(sliderItems[0]);
}
if (postModels.size() > 0) {
DownloadUtils.batchDownload(requireContext(),
DownloadUtils.batchDownload(context,
username,
DownloadMethod.DOWNLOAD_FEED,
postModels);
}
};
new AlertDialog.Builder(requireContext())
new AlertDialog.Builder(context)
.setTitle(R.string.post_viewer_download_dialog_title).setPositiveButton(
R.string.post_viewer_download_current,
clickListener1)
@ -337,7 +340,9 @@ public class FeedFragment extends Fragment implements SwipeRefreshLayout.OnRefre
private void setupFeed() {
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.setHasFixedSize(true);
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);
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);
feedStoriesViewModel.getList().observe(fragmentActivity, feedStoriesAdapter::submitList);
fetchStories();

View File

@ -1,5 +1,6 @@
package awais.instagrabber.fragments.main;
import android.content.Context;
import android.content.DialogInterface;
import android.content.res.ColorStateList;
import android.graphics.Typeface;
@ -74,9 +75,6 @@ import awais.instagrabber.models.enums.PostItemType;
import awais.instagrabber.models.enums.StoryViewerChoice;
import awais.instagrabber.repositories.responses.FriendshipRepoChangeRootResponse;
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.CookieUtils;
import awais.instagrabber.utils.DataBox;
@ -85,6 +83,9 @@ import awais.instagrabber.utils.TextUtils;
import awais.instagrabber.utils.Utils;
import awais.instagrabber.viewmodels.HighlightsViewModel;
import awais.instagrabber.viewmodels.PostsViewModel;
import awais.instagrabber.webservices.AloService;
import awais.instagrabber.webservices.FriendshipService;
import awais.instagrabber.webservices.ServiceCallback;
import awaisomereport.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) {
return false;
}
DownloadUtils.batchDownload(requireContext(),
final Context context = getContext();
if (context == null) return false;
DownloadUtils.batchDownload(context,
username,
DownloadMethod.DOWNLOAD_MAIN,
postsAdapter.getSelectedModels());
@ -351,19 +354,21 @@ public class ProfileFragment extends Fragment implements SwipeRefreshLayout.OnRe
}
private void setProfileDetails() {
final Context context = getContext();
if (context == null) return;
if (profileModel == null) {
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;
}
binding.isVerified.setVisibility(profileModel.isVerified() ? View.VISIBLE : View.GONE);
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,
profileModel.getUsername(),
false,
false,
!isLoggedIn && settingsHelper.getString(Constants.STORY_VIEWER) == StoryViewerChoice.STORIESIG.getValue(),
!isLoggedIn && settingsHelper.getString(Constants.STORY_VIEWER).equals(StoryViewerChoice.STORIESIG.getValue()),
false,
result -> {
storyModels = result;
@ -372,19 +377,18 @@ public class ProfileFragment extends Fragment implements SwipeRefreshLayout.OnRe
}
}).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
new HighlightsFetcher(profileId,
!isLoggedIn && settingsHelper.getString(Constants.STORY_VIEWER) == StoryViewerChoice.STORIESIG.getValue(),
!isLoggedIn && settingsHelper.getString(Constants.STORY_VIEWER).equals(StoryViewerChoice.STORIESIG.getValue()),
result -> {
if (result != null) {
binding.highlightsList.setVisibility(View.VISIBLE);
highlightsViewModel.getList().postValue(result);
} else binding.highlightsList.setVisibility(View.GONE);
}).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");
aloService.getUserStory(profileId, profileModel.getUsername(), false, new ServiceCallback<List<StoryModel>>() {
@Override
public void onSuccess(final List<StoryModel> result){
public void onSuccess(final List<StoryModel> result) {
if (result != null && result.size() > 0) {
storyModels = result.toArray(storyModels);
binding.mainProfileImage.setStoriesBorder();
@ -406,7 +410,7 @@ public class ProfileFragment extends Fragment implements SwipeRefreshLayout.OnRe
binding.btnLiked.setVisibility(View.VISIBLE);
binding.btnSaved.setText(R.string.saved);
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 {
binding.btnTagged.setVisibility(View.GONE);
binding.btnSaved.setVisibility(View.GONE);
@ -415,54 +419,54 @@ public class ProfileFragment extends Fragment implements SwipeRefreshLayout.OnRe
if (profileModel.getFollowing()) {
binding.btnFollow.setText(R.string.unfollow);
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()) {
binding.btnFollow.setText(R.string.cancel);
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 {
binding.btnFollow.setText(R.string.follow);
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);
if (profileModel.getRestricted()) {
binding.btnRestrict.setText(R.string.unrestrict);
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 {
binding.btnRestrict.setText(R.string.restrict);
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.btnTagged.setVisibility(View.VISIBLE);
if (profileModel.getBlocked()) {
binding.btnBlock.setText(R.string.unblock);
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 {
binding.btnBlock.setText(R.string.block);
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 {
if (Utils.dataBox.getFavorite(username) != null) {
binding.btnFollow.setText(R.string.unfavorite_short);
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 {
binding.btnFollow.setText(R.string.favorite_short);
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);
if (!profileModel.isReallyPrivate()) {
binding.btnRestrict.setVisibility(View.VISIBLE);
binding.btnRestrict.setText(R.string.tagged);
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();
};
new AlertDialog.Builder(requireContext())
final Context context = getContext();
if (context == null) return;
new AlertDialog.Builder(context)
.setItems(options, profileDialogListener)
.setNeutralButton(R.string.cancel, null)
.show();
@ -742,7 +748,9 @@ public class ProfileFragment extends Fragment implements SwipeRefreshLayout.OnRe
private void setupPosts() {
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.addItemDecoration(new GridSpacingItemDecoration(Utils.convertDpToPx(4)));
postsAdapter = new PostsAdapter((postModel, position) -> {
@ -804,7 +812,9 @@ public class ProfileFragment extends Fragment implements SwipeRefreshLayout.OnRe
.actionProfileFragmentToStoryViewerFragment(position, model.getTitle(), false, null, null);
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.setAdapter(highlightsAdapter);
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.Intent;
import android.content.res.TypedArray;
import android.net.Uri;
import android.view.View;
import androidx.annotation.NonNull;
import androidx.appcompat.widget.AppCompatButton;
import androidx.appcompat.widget.AppCompatTextView;
import androidx.fragment.app.FragmentActivity;
import androidx.preference.ListPreference;
import androidx.preference.Preference;
import androidx.preference.PreferenceCategory;
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.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 {
private static AppCompatTextView customPathTextView;
@Override
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);
generalCategory.setTitle(R.string.pref_category_general);
generalCategory.setIconSpaceReserved(false);
@ -47,7 +26,7 @@ public class AboutFragment extends BasePreferencesFragment {
generalCategory.addPreference(getRepoPreference());
generalCategory.addPreference(getFeedbackPreference());
final PreferenceCategory thirdPartyCategory = new PreferenceCategory(requireContext());
final PreferenceCategory thirdPartyCategory = new PreferenceCategory(context);
screen.addPreference(thirdPartyCategory);
thirdPartyCategory.setTitle(R.string.about_category_3pt);
thirdPartyCategory.setSummary(R.string.about_category_3pt_summary);
@ -58,7 +37,7 @@ public class AboutFragment extends BasePreferencesFragment {
thirdPartyCategory.addPreference(getJsoupPreference());
thirdPartyCategory.addPreference(getRetrofitPreference());
final PreferenceCategory licenseCategory = new PreferenceCategory(requireContext());
final PreferenceCategory licenseCategory = new PreferenceCategory(context);
screen.addPreference(licenseCategory);
licenseCategory.setTitle(R.string.about_category_license);
licenseCategory.setIconSpaceReserved(false);
@ -67,7 +46,9 @@ public class AboutFragment extends BasePreferencesFragment {
}
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.setSummary(R.string.about_documentation_summary);
preference.setIconSpaceReserved(false);
@ -81,7 +62,9 @@ public class AboutFragment extends BasePreferencesFragment {
}
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.setSummary(R.string.about_repository_summary);
preference.setIconSpaceReserved(false);
@ -95,21 +78,25 @@ public class AboutFragment extends BasePreferencesFragment {
}
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.setSummary(R.string.about_feedback_summary);
preference.setIconSpaceReserved(false);
preference.setOnPreferenceClickListener(p -> {
final Intent intent = new Intent(Intent.ACTION_SENDTO);
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 preference;
}
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.setSummary("Copyright 2013 Square, Inc. Apache Version 2.0.");
preference.setIconSpaceReserved(false);
@ -123,7 +110,9 @@ public class AboutFragment extends BasePreferencesFragment {
}
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.setSummary("Copyright (c) 2009-2020 Jonathan Hedley. MIT License.");
preference.setIconSpaceReserved(false);
@ -137,7 +126,9 @@ public class AboutFragment extends BasePreferencesFragment {
}
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.setSummary("Copyright (c) Facebook, Inc. and its affiliates. MIT License.");
preference.setIconSpaceReserved(false);
@ -151,7 +142,9 @@ public class AboutFragment extends BasePreferencesFragment {
}
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.setSummary("Copyright (C) 2016 The Android Open Source Project. Apache Version 2.0.");
preference.setIconSpaceReserved(false);
@ -165,7 +158,9 @@ public class AboutFragment extends BasePreferencesFragment {
}
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.setEnabled(false);
preference.setIcon(R.drawable.ic_outline_info_24);
@ -174,7 +169,9 @@ public class AboutFragment extends BasePreferencesFragment {
}
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.setEnabled(false);
preference.setIcon(R.drawable.ic_warning);

View File

@ -1,5 +1,6 @@
package awais.instagrabber.fragments.settings;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
@ -19,7 +20,9 @@ public abstract class BasePreferencesFragment extends PreferenceFragmentCompat i
final PreferenceManager preferenceManager = getPreferenceManager();
preferenceManager.setSharedPreferencesName("settings");
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);
setPreferenceScreen(screen);
}

View File

@ -9,7 +9,6 @@ import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
@ -21,6 +20,7 @@ import androidx.preference.PreferenceCategory;
import androidx.preference.PreferenceScreen;
import androidx.preference.PreferenceViewHolder;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
@ -31,14 +31,14 @@ import awais.instagrabber.adapters.AccountSwitcherListAdapter;
import awais.instagrabber.adapters.AccountSwitcherListAdapter.OnAccountClickListener;
import awais.instagrabber.databinding.PrefAccountSwitcherBinding;
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.CookieUtils;
import awais.instagrabber.utils.DataBox;
import awais.instagrabber.utils.FlavorTown;
import awais.instagrabber.utils.TextUtils;
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.utils.Utils.settingsHelper;
@ -53,21 +53,15 @@ public class MorePreferencesFragment extends BasePreferencesFragment {
void setupPreferenceScreen(final PreferenceScreen screen) {
final String cookie = settingsHelper.getString(Constants.COOKIE);
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.setIconSpaceReserved(false);
screen.addPreference(accountCategory);
// To re-login, user can just add the same account back from account switcher dialog
// 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;
// }));
final ArrayList<DataBox.CookieModel> allCookies = Utils.dataBox.getAllCookies();
if (isLoggedIn) {
accountCategory.setSummary(R.string.account_hint);
accountCategory.addPreference(getAccountSwitcherPreference(cookie));
@ -75,12 +69,12 @@ public class MorePreferencesFragment extends BasePreferencesFragment {
if (getContext() == null) return false;
CookieUtils.setupCookies("LOGOUT");
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, "");
return true;
}));
} else {
if (Utils.dataBox.getAllCookies().size() > 0) {
if (allCookies != null && allCookies.size() > 0) {
accountCategory.addPreference(getAccountSwitcherPreference(null));
}
// 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 -> {
if (getContext() == null) return false;
new AlertDialog.Builder(getContext())
@ -99,7 +93,7 @@ public class MorePreferencesFragment extends BasePreferencesFragment {
.setPositiveButton(R.string.yes, (dialog, which) -> {
CookieUtils.setupCookies("REMOVE");
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, "");
})
.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.setIconSpaceReserved(false);
screen.addPreference(generalCategory);
@ -131,15 +125,15 @@ public class MorePreferencesFragment extends BasePreferencesFragment {
});
generalCategory.addPreference(aboutPreference);
final Preference divider = new Preference(requireContext());
final Preference divider = new Preference(context);
divider.setLayoutResource(R.layout.item_pref_divider);
screen.addPreference(divider);
final Preference versionPreference = getPreference(R.string.version,
BuildConfig.VERSION_NAME + " (" + BuildConfig.VERSION_CODE + ")", -1, preference -> {
FlavorTown.updateCheck((AppCompatActivity) requireActivity(), true);
return true;
});
BuildConfig.VERSION_NAME + " (" + BuildConfig.VERSION_CODE + ")", -1, preference -> {
FlavorTown.updateCheck((AppCompatActivity) requireActivity(), true);
return true;
});
screen.addPreference(versionPreference);
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);
settingsHelper.putString(Constants.COOKIE, cookie);
// 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
final String uid = CookieUtils.getUserIdFromCookie(cookie);
@ -180,7 +174,6 @@ public class MorePreferencesFragment extends BasePreferencesFragment {
}
}
@NonNull
private AccountSwitcherPreference getAccountSwitcherPreference(final String cookie) {
final List<DataBox.CookieModel> allUsers = Utils.dataBox.getAllCookies();
if (getContext() != null && allUsers != null) {
@ -239,7 +232,9 @@ public class MorePreferencesFragment extends BasePreferencesFragment {
});
}
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;
finalDialog.show();
});
@ -278,14 +273,12 @@ public class MorePreferencesFragment extends BasePreferencesFragment {
});
}
@NonNull
private Preference getPreference(final int title,
final int icon,
final Preference.OnPreferenceClickListener clickListener) {
return getPreference(title, -1, icon, clickListener);
}
@NonNull
private Preference getPreference(final int title,
final int summary,
final int icon,
@ -301,12 +294,13 @@ public class MorePreferencesFragment extends BasePreferencesFragment {
return getPreference(title, string, icon, clickListener);
}
@NonNull
private Preference getPreference(final int title,
final String summary,
final int icon,
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.setIcon(icon);
preference.setTitle(title);

View File

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

View File

@ -110,17 +110,16 @@ public final class Utils {
}
}
public static void copyText(final Context context, final CharSequence string) {
final boolean ctxNotNull = context != null;
if (ctxNotNull && clipboardManager == null)
public static void copyText(@NonNull final Context context, final CharSequence string) {
if (clipboardManager == null)
clipboardManager = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
int toastMessage = R.string.clipboard_error;
if (clipboardManager != null && ctxNotNull) {
if (clipboardManager != null) {
clipboardManager.setPrimaryClip(ClipData.newPlainText(context.getString(R.string.app_name), string));
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) {